linter.js 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018
  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. pkg = require("../../package.json"),
  17. astUtils = require("../shared/ast-utils"),
  18. {
  19. directivesPattern
  20. } = require("../shared/directives"),
  21. {
  22. Legacy: {
  23. ConfigOps,
  24. ConfigValidator,
  25. environments: BuiltInEnvironments
  26. }
  27. } = require("@eslint/eslintrc/universal"),
  28. Traverser = require("../shared/traverser"),
  29. { SourceCode } = require("../source-code"),
  30. CodePathAnalyzer = require("./code-path-analysis/code-path-analyzer"),
  31. applyDisableDirectives = require("./apply-disable-directives"),
  32. ConfigCommentParser = require("./config-comment-parser"),
  33. NodeEventGenerator = require("./node-event-generator"),
  34. createReportTranslator = require("./report-translator"),
  35. Rules = require("./rules"),
  36. createEmitter = require("./safe-emitter"),
  37. SourceCodeFixer = require("./source-code-fixer"),
  38. timing = require("./timing"),
  39. ruleReplacements = require("../../conf/replacements.json");
  40. const { getRuleFromConfig } = require("../config/flat-config-helpers");
  41. const { FlatConfigArray } = require("../config/flat-config-array");
  42. const debug = require("debug")("eslint:linter");
  43. const MAX_AUTOFIX_PASSES = 10;
  44. const DEFAULT_PARSER_NAME = "espree";
  45. const DEFAULT_ECMA_VERSION = 5;
  46. const commentParser = new ConfigCommentParser();
  47. const DEFAULT_ERROR_LOC = { start: { line: 1, column: 0 }, end: { line: 1, column: 1 } };
  48. const parserSymbol = Symbol.for("eslint.RuleTester.parser");
  49. const globals = require("../../conf/globals");
  50. //------------------------------------------------------------------------------
  51. // Typedefs
  52. //------------------------------------------------------------------------------
  53. /** @typedef {InstanceType<import("../cli-engine/config-array").ConfigArray>} ConfigArray */
  54. /** @typedef {InstanceType<import("../cli-engine/config-array").ExtractedConfig>} ExtractedConfig */
  55. /** @typedef {import("../shared/types").ConfigData} ConfigData */
  56. /** @typedef {import("../shared/types").Environment} Environment */
  57. /** @typedef {import("../shared/types").GlobalConf} GlobalConf */
  58. /** @typedef {import("../shared/types").LintMessage} LintMessage */
  59. /** @typedef {import("../shared/types").SuppressedLintMessage} SuppressedLintMessage */
  60. /** @typedef {import("../shared/types").ParserOptions} ParserOptions */
  61. /** @typedef {import("../shared/types").LanguageOptions} LanguageOptions */
  62. /** @typedef {import("../shared/types").Processor} Processor */
  63. /** @typedef {import("../shared/types").Rule} Rule */
  64. /* eslint-disable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/4#issuecomment-778805577 */
  65. /**
  66. * @template T
  67. * @typedef {{ [P in keyof T]-?: T[P] }} Required
  68. */
  69. /* eslint-enable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/4#issuecomment-778805577 */
  70. /**
  71. * @typedef {Object} DisableDirective
  72. * @property {("disable"|"enable"|"disable-line"|"disable-next-line")} type Type of directive
  73. * @property {number} line The line number
  74. * @property {number} column The column number
  75. * @property {(string|null)} ruleId The rule ID
  76. * @property {string} justification The justification of directive
  77. */
  78. /**
  79. * The private data for `Linter` instance.
  80. * @typedef {Object} LinterInternalSlots
  81. * @property {ConfigArray|null} lastConfigArray The `ConfigArray` instance that the last `verify()` call used.
  82. * @property {SourceCode|null} lastSourceCode The `SourceCode` instance that the last `verify()` call used.
  83. * @property {SuppressedLintMessage[]} lastSuppressedMessages The `SuppressedLintMessage[]` instance that the last `verify()` call produced.
  84. * @property {Map<string, Parser>} parserMap The loaded parsers.
  85. * @property {Rules} ruleMap The loaded rules.
  86. */
  87. /**
  88. * @typedef {Object} VerifyOptions
  89. * @property {boolean} [allowInlineConfig] Allow/disallow inline comments' ability
  90. * to change config once it is set. Defaults to true if not supplied.
  91. * Useful if you want to validate JS without comments overriding rules.
  92. * @property {boolean} [disableFixes] if `true` then the linter doesn't make `fix`
  93. * properties into the lint result.
  94. * @property {string} [filename] the filename of the source code.
  95. * @property {boolean | "off" | "warn" | "error"} [reportUnusedDisableDirectives] Adds reported errors for
  96. * unused `eslint-disable` directives.
  97. */
  98. /**
  99. * @typedef {Object} ProcessorOptions
  100. * @property {(filename:string, text:string) => boolean} [filterCodeBlock] the
  101. * predicate function that selects adopt code blocks.
  102. * @property {Processor.postprocess} [postprocess] postprocessor for report
  103. * messages. If provided, this should accept an array of the message lists
  104. * for each code block returned from the preprocessor, apply a mapping to
  105. * the messages as appropriate, and return a one-dimensional array of
  106. * messages.
  107. * @property {Processor.preprocess} [preprocess] preprocessor for source text.
  108. * If provided, this should accept a string of source text, and return an
  109. * array of code blocks to lint.
  110. */
  111. /**
  112. * @typedef {Object} FixOptions
  113. * @property {boolean | ((message: LintMessage) => boolean)} [fix] Determines
  114. * whether fixes should be applied.
  115. */
  116. /**
  117. * @typedef {Object} InternalOptions
  118. * @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.
  119. * @property {"off" | "warn" | "error"} reportUnusedDisableDirectives (boolean values were normalized)
  120. */
  121. //------------------------------------------------------------------------------
  122. // Helpers
  123. //------------------------------------------------------------------------------
  124. /**
  125. * Determines if a given object is Espree.
  126. * @param {Object} parser The parser to check.
  127. * @returns {boolean} True if the parser is Espree or false if not.
  128. */
  129. function isEspree(parser) {
  130. return !!(parser === espree || parser[parserSymbol] === espree);
  131. }
  132. /**
  133. * Retrieves globals for the given ecmaVersion.
  134. * @param {number} ecmaVersion The version to retrieve globals for.
  135. * @returns {Object} The globals for the given ecmaVersion.
  136. */
  137. function getGlobalsForEcmaVersion(ecmaVersion) {
  138. switch (ecmaVersion) {
  139. case 3:
  140. return globals.es3;
  141. case 5:
  142. return globals.es5;
  143. default:
  144. if (ecmaVersion < 2015) {
  145. return globals[`es${ecmaVersion + 2009}`];
  146. }
  147. return globals[`es${ecmaVersion}`];
  148. }
  149. }
  150. /**
  151. * Ensures that variables representing built-in properties of the Global Object,
  152. * and any globals declared by special block comments, are present in the global
  153. * scope.
  154. * @param {Scope} globalScope The global scope.
  155. * @param {Object} configGlobals The globals declared in configuration
  156. * @param {{exportedVariables: Object, enabledGlobals: Object}} commentDirectives Directives from comment configuration
  157. * @returns {void}
  158. */
  159. function addDeclaredGlobals(globalScope, configGlobals, { exportedVariables, enabledGlobals }) {
  160. // Define configured global variables.
  161. for (const id of new Set([...Object.keys(configGlobals), ...Object.keys(enabledGlobals)])) {
  162. /*
  163. * `ConfigOps.normalizeConfigGlobal` will throw an error if a configured global value is invalid. However, these errors would
  164. * typically be caught when validating a config anyway (validity for inline global comments is checked separately).
  165. */
  166. const configValue = configGlobals[id] === void 0 ? void 0 : ConfigOps.normalizeConfigGlobal(configGlobals[id]);
  167. const commentValue = enabledGlobals[id] && enabledGlobals[id].value;
  168. const value = commentValue || configValue;
  169. const sourceComments = enabledGlobals[id] && enabledGlobals[id].comments;
  170. if (value === "off") {
  171. continue;
  172. }
  173. let variable = globalScope.set.get(id);
  174. if (!variable) {
  175. variable = new eslintScope.Variable(id, globalScope);
  176. globalScope.variables.push(variable);
  177. globalScope.set.set(id, variable);
  178. }
  179. variable.eslintImplicitGlobalSetting = configValue;
  180. variable.eslintExplicitGlobal = sourceComments !== void 0;
  181. variable.eslintExplicitGlobalComments = sourceComments;
  182. variable.writeable = (value === "writable");
  183. }
  184. // mark all exported variables as such
  185. Object.keys(exportedVariables).forEach(name => {
  186. const variable = globalScope.set.get(name);
  187. if (variable) {
  188. variable.eslintUsed = true;
  189. variable.eslintExported = true;
  190. }
  191. });
  192. /*
  193. * "through" contains all references which definitions cannot be found.
  194. * Since we augment the global scope using configuration, we need to update
  195. * references and remove the ones that were added by configuration.
  196. */
  197. globalScope.through = globalScope.through.filter(reference => {
  198. const name = reference.identifier.name;
  199. const variable = globalScope.set.get(name);
  200. if (variable) {
  201. /*
  202. * Links the variable and the reference.
  203. * And this reference is removed from `Scope#through`.
  204. */
  205. reference.resolved = variable;
  206. variable.references.push(reference);
  207. return false;
  208. }
  209. return true;
  210. });
  211. }
  212. /**
  213. * creates a missing-rule message.
  214. * @param {string} ruleId the ruleId to create
  215. * @returns {string} created error message
  216. * @private
  217. */
  218. function createMissingRuleMessage(ruleId) {
  219. return Object.prototype.hasOwnProperty.call(ruleReplacements.rules, ruleId)
  220. ? `Rule '${ruleId}' was removed and replaced by: ${ruleReplacements.rules[ruleId].join(", ")}`
  221. : `Definition for rule '${ruleId}' was not found.`;
  222. }
  223. /**
  224. * creates a linting problem
  225. * @param {Object} options to create linting error
  226. * @param {string} [options.ruleId] the ruleId to report
  227. * @param {Object} [options.loc] the loc to report
  228. * @param {string} [options.message] the error message to report
  229. * @param {string} [options.severity] the error message to report
  230. * @returns {LintMessage} created problem, returns a missing-rule problem if only provided ruleId.
  231. * @private
  232. */
  233. function createLintingProblem(options) {
  234. const {
  235. ruleId = null,
  236. loc = DEFAULT_ERROR_LOC,
  237. message = createMissingRuleMessage(options.ruleId),
  238. severity = 2
  239. } = options;
  240. return {
  241. ruleId,
  242. message,
  243. line: loc.start.line,
  244. column: loc.start.column + 1,
  245. endLine: loc.end.line,
  246. endColumn: loc.end.column + 1,
  247. severity,
  248. nodeType: null
  249. };
  250. }
  251. /**
  252. * Creates a collection of disable directives from a comment
  253. * @param {Object} options to create disable directives
  254. * @param {("disable"|"enable"|"disable-line"|"disable-next-line")} options.type The type of directive comment
  255. * @param {token} options.commentToken The Comment token
  256. * @param {string} options.value The value after the directive in the comment
  257. * comment specified no specific rules, so it applies to all rules (e.g. `eslint-disable`)
  258. * @param {string} options.justification The justification of the directive
  259. * @param {function(string): {create: Function}} options.ruleMapper A map from rule IDs to defined rules
  260. * @returns {Object} Directives and problems from the comment
  261. */
  262. function createDisableDirectives(options) {
  263. const { commentToken, type, value, justification, ruleMapper } = options;
  264. const ruleIds = Object.keys(commentParser.parseListConfig(value));
  265. const directiveRules = ruleIds.length ? ruleIds : [null];
  266. const result = {
  267. directives: [], // valid disable directives
  268. directiveProblems: [] // problems in directives
  269. };
  270. const parentComment = { commentToken, ruleIds };
  271. for (const ruleId of directiveRules) {
  272. // push to directives, if the rule is defined(including null, e.g. /*eslint enable*/)
  273. if (ruleId === null || !!ruleMapper(ruleId)) {
  274. if (type === "disable-next-line") {
  275. result.directives.push({
  276. parentComment,
  277. type,
  278. line: commentToken.loc.end.line,
  279. column: commentToken.loc.end.column + 1,
  280. ruleId,
  281. justification
  282. });
  283. } else {
  284. result.directives.push({
  285. parentComment,
  286. type,
  287. line: commentToken.loc.start.line,
  288. column: commentToken.loc.start.column + 1,
  289. ruleId,
  290. justification
  291. });
  292. }
  293. } else {
  294. result.directiveProblems.push(createLintingProblem({ ruleId, loc: commentToken.loc }));
  295. }
  296. }
  297. return result;
  298. }
  299. /**
  300. * Extract the directive and the justification from a given directive comment and trim them.
  301. * @param {string} value The comment text to extract.
  302. * @returns {{directivePart: string, justificationPart: string}} The extracted directive and justification.
  303. */
  304. function extractDirectiveComment(value) {
  305. const match = /\s-{2,}\s/u.exec(value);
  306. if (!match) {
  307. return { directivePart: value.trim(), justificationPart: "" };
  308. }
  309. const directive = value.slice(0, match.index).trim();
  310. const justification = value.slice(match.index + match[0].length).trim();
  311. return { directivePart: directive, justificationPart: justification };
  312. }
  313. /**
  314. * Parses comments in file to extract file-specific config of rules, globals
  315. * and environments and merges them with global config; also code blocks
  316. * where reporting is disabled or enabled and merges them with reporting config.
  317. * @param {ASTNode} ast The top node of the AST.
  318. * @param {function(string): {create: Function}} ruleMapper A map from rule IDs to defined rules
  319. * @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.
  320. * @returns {{configuredRules: Object, enabledGlobals: {value:string,comment:Token}[], exportedVariables: Object, problems: LintMessage[], disableDirectives: DisableDirective[]}}
  321. * A collection of the directive comments that were found, along with any problems that occurred when parsing
  322. */
  323. function getDirectiveComments(ast, ruleMapper, warnInlineConfig) {
  324. const configuredRules = {};
  325. const enabledGlobals = Object.create(null);
  326. const exportedVariables = {};
  327. const problems = [];
  328. const disableDirectives = [];
  329. const validator = new ConfigValidator({
  330. builtInRules: Rules
  331. });
  332. ast.comments.filter(token => token.type !== "Shebang").forEach(comment => {
  333. const { directivePart, justificationPart } = extractDirectiveComment(comment.value);
  334. const match = directivesPattern.exec(directivePart);
  335. if (!match) {
  336. return;
  337. }
  338. const directiveText = match[1];
  339. const lineCommentSupported = /^eslint-disable-(next-)?line$/u.test(directiveText);
  340. if (comment.type === "Line" && !lineCommentSupported) {
  341. return;
  342. }
  343. if (warnInlineConfig) {
  344. const kind = comment.type === "Block" ? `/*${directiveText}*/` : `//${directiveText}`;
  345. problems.push(createLintingProblem({
  346. ruleId: null,
  347. message: `'${kind}' has no effect because you have 'noInlineConfig' setting in ${warnInlineConfig}.`,
  348. loc: comment.loc,
  349. severity: 1
  350. }));
  351. return;
  352. }
  353. if (directiveText === "eslint-disable-line" && comment.loc.start.line !== comment.loc.end.line) {
  354. const message = `${directiveText} comment should not span multiple lines.`;
  355. problems.push(createLintingProblem({
  356. ruleId: null,
  357. message,
  358. loc: comment.loc
  359. }));
  360. return;
  361. }
  362. const directiveValue = directivePart.slice(match.index + directiveText.length);
  363. switch (directiveText) {
  364. case "eslint-disable":
  365. case "eslint-enable":
  366. case "eslint-disable-next-line":
  367. case "eslint-disable-line": {
  368. const directiveType = directiveText.slice("eslint-".length);
  369. const options = { commentToken: comment, type: directiveType, value: directiveValue, justification: justificationPart, ruleMapper };
  370. const { directives, directiveProblems } = createDisableDirectives(options);
  371. disableDirectives.push(...directives);
  372. problems.push(...directiveProblems);
  373. break;
  374. }
  375. case "exported":
  376. Object.assign(exportedVariables, commentParser.parseStringConfig(directiveValue, comment));
  377. break;
  378. case "globals":
  379. case "global":
  380. for (const [id, { value }] of Object.entries(commentParser.parseStringConfig(directiveValue, comment))) {
  381. let normalizedValue;
  382. try {
  383. normalizedValue = ConfigOps.normalizeConfigGlobal(value);
  384. } catch (err) {
  385. problems.push(createLintingProblem({
  386. ruleId: null,
  387. loc: comment.loc,
  388. message: err.message
  389. }));
  390. continue;
  391. }
  392. if (enabledGlobals[id]) {
  393. enabledGlobals[id].comments.push(comment);
  394. enabledGlobals[id].value = normalizedValue;
  395. } else {
  396. enabledGlobals[id] = {
  397. comments: [comment],
  398. value: normalizedValue
  399. };
  400. }
  401. }
  402. break;
  403. case "eslint": {
  404. const parseResult = commentParser.parseJsonConfig(directiveValue, comment.loc);
  405. if (parseResult.success) {
  406. Object.keys(parseResult.config).forEach(name => {
  407. const rule = ruleMapper(name);
  408. const ruleValue = parseResult.config[name];
  409. if (!rule) {
  410. problems.push(createLintingProblem({ ruleId: name, loc: comment.loc }));
  411. return;
  412. }
  413. try {
  414. validator.validateRuleOptions(rule, name, ruleValue);
  415. } catch (err) {
  416. problems.push(createLintingProblem({
  417. ruleId: name,
  418. message: err.message,
  419. loc: comment.loc
  420. }));
  421. // do not apply the config, if found invalid options.
  422. return;
  423. }
  424. configuredRules[name] = ruleValue;
  425. });
  426. } else {
  427. problems.push(parseResult.error);
  428. }
  429. break;
  430. }
  431. // no default
  432. }
  433. });
  434. return {
  435. configuredRules,
  436. enabledGlobals,
  437. exportedVariables,
  438. problems,
  439. disableDirectives
  440. };
  441. }
  442. /**
  443. * Normalize ECMAScript version from the initial config
  444. * @param {Parser} parser The parser which uses this options.
  445. * @param {number} ecmaVersion ECMAScript version from the initial config
  446. * @returns {number} normalized ECMAScript version
  447. */
  448. function normalizeEcmaVersion(parser, ecmaVersion) {
  449. if (isEspree(parser)) {
  450. if (ecmaVersion === "latest") {
  451. return espree.latestEcmaVersion;
  452. }
  453. }
  454. /*
  455. * Calculate ECMAScript edition number from official year version starting with
  456. * ES2015, which corresponds with ES6 (or a difference of 2009).
  457. */
  458. return ecmaVersion >= 2015 ? ecmaVersion - 2009 : ecmaVersion;
  459. }
  460. /**
  461. * Normalize ECMAScript version from the initial config into languageOptions (year)
  462. * format.
  463. * @param {any} [ecmaVersion] ECMAScript version from the initial config
  464. * @returns {number} normalized ECMAScript version
  465. */
  466. function normalizeEcmaVersionForLanguageOptions(ecmaVersion) {
  467. switch (ecmaVersion) {
  468. case 3:
  469. return 3;
  470. // void 0 = no ecmaVersion specified so use the default
  471. case 5:
  472. case void 0:
  473. return 5;
  474. default:
  475. if (typeof ecmaVersion === "number") {
  476. return ecmaVersion >= 2015 ? ecmaVersion : ecmaVersion + 2009;
  477. }
  478. }
  479. /*
  480. * We default to the latest supported ecmaVersion for everything else.
  481. * Remember, this is for languageOptions.ecmaVersion, which sets the version
  482. * that is used for a number of processes inside of ESLint. It's normally
  483. * safe to assume people want the latest unless otherwise specified.
  484. */
  485. return espree.latestEcmaVersion + 2009;
  486. }
  487. const eslintEnvPattern = /\/\*\s*eslint-env\s(.+?)(?:\*\/|$)/gsu;
  488. /**
  489. * Checks whether or not there is a comment which has "eslint-env *" in a given text.
  490. * @param {string} text A source code text to check.
  491. * @returns {Object|null} A result of parseListConfig() with "eslint-env *" comment.
  492. */
  493. function findEslintEnv(text) {
  494. let match, retv;
  495. eslintEnvPattern.lastIndex = 0;
  496. while ((match = eslintEnvPattern.exec(text)) !== null) {
  497. if (match[0].endsWith("*/")) {
  498. retv = Object.assign(
  499. retv || {},
  500. commentParser.parseListConfig(extractDirectiveComment(match[1]).directivePart)
  501. );
  502. }
  503. }
  504. return retv;
  505. }
  506. /**
  507. * Convert "/path/to/<text>" to "<text>".
  508. * `CLIEngine#executeOnText()` method gives "/path/to/<text>" if the filename
  509. * was omitted because `configArray.extractConfig()` requires an absolute path.
  510. * But the linter should pass `<text>` to `RuleContext#filename` in that
  511. * case.
  512. * Also, code blocks can have their virtual filename. If the parent filename was
  513. * `<text>`, the virtual filename is `<text>/0_foo.js` or something like (i.e.,
  514. * it's not an absolute path).
  515. * @param {string} filename The filename to normalize.
  516. * @returns {string} The normalized filename.
  517. */
  518. function normalizeFilename(filename) {
  519. const parts = filename.split(path.sep);
  520. const index = parts.lastIndexOf("<text>");
  521. return index === -1 ? filename : parts.slice(index).join(path.sep);
  522. }
  523. /**
  524. * Normalizes the possible options for `linter.verify` and `linter.verifyAndFix` to a
  525. * consistent shape.
  526. * @param {VerifyOptions} providedOptions Options
  527. * @param {ConfigData} config Config.
  528. * @returns {Required<VerifyOptions> & InternalOptions} Normalized options
  529. */
  530. function normalizeVerifyOptions(providedOptions, config) {
  531. const linterOptions = config.linterOptions || config;
  532. // .noInlineConfig for eslintrc, .linterOptions.noInlineConfig for flat
  533. const disableInlineConfig = linterOptions.noInlineConfig === true;
  534. const ignoreInlineConfig = providedOptions.allowInlineConfig === false;
  535. const configNameOfNoInlineConfig = config.configNameOfNoInlineConfig
  536. ? ` (${config.configNameOfNoInlineConfig})`
  537. : "";
  538. let reportUnusedDisableDirectives = providedOptions.reportUnusedDisableDirectives;
  539. if (typeof reportUnusedDisableDirectives === "boolean") {
  540. reportUnusedDisableDirectives = reportUnusedDisableDirectives ? "error" : "off";
  541. }
  542. if (typeof reportUnusedDisableDirectives !== "string") {
  543. reportUnusedDisableDirectives =
  544. linterOptions.reportUnusedDisableDirectives
  545. ? "warn" : "off";
  546. }
  547. return {
  548. filename: normalizeFilename(providedOptions.filename || "<input>"),
  549. allowInlineConfig: !ignoreInlineConfig,
  550. warnInlineConfig: disableInlineConfig && !ignoreInlineConfig
  551. ? `your config${configNameOfNoInlineConfig}`
  552. : null,
  553. reportUnusedDisableDirectives,
  554. disableFixes: Boolean(providedOptions.disableFixes)
  555. };
  556. }
  557. /**
  558. * Combines the provided parserOptions with the options from environments
  559. * @param {Parser} parser The parser which uses this options.
  560. * @param {ParserOptions} providedOptions The provided 'parserOptions' key in a config
  561. * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments
  562. * @returns {ParserOptions} Resulting parser options after merge
  563. */
  564. function resolveParserOptions(parser, providedOptions, enabledEnvironments) {
  565. const parserOptionsFromEnv = enabledEnvironments
  566. .filter(env => env.parserOptions)
  567. .reduce((parserOptions, env) => merge(parserOptions, env.parserOptions), {});
  568. const mergedParserOptions = merge(parserOptionsFromEnv, providedOptions || {});
  569. const isModule = mergedParserOptions.sourceType === "module";
  570. if (isModule) {
  571. /*
  572. * can't have global return inside of modules
  573. * TODO: espree validate parserOptions.globalReturn when sourceType is setting to module.(@aladdin-add)
  574. */
  575. mergedParserOptions.ecmaFeatures = Object.assign({}, mergedParserOptions.ecmaFeatures, { globalReturn: false });
  576. }
  577. mergedParserOptions.ecmaVersion = normalizeEcmaVersion(parser, mergedParserOptions.ecmaVersion);
  578. return mergedParserOptions;
  579. }
  580. /**
  581. * Converts parserOptions to languageOptions for backwards compatibility with eslintrc.
  582. * @param {ConfigData} config Config object.
  583. * @param {Object} config.globals Global variable definitions.
  584. * @param {Parser} config.parser The parser to use.
  585. * @param {ParserOptions} config.parserOptions The parserOptions to use.
  586. * @returns {LanguageOptions} The languageOptions equivalent.
  587. */
  588. function createLanguageOptions({ globals: configuredGlobals, parser, parserOptions }) {
  589. const {
  590. ecmaVersion,
  591. sourceType
  592. } = parserOptions;
  593. return {
  594. globals: configuredGlobals,
  595. ecmaVersion: normalizeEcmaVersionForLanguageOptions(ecmaVersion),
  596. sourceType,
  597. parser,
  598. parserOptions
  599. };
  600. }
  601. /**
  602. * Combines the provided globals object with the globals from environments
  603. * @param {Record<string, GlobalConf>} providedGlobals The 'globals' key in a config
  604. * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments
  605. * @returns {Record<string, GlobalConf>} The resolved globals object
  606. */
  607. function resolveGlobals(providedGlobals, enabledEnvironments) {
  608. return Object.assign(
  609. {},
  610. ...enabledEnvironments.filter(env => env.globals).map(env => env.globals),
  611. providedGlobals
  612. );
  613. }
  614. /**
  615. * Strips Unicode BOM from a given text.
  616. * @param {string} text A text to strip.
  617. * @returns {string} The stripped text.
  618. */
  619. function stripUnicodeBOM(text) {
  620. /*
  621. * Check Unicode BOM.
  622. * In JavaScript, string data is stored as UTF-16, so BOM is 0xFEFF.
  623. * http://www.ecma-international.org/ecma-262/6.0/#sec-unicode-format-control-characters
  624. */
  625. if (text.charCodeAt(0) === 0xFEFF) {
  626. return text.slice(1);
  627. }
  628. return text;
  629. }
  630. /**
  631. * Get the options for a rule (not including severity), if any
  632. * @param {Array|number} ruleConfig rule configuration
  633. * @returns {Array} of rule options, empty Array if none
  634. */
  635. function getRuleOptions(ruleConfig) {
  636. if (Array.isArray(ruleConfig)) {
  637. return ruleConfig.slice(1);
  638. }
  639. return [];
  640. }
  641. /**
  642. * Analyze scope of the given AST.
  643. * @param {ASTNode} ast The `Program` node to analyze.
  644. * @param {LanguageOptions} languageOptions The parser options.
  645. * @param {Record<string, string[]>} visitorKeys The visitor keys.
  646. * @returns {ScopeManager} The analysis result.
  647. */
  648. function analyzeScope(ast, languageOptions, visitorKeys) {
  649. const parserOptions = languageOptions.parserOptions;
  650. const ecmaFeatures = parserOptions.ecmaFeatures || {};
  651. const ecmaVersion = languageOptions.ecmaVersion || DEFAULT_ECMA_VERSION;
  652. return eslintScope.analyze(ast, {
  653. ignoreEval: true,
  654. nodejsScope: ecmaFeatures.globalReturn,
  655. impliedStrict: ecmaFeatures.impliedStrict,
  656. ecmaVersion: typeof ecmaVersion === "number" ? ecmaVersion : 6,
  657. sourceType: languageOptions.sourceType || "script",
  658. childVisitorKeys: visitorKeys || evk.KEYS,
  659. fallback: Traverser.getKeys
  660. });
  661. }
  662. /**
  663. * Parses text into an AST. Moved out here because the try-catch prevents
  664. * optimization of functions, so it's best to keep the try-catch as isolated
  665. * as possible
  666. * @param {string} text The text to parse.
  667. * @param {LanguageOptions} languageOptions Options to pass to the parser
  668. * @param {string} filePath The path to the file being parsed.
  669. * @returns {{success: false, error: LintMessage}|{success: true, sourceCode: SourceCode}}
  670. * An object containing the AST and parser services if parsing was successful, or the error if parsing failed
  671. * @private
  672. */
  673. function parse(text, languageOptions, filePath) {
  674. const textToParse = stripUnicodeBOM(text).replace(astUtils.shebangPattern, (match, captured) => `//${captured}`);
  675. const { ecmaVersion, sourceType, parser } = languageOptions;
  676. const parserOptions = Object.assign(
  677. { ecmaVersion, sourceType },
  678. languageOptions.parserOptions,
  679. {
  680. loc: true,
  681. range: true,
  682. raw: true,
  683. tokens: true,
  684. comment: true,
  685. eslintVisitorKeys: true,
  686. eslintScopeManager: true,
  687. filePath
  688. }
  689. );
  690. /*
  691. * Check for parsing errors first. If there's a parsing error, nothing
  692. * else can happen. However, a parsing error does not throw an error
  693. * from this method - it's just considered a fatal error message, a
  694. * problem that ESLint identified just like any other.
  695. */
  696. try {
  697. debug("Parsing:", filePath);
  698. const parseResult = (typeof parser.parseForESLint === "function")
  699. ? parser.parseForESLint(textToParse, parserOptions)
  700. : { ast: parser.parse(textToParse, parserOptions) };
  701. debug("Parsing successful:", filePath);
  702. const ast = parseResult.ast;
  703. const parserServices = parseResult.services || {};
  704. const visitorKeys = parseResult.visitorKeys || evk.KEYS;
  705. debug("Scope analysis:", filePath);
  706. const scopeManager = parseResult.scopeManager || analyzeScope(ast, languageOptions, visitorKeys);
  707. debug("Scope analysis successful:", filePath);
  708. return {
  709. success: true,
  710. /*
  711. * Save all values that `parseForESLint()` returned.
  712. * If a `SourceCode` object is given as the first parameter instead of source code text,
  713. * linter skips the parsing process and reuses the source code object.
  714. * In that case, linter needs all the values that `parseForESLint()` returned.
  715. */
  716. sourceCode: new SourceCode({
  717. text,
  718. ast,
  719. parserServices,
  720. scopeManager,
  721. visitorKeys
  722. })
  723. };
  724. } catch (ex) {
  725. // If the message includes a leading line number, strip it:
  726. const message = `Parsing error: ${ex.message.replace(/^line \d+:/iu, "").trim()}`;
  727. debug("%s\n%s", message, ex.stack);
  728. return {
  729. success: false,
  730. error: {
  731. ruleId: null,
  732. fatal: true,
  733. severity: 2,
  734. message,
  735. line: ex.lineNumber,
  736. column: ex.column,
  737. nodeType: null
  738. }
  739. };
  740. }
  741. }
  742. /**
  743. * Runs a rule, and gets its listeners
  744. * @param {Rule} rule A normalized rule with a `create` method
  745. * @param {Context} ruleContext The context that should be passed to the rule
  746. * @throws {any} Any error during the rule's `create`
  747. * @returns {Object} A map of selector listeners provided by the rule
  748. */
  749. function createRuleListeners(rule, ruleContext) {
  750. try {
  751. return rule.create(ruleContext);
  752. } catch (ex) {
  753. ex.message = `Error while loading rule '${ruleContext.id}': ${ex.message}`;
  754. throw ex;
  755. }
  756. }
  757. // methods that exist on SourceCode object
  758. const DEPRECATED_SOURCECODE_PASSTHROUGHS = {
  759. getSource: "getText",
  760. getSourceLines: "getLines",
  761. getAllComments: "getAllComments",
  762. getNodeByRangeIndex: "getNodeByRangeIndex",
  763. getComments: "getComments",
  764. getCommentsBefore: "getCommentsBefore",
  765. getCommentsAfter: "getCommentsAfter",
  766. getCommentsInside: "getCommentsInside",
  767. getJSDocComment: "getJSDocComment",
  768. getFirstToken: "getFirstToken",
  769. getFirstTokens: "getFirstTokens",
  770. getLastToken: "getLastToken",
  771. getLastTokens: "getLastTokens",
  772. getTokenAfter: "getTokenAfter",
  773. getTokenBefore: "getTokenBefore",
  774. getTokenByRangeStart: "getTokenByRangeStart",
  775. getTokens: "getTokens",
  776. getTokensAfter: "getTokensAfter",
  777. getTokensBefore: "getTokensBefore",
  778. getTokensBetween: "getTokensBetween"
  779. };
  780. const BASE_TRAVERSAL_CONTEXT = Object.freeze(
  781. Object.keys(DEPRECATED_SOURCECODE_PASSTHROUGHS).reduce(
  782. (contextInfo, methodName) =>
  783. Object.assign(contextInfo, {
  784. [methodName](...args) {
  785. return this.sourceCode[DEPRECATED_SOURCECODE_PASSTHROUGHS[methodName]](...args);
  786. }
  787. }),
  788. {}
  789. )
  790. );
  791. /**
  792. * Runs the given rules on the given SourceCode object
  793. * @param {SourceCode} sourceCode A SourceCode object for the given text
  794. * @param {Object} configuredRules The rules configuration
  795. * @param {function(string): Rule} ruleMapper A mapper function from rule names to rules
  796. * @param {string | undefined} parserName The name of the parser in the config
  797. * @param {LanguageOptions} languageOptions The options for parsing the code.
  798. * @param {Object} settings The settings that were enabled in the config
  799. * @param {string} filename The reported filename of the code
  800. * @param {boolean} disableFixes If true, it doesn't make `fix` properties.
  801. * @param {string | undefined} cwd cwd of the cli
  802. * @param {string} physicalFilename The full path of the file on disk without any code block information
  803. * @returns {LintMessage[]} An array of reported problems
  804. */
  805. function runRules(sourceCode, configuredRules, ruleMapper, parserName, languageOptions, settings, filename, disableFixes, cwd, physicalFilename) {
  806. const emitter = createEmitter();
  807. const nodeQueue = [];
  808. let currentNode = sourceCode.ast;
  809. Traverser.traverse(sourceCode.ast, {
  810. enter(node, parent) {
  811. node.parent = parent;
  812. nodeQueue.push({ isEntering: true, node });
  813. },
  814. leave(node) {
  815. nodeQueue.push({ isEntering: false, node });
  816. },
  817. visitorKeys: sourceCode.visitorKeys
  818. });
  819. /*
  820. * Create a frozen object with the ruleContext properties and methods that are shared by all rules.
  821. * All rule contexts will inherit from this object. This avoids the performance penalty of copying all the
  822. * properties once for each rule.
  823. */
  824. const sharedTraversalContext = Object.freeze(
  825. Object.assign(
  826. Object.create(BASE_TRAVERSAL_CONTEXT),
  827. {
  828. getAncestors: () => sourceCode.getAncestors(currentNode),
  829. getDeclaredVariables: node => sourceCode.getDeclaredVariables(node),
  830. getCwd: () => cwd,
  831. cwd,
  832. getFilename: () => filename,
  833. filename,
  834. getPhysicalFilename: () => physicalFilename || filename,
  835. physicalFilename: physicalFilename || filename,
  836. getScope: () => sourceCode.getScope(currentNode),
  837. getSourceCode: () => sourceCode,
  838. sourceCode,
  839. markVariableAsUsed: name => sourceCode.markVariableAsUsed(name, currentNode),
  840. parserOptions: {
  841. ...languageOptions.parserOptions
  842. },
  843. parserPath: parserName,
  844. languageOptions,
  845. parserServices: sourceCode.parserServices,
  846. settings
  847. }
  848. )
  849. );
  850. const lintingProblems = [];
  851. Object.keys(configuredRules).forEach(ruleId => {
  852. const severity = ConfigOps.getRuleSeverity(configuredRules[ruleId]);
  853. // not load disabled rules
  854. if (severity === 0) {
  855. return;
  856. }
  857. const rule = ruleMapper(ruleId);
  858. if (!rule) {
  859. lintingProblems.push(createLintingProblem({ ruleId }));
  860. return;
  861. }
  862. const messageIds = rule.meta && rule.meta.messages;
  863. let reportTranslator = null;
  864. const ruleContext = Object.freeze(
  865. Object.assign(
  866. Object.create(sharedTraversalContext),
  867. {
  868. id: ruleId,
  869. options: getRuleOptions(configuredRules[ruleId]),
  870. report(...args) {
  871. /*
  872. * Create a report translator lazily.
  873. * In a vast majority of cases, any given rule reports zero errors on a given
  874. * piece of code. Creating a translator lazily avoids the performance cost of
  875. * creating a new translator function for each rule that usually doesn't get
  876. * called.
  877. *
  878. * Using lazy report translators improves end-to-end performance by about 3%
  879. * with Node 8.4.0.
  880. */
  881. if (reportTranslator === null) {
  882. reportTranslator = createReportTranslator({
  883. ruleId,
  884. severity,
  885. sourceCode,
  886. messageIds,
  887. disableFixes
  888. });
  889. }
  890. const problem = reportTranslator(...args);
  891. if (problem.fix && !(rule.meta && rule.meta.fixable)) {
  892. throw new Error("Fixable rules must set the `meta.fixable` property to \"code\" or \"whitespace\".");
  893. }
  894. if (problem.suggestions && !(rule.meta && rule.meta.hasSuggestions === true)) {
  895. if (rule.meta && rule.meta.docs && typeof rule.meta.docs.suggestion !== "undefined") {
  896. // Encourage migration from the former property name.
  897. throw new Error("Rules with suggestions must set the `meta.hasSuggestions` property to `true`. `meta.docs.suggestion` is ignored by ESLint.");
  898. }
  899. throw new Error("Rules with suggestions must set the `meta.hasSuggestions` property to `true`.");
  900. }
  901. lintingProblems.push(problem);
  902. }
  903. }
  904. )
  905. );
  906. const ruleListeners = timing.enabled ? timing.time(ruleId, createRuleListeners)(rule, ruleContext) : createRuleListeners(rule, ruleContext);
  907. /**
  908. * Include `ruleId` in error logs
  909. * @param {Function} ruleListener A rule method that listens for a node.
  910. * @returns {Function} ruleListener wrapped in error handler
  911. */
  912. function addRuleErrorHandler(ruleListener) {
  913. return function ruleErrorHandler(...listenerArgs) {
  914. try {
  915. return ruleListener(...listenerArgs);
  916. } catch (e) {
  917. e.ruleId = ruleId;
  918. throw e;
  919. }
  920. };
  921. }
  922. if (typeof ruleListeners === "undefined" || ruleListeners === null) {
  923. throw new Error(`The create() function for rule '${ruleId}' did not return an object.`);
  924. }
  925. // add all the selectors from the rule as listeners
  926. Object.keys(ruleListeners).forEach(selector => {
  927. const ruleListener = timing.enabled
  928. ? timing.time(ruleId, ruleListeners[selector])
  929. : ruleListeners[selector];
  930. emitter.on(
  931. selector,
  932. addRuleErrorHandler(ruleListener)
  933. );
  934. });
  935. });
  936. // only run code path analyzer if the top level node is "Program", skip otherwise
  937. const eventGenerator = nodeQueue[0].node.type === "Program"
  938. ? new CodePathAnalyzer(new NodeEventGenerator(emitter, { visitorKeys: sourceCode.visitorKeys, fallback: Traverser.getKeys }))
  939. : new NodeEventGenerator(emitter, { visitorKeys: sourceCode.visitorKeys, fallback: Traverser.getKeys });
  940. nodeQueue.forEach(traversalInfo => {
  941. currentNode = traversalInfo.node;
  942. try {
  943. if (traversalInfo.isEntering) {
  944. eventGenerator.enterNode(currentNode);
  945. } else {
  946. eventGenerator.leaveNode(currentNode);
  947. }
  948. } catch (err) {
  949. err.currentNode = currentNode;
  950. throw err;
  951. }
  952. });
  953. return lintingProblems;
  954. }
  955. /**
  956. * Ensure the source code to be a string.
  957. * @param {string|SourceCode} textOrSourceCode The text or source code object.
  958. * @returns {string} The source code text.
  959. */
  960. function ensureText(textOrSourceCode) {
  961. if (typeof textOrSourceCode === "object") {
  962. const { hasBOM, text } = textOrSourceCode;
  963. const bom = hasBOM ? "\uFEFF" : "";
  964. return bom + text;
  965. }
  966. return String(textOrSourceCode);
  967. }
  968. /**
  969. * Get an environment.
  970. * @param {LinterInternalSlots} slots The internal slots of Linter.
  971. * @param {string} envId The environment ID to get.
  972. * @returns {Environment|null} The environment.
  973. */
  974. function getEnv(slots, envId) {
  975. return (
  976. (slots.lastConfigArray && slots.lastConfigArray.pluginEnvironments.get(envId)) ||
  977. BuiltInEnvironments.get(envId) ||
  978. null
  979. );
  980. }
  981. /**
  982. * Get a rule.
  983. * @param {LinterInternalSlots} slots The internal slots of Linter.
  984. * @param {string} ruleId The rule ID to get.
  985. * @returns {Rule|null} The rule.
  986. */
  987. function getRule(slots, ruleId) {
  988. return (
  989. (slots.lastConfigArray && slots.lastConfigArray.pluginRules.get(ruleId)) ||
  990. slots.ruleMap.get(ruleId)
  991. );
  992. }
  993. /**
  994. * Normalize the value of the cwd
  995. * @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.
  996. * @returns {string | undefined} normalized cwd
  997. */
  998. function normalizeCwd(cwd) {
  999. if (cwd) {
  1000. return cwd;
  1001. }
  1002. if (typeof process === "object") {
  1003. return process.cwd();
  1004. }
  1005. // It's more explicit to assign the undefined
  1006. // eslint-disable-next-line no-undefined -- Consistently returning a value
  1007. return undefined;
  1008. }
  1009. /**
  1010. * The map to store private data.
  1011. * @type {WeakMap<Linter, LinterInternalSlots>}
  1012. */
  1013. const internalSlotsMap = new WeakMap();
  1014. /**
  1015. * Throws an error when the given linter is in flat config mode.
  1016. * @param {Linter} linter The linter to check.
  1017. * @returns {void}
  1018. * @throws {Error} If the linter is in flat config mode.
  1019. */
  1020. function assertEslintrcConfig(linter) {
  1021. const { configType } = internalSlotsMap.get(linter);
  1022. if (configType === "flat") {
  1023. throw new Error("This method cannot be used with flat config. Add your entries directly into the config array.");
  1024. }
  1025. }
  1026. //------------------------------------------------------------------------------
  1027. // Public Interface
  1028. //------------------------------------------------------------------------------
  1029. /**
  1030. * Object that is responsible for verifying JavaScript text
  1031. * @name Linter
  1032. */
  1033. class Linter {
  1034. /**
  1035. * Initialize the Linter.
  1036. * @param {Object} [config] the config object
  1037. * @param {string} [config.cwd] path to a directory that should be considered as the current working directory, can be undefined.
  1038. * @param {"flat"|"eslintrc"} [config.configType="eslintrc"] the type of config used.
  1039. */
  1040. constructor({ cwd, configType } = {}) {
  1041. internalSlotsMap.set(this, {
  1042. cwd: normalizeCwd(cwd),
  1043. lastConfigArray: null,
  1044. lastSourceCode: null,
  1045. lastSuppressedMessages: [],
  1046. configType, // TODO: Remove after flat config conversion
  1047. parserMap: new Map([["espree", espree]]),
  1048. ruleMap: new Rules()
  1049. });
  1050. this.version = pkg.version;
  1051. }
  1052. /**
  1053. * Getter for package version.
  1054. * @static
  1055. * @returns {string} The version from package.json.
  1056. */
  1057. static get version() {
  1058. return pkg.version;
  1059. }
  1060. /**
  1061. * Same as linter.verify, except without support for processors.
  1062. * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
  1063. * @param {ConfigData} providedConfig An ESLintConfig instance to configure everything.
  1064. * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked.
  1065. * @throws {Error} If during rule execution.
  1066. * @returns {(LintMessage|SuppressedLintMessage)[]} The results as an array of messages or an empty array if no messages.
  1067. */
  1068. _verifyWithoutProcessors(textOrSourceCode, providedConfig, providedOptions) {
  1069. const slots = internalSlotsMap.get(this);
  1070. const config = providedConfig || {};
  1071. const options = normalizeVerifyOptions(providedOptions, config);
  1072. let text;
  1073. // evaluate arguments
  1074. if (typeof textOrSourceCode === "string") {
  1075. slots.lastSourceCode = null;
  1076. text = textOrSourceCode;
  1077. } else {
  1078. slots.lastSourceCode = textOrSourceCode;
  1079. text = textOrSourceCode.text;
  1080. }
  1081. // Resolve parser.
  1082. let parserName = DEFAULT_PARSER_NAME;
  1083. let parser = espree;
  1084. if (typeof config.parser === "object" && config.parser !== null) {
  1085. parserName = config.parser.filePath;
  1086. parser = config.parser.definition;
  1087. } else if (typeof config.parser === "string") {
  1088. if (!slots.parserMap.has(config.parser)) {
  1089. return [{
  1090. ruleId: null,
  1091. fatal: true,
  1092. severity: 2,
  1093. message: `Configured parser '${config.parser}' was not found.`,
  1094. line: 0,
  1095. column: 0,
  1096. nodeType: null
  1097. }];
  1098. }
  1099. parserName = config.parser;
  1100. parser = slots.parserMap.get(config.parser);
  1101. }
  1102. // search and apply "eslint-env *".
  1103. const envInFile = options.allowInlineConfig && !options.warnInlineConfig
  1104. ? findEslintEnv(text)
  1105. : {};
  1106. const resolvedEnvConfig = Object.assign({ builtin: true }, config.env, envInFile);
  1107. const enabledEnvs = Object.keys(resolvedEnvConfig)
  1108. .filter(envName => resolvedEnvConfig[envName])
  1109. .map(envName => getEnv(slots, envName))
  1110. .filter(env => env);
  1111. const parserOptions = resolveParserOptions(parser, config.parserOptions || {}, enabledEnvs);
  1112. const configuredGlobals = resolveGlobals(config.globals || {}, enabledEnvs);
  1113. const settings = config.settings || {};
  1114. const languageOptions = createLanguageOptions({
  1115. globals: config.globals,
  1116. parser,
  1117. parserOptions
  1118. });
  1119. if (!slots.lastSourceCode) {
  1120. const parseResult = parse(
  1121. text,
  1122. languageOptions,
  1123. options.filename
  1124. );
  1125. if (!parseResult.success) {
  1126. return [parseResult.error];
  1127. }
  1128. slots.lastSourceCode = parseResult.sourceCode;
  1129. } else {
  1130. /*
  1131. * If the given source code object as the first argument does not have scopeManager, analyze the scope.
  1132. * This is for backward compatibility (SourceCode is frozen so it cannot rebind).
  1133. */
  1134. if (!slots.lastSourceCode.scopeManager) {
  1135. slots.lastSourceCode = new SourceCode({
  1136. text: slots.lastSourceCode.text,
  1137. ast: slots.lastSourceCode.ast,
  1138. parserServices: slots.lastSourceCode.parserServices,
  1139. visitorKeys: slots.lastSourceCode.visitorKeys,
  1140. scopeManager: analyzeScope(slots.lastSourceCode.ast, languageOptions)
  1141. });
  1142. }
  1143. }
  1144. const sourceCode = slots.lastSourceCode;
  1145. const commentDirectives = options.allowInlineConfig
  1146. ? getDirectiveComments(sourceCode.ast, ruleId => getRule(slots, ruleId), options.warnInlineConfig)
  1147. : { configuredRules: {}, enabledGlobals: {}, exportedVariables: {}, problems: [], disableDirectives: [] };
  1148. // augment global scope with declared global variables
  1149. addDeclaredGlobals(
  1150. sourceCode.scopeManager.scopes[0],
  1151. configuredGlobals,
  1152. { exportedVariables: commentDirectives.exportedVariables, enabledGlobals: commentDirectives.enabledGlobals }
  1153. );
  1154. const configuredRules = Object.assign({}, config.rules, commentDirectives.configuredRules);
  1155. let lintingProblems;
  1156. try {
  1157. lintingProblems = runRules(
  1158. sourceCode,
  1159. configuredRules,
  1160. ruleId => getRule(slots, ruleId),
  1161. parserName,
  1162. languageOptions,
  1163. settings,
  1164. options.filename,
  1165. options.disableFixes,
  1166. slots.cwd,
  1167. providedOptions.physicalFilename
  1168. );
  1169. } catch (err) {
  1170. err.message += `\nOccurred while linting ${options.filename}`;
  1171. debug("An error occurred while traversing");
  1172. debug("Filename:", options.filename);
  1173. if (err.currentNode) {
  1174. const { line } = err.currentNode.loc.start;
  1175. debug("Line:", line);
  1176. err.message += `:${line}`;
  1177. }
  1178. debug("Parser Options:", parserOptions);
  1179. debug("Parser Path:", parserName);
  1180. debug("Settings:", settings);
  1181. if (err.ruleId) {
  1182. err.message += `\nRule: "${err.ruleId}"`;
  1183. }
  1184. throw err;
  1185. }
  1186. return applyDisableDirectives({
  1187. directives: commentDirectives.disableDirectives,
  1188. disableFixes: options.disableFixes,
  1189. problems: lintingProblems
  1190. .concat(commentDirectives.problems)
  1191. .sort((problemA, problemB) => problemA.line - problemB.line || problemA.column - problemB.column),
  1192. reportUnusedDisableDirectives: options.reportUnusedDisableDirectives
  1193. });
  1194. }
  1195. /**
  1196. * Verifies the text against the rules specified by the second argument.
  1197. * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
  1198. * @param {ConfigData|ConfigArray} config An ESLintConfig instance to configure everything.
  1199. * @param {(string|(VerifyOptions&ProcessorOptions))} [filenameOrOptions] The optional filename of the file being checked.
  1200. * If this is not set, the filename will default to '<input>' in the rule context. If
  1201. * an object, then it has "filename", "allowInlineConfig", and some properties.
  1202. * @returns {LintMessage[]} The results as an array of messages or an empty array if no messages.
  1203. */
  1204. verify(textOrSourceCode, config, filenameOrOptions) {
  1205. debug("Verify");
  1206. const { configType } = internalSlotsMap.get(this);
  1207. const options = typeof filenameOrOptions === "string"
  1208. ? { filename: filenameOrOptions }
  1209. : filenameOrOptions || {};
  1210. if (config) {
  1211. if (configType === "flat") {
  1212. /*
  1213. * Because of how Webpack packages up the files, we can't
  1214. * compare directly to `FlatConfigArray` using `instanceof`
  1215. * because it's not the same `FlatConfigArray` as in the tests.
  1216. * So, we work around it by assuming an array is, in fact, a
  1217. * `FlatConfigArray` if it has a `getConfig()` method.
  1218. */
  1219. let configArray = config;
  1220. if (!Array.isArray(config) || typeof config.getConfig !== "function") {
  1221. configArray = new FlatConfigArray(config);
  1222. configArray.normalizeSync();
  1223. }
  1224. return this._distinguishSuppressedMessages(this._verifyWithFlatConfigArray(textOrSourceCode, configArray, options, true));
  1225. }
  1226. if (typeof config.extractConfig === "function") {
  1227. return this._distinguishSuppressedMessages(this._verifyWithConfigArray(textOrSourceCode, config, options));
  1228. }
  1229. }
  1230. /*
  1231. * If we get to here, it means `config` is just an object rather
  1232. * than a config array so we can go right into linting.
  1233. */
  1234. /*
  1235. * `Linter` doesn't support `overrides` property in configuration.
  1236. * So we cannot apply multiple processors.
  1237. */
  1238. if (options.preprocess || options.postprocess) {
  1239. return this._distinguishSuppressedMessages(this._verifyWithProcessor(textOrSourceCode, config, options));
  1240. }
  1241. return this._distinguishSuppressedMessages(this._verifyWithoutProcessors(textOrSourceCode, config, options));
  1242. }
  1243. /**
  1244. * Verify with a processor.
  1245. * @param {string|SourceCode} textOrSourceCode The source code.
  1246. * @param {FlatConfig} config The config array.
  1247. * @param {VerifyOptions&ProcessorOptions} options The options.
  1248. * @param {FlatConfigArray} [configForRecursive] The `ConfigArray` object to apply multiple processors recursively.
  1249. * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems.
  1250. */
  1251. _verifyWithFlatConfigArrayAndProcessor(textOrSourceCode, config, options, configForRecursive) {
  1252. const filename = options.filename || "<input>";
  1253. const filenameToExpose = normalizeFilename(filename);
  1254. const physicalFilename = options.physicalFilename || filenameToExpose;
  1255. const text = ensureText(textOrSourceCode);
  1256. const preprocess = options.preprocess || (rawText => [rawText]);
  1257. const postprocess = options.postprocess || (messagesList => messagesList.flat());
  1258. const filterCodeBlock =
  1259. options.filterCodeBlock ||
  1260. (blockFilename => blockFilename.endsWith(".js"));
  1261. const originalExtname = path.extname(filename);
  1262. let blocks;
  1263. try {
  1264. blocks = preprocess(text, filenameToExpose);
  1265. } catch (ex) {
  1266. // If the message includes a leading line number, strip it:
  1267. const message = `Preprocessing error: ${ex.message.replace(/^line \d+:/iu, "").trim()}`;
  1268. debug("%s\n%s", message, ex.stack);
  1269. return [
  1270. {
  1271. ruleId: null,
  1272. fatal: true,
  1273. severity: 2,
  1274. message,
  1275. line: ex.lineNumber,
  1276. column: ex.column,
  1277. nodeType: null
  1278. }
  1279. ];
  1280. }
  1281. const messageLists = blocks.map((block, i) => {
  1282. debug("A code block was found: %o", block.filename || "(unnamed)");
  1283. // Keep the legacy behavior.
  1284. if (typeof block === "string") {
  1285. return this._verifyWithFlatConfigArrayAndWithoutProcessors(block, config, options);
  1286. }
  1287. const blockText = block.text;
  1288. const blockName = path.join(filename, `${i}_${block.filename}`);
  1289. // Skip this block if filtered.
  1290. if (!filterCodeBlock(blockName, blockText)) {
  1291. debug("This code block was skipped.");
  1292. return [];
  1293. }
  1294. // Resolve configuration again if the file content or extension was changed.
  1295. if (configForRecursive && (text !== blockText || path.extname(blockName) !== originalExtname)) {
  1296. debug("Resolving configuration again because the file content or extension was changed.");
  1297. return this._verifyWithFlatConfigArray(
  1298. blockText,
  1299. configForRecursive,
  1300. { ...options, filename: blockName, physicalFilename }
  1301. );
  1302. }
  1303. // Does lint.
  1304. return this._verifyWithFlatConfigArrayAndWithoutProcessors(
  1305. blockText,
  1306. config,
  1307. { ...options, filename: blockName, physicalFilename }
  1308. );
  1309. });
  1310. return postprocess(messageLists, filenameToExpose);
  1311. }
  1312. /**
  1313. * Same as linter.verify, except without support for processors.
  1314. * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
  1315. * @param {FlatConfig} providedConfig An ESLintConfig instance to configure everything.
  1316. * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked.
  1317. * @throws {Error} If during rule execution.
  1318. * @returns {(LintMessage|SuppressedLintMessage)[]} The results as an array of messages or an empty array if no messages.
  1319. */
  1320. _verifyWithFlatConfigArrayAndWithoutProcessors(textOrSourceCode, providedConfig, providedOptions) {
  1321. const slots = internalSlotsMap.get(this);
  1322. const config = providedConfig || {};
  1323. const options = normalizeVerifyOptions(providedOptions, config);
  1324. let text;
  1325. // evaluate arguments
  1326. if (typeof textOrSourceCode === "string") {
  1327. slots.lastSourceCode = null;
  1328. text = textOrSourceCode;
  1329. } else {
  1330. slots.lastSourceCode = textOrSourceCode;
  1331. text = textOrSourceCode.text;
  1332. }
  1333. const languageOptions = config.languageOptions;
  1334. languageOptions.ecmaVersion = normalizeEcmaVersionForLanguageOptions(
  1335. languageOptions.ecmaVersion
  1336. );
  1337. /*
  1338. * add configured globals and language globals
  1339. *
  1340. * using Object.assign instead of object spread for performance reasons
  1341. * https://github.com/eslint/eslint/issues/16302
  1342. */
  1343. const configuredGlobals = Object.assign(
  1344. {},
  1345. getGlobalsForEcmaVersion(languageOptions.ecmaVersion),
  1346. languageOptions.sourceType === "commonjs" ? globals.commonjs : void 0,
  1347. languageOptions.globals
  1348. );
  1349. // double check that there is a parser to avoid mysterious error messages
  1350. if (!languageOptions.parser) {
  1351. throw new TypeError(`No parser specified for ${options.filename}`);
  1352. }
  1353. // Espree expects this information to be passed in
  1354. if (isEspree(languageOptions.parser)) {
  1355. const parserOptions = languageOptions.parserOptions;
  1356. if (languageOptions.sourceType) {
  1357. parserOptions.sourceType = languageOptions.sourceType;
  1358. if (
  1359. parserOptions.sourceType === "module" &&
  1360. parserOptions.ecmaFeatures &&
  1361. parserOptions.ecmaFeatures.globalReturn
  1362. ) {
  1363. parserOptions.ecmaFeatures.globalReturn = false;
  1364. }
  1365. }
  1366. }
  1367. const settings = config.settings || {};
  1368. if (!slots.lastSourceCode) {
  1369. const parseResult = parse(
  1370. text,
  1371. languageOptions,
  1372. options.filename
  1373. );
  1374. if (!parseResult.success) {
  1375. return [parseResult.error];
  1376. }
  1377. slots.lastSourceCode = parseResult.sourceCode;
  1378. } else {
  1379. /*
  1380. * If the given source code object as the first argument does not have scopeManager, analyze the scope.
  1381. * This is for backward compatibility (SourceCode is frozen so it cannot rebind).
  1382. */
  1383. if (!slots.lastSourceCode.scopeManager) {
  1384. slots.lastSourceCode = new SourceCode({
  1385. text: slots.lastSourceCode.text,
  1386. ast: slots.lastSourceCode.ast,
  1387. parserServices: slots.lastSourceCode.parserServices,
  1388. visitorKeys: slots.lastSourceCode.visitorKeys,
  1389. scopeManager: analyzeScope(slots.lastSourceCode.ast, languageOptions)
  1390. });
  1391. }
  1392. }
  1393. const sourceCode = slots.lastSourceCode;
  1394. const commentDirectives = options.allowInlineConfig
  1395. ? getDirectiveComments(
  1396. sourceCode.ast,
  1397. ruleId => getRuleFromConfig(ruleId, config),
  1398. options.warnInlineConfig
  1399. )
  1400. : { configuredRules: {}, enabledGlobals: {}, exportedVariables: {}, problems: [], disableDirectives: [] };
  1401. // augment global scope with declared global variables
  1402. addDeclaredGlobals(
  1403. sourceCode.scopeManager.scopes[0],
  1404. configuredGlobals,
  1405. { exportedVariables: commentDirectives.exportedVariables, enabledGlobals: commentDirectives.enabledGlobals }
  1406. );
  1407. const configuredRules = Object.assign({}, config.rules, commentDirectives.configuredRules);
  1408. let lintingProblems;
  1409. try {
  1410. lintingProblems = runRules(
  1411. sourceCode,
  1412. configuredRules,
  1413. ruleId => getRuleFromConfig(ruleId, config),
  1414. void 0,
  1415. languageOptions,
  1416. settings,
  1417. options.filename,
  1418. options.disableFixes,
  1419. slots.cwd,
  1420. providedOptions.physicalFilename
  1421. );
  1422. } catch (err) {
  1423. err.message += `\nOccurred while linting ${options.filename}`;
  1424. debug("An error occurred while traversing");
  1425. debug("Filename:", options.filename);
  1426. if (err.currentNode) {
  1427. const { line } = err.currentNode.loc.start;
  1428. debug("Line:", line);
  1429. err.message += `:${line}`;
  1430. }
  1431. debug("Parser Options:", languageOptions.parserOptions);
  1432. // debug("Parser Path:", parserName);
  1433. debug("Settings:", settings);
  1434. if (err.ruleId) {
  1435. err.message += `\nRule: "${err.ruleId}"`;
  1436. }
  1437. throw err;
  1438. }
  1439. return applyDisableDirectives({
  1440. directives: commentDirectives.disableDirectives,
  1441. disableFixes: options.disableFixes,
  1442. problems: lintingProblems
  1443. .concat(commentDirectives.problems)
  1444. .sort((problemA, problemB) => problemA.line - problemB.line || problemA.column - problemB.column),
  1445. reportUnusedDisableDirectives: options.reportUnusedDisableDirectives
  1446. });
  1447. }
  1448. /**
  1449. * Verify a given code with `ConfigArray`.
  1450. * @param {string|SourceCode} textOrSourceCode The source code.
  1451. * @param {ConfigArray} configArray The config array.
  1452. * @param {VerifyOptions&ProcessorOptions} options The options.
  1453. * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems.
  1454. */
  1455. _verifyWithConfigArray(textOrSourceCode, configArray, options) {
  1456. debug("With ConfigArray: %s", options.filename);
  1457. // Store the config array in order to get plugin envs and rules later.
  1458. internalSlotsMap.get(this).lastConfigArray = configArray;
  1459. // Extract the final config for this file.
  1460. const config = configArray.extractConfig(options.filename);
  1461. const processor =
  1462. config.processor &&
  1463. configArray.pluginProcessors.get(config.processor);
  1464. // Verify.
  1465. if (processor) {
  1466. debug("Apply the processor: %o", config.processor);
  1467. const { preprocess, postprocess, supportsAutofix } = processor;
  1468. const disableFixes = options.disableFixes || !supportsAutofix;
  1469. return this._verifyWithProcessor(
  1470. textOrSourceCode,
  1471. config,
  1472. { ...options, disableFixes, postprocess, preprocess },
  1473. configArray
  1474. );
  1475. }
  1476. return this._verifyWithoutProcessors(textOrSourceCode, config, options);
  1477. }
  1478. /**
  1479. * Verify a given code with a flat config.
  1480. * @param {string|SourceCode} textOrSourceCode The source code.
  1481. * @param {FlatConfigArray} configArray The config array.
  1482. * @param {VerifyOptions&ProcessorOptions} options The options.
  1483. * @param {boolean} [firstCall=false] Indicates if this is being called directly
  1484. * from verify(). (TODO: Remove once eslintrc is removed.)
  1485. * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems.
  1486. */
  1487. _verifyWithFlatConfigArray(textOrSourceCode, configArray, options, firstCall = false) {
  1488. debug("With flat config: %s", options.filename);
  1489. // we need a filename to match configs against
  1490. const filename = options.filename || "__placeholder__.js";
  1491. // Store the config array in order to get plugin envs and rules later.
  1492. internalSlotsMap.get(this).lastConfigArray = configArray;
  1493. const config = configArray.getConfig(filename);
  1494. if (!config) {
  1495. return [
  1496. {
  1497. ruleId: null,
  1498. severity: 1,
  1499. message: `No matching configuration found for ${filename}.`,
  1500. line: 0,
  1501. column: 0,
  1502. nodeType: null
  1503. }
  1504. ];
  1505. }
  1506. // Verify.
  1507. if (config.processor) {
  1508. debug("Apply the processor: %o", config.processor);
  1509. const { preprocess, postprocess, supportsAutofix } = config.processor;
  1510. const disableFixes = options.disableFixes || !supportsAutofix;
  1511. return this._verifyWithFlatConfigArrayAndProcessor(
  1512. textOrSourceCode,
  1513. config,
  1514. { ...options, filename, disableFixes, postprocess, preprocess },
  1515. configArray
  1516. );
  1517. }
  1518. // check for options-based processing
  1519. if (firstCall && (options.preprocess || options.postprocess)) {
  1520. return this._verifyWithFlatConfigArrayAndProcessor(textOrSourceCode, config, options);
  1521. }
  1522. return this._verifyWithFlatConfigArrayAndWithoutProcessors(textOrSourceCode, config, options);
  1523. }
  1524. /**
  1525. * Verify with a processor.
  1526. * @param {string|SourceCode} textOrSourceCode The source code.
  1527. * @param {ConfigData|ExtractedConfig} config The config array.
  1528. * @param {VerifyOptions&ProcessorOptions} options The options.
  1529. * @param {ConfigArray} [configForRecursive] The `ConfigArray` object to apply multiple processors recursively.
  1530. * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems.
  1531. */
  1532. _verifyWithProcessor(textOrSourceCode, config, options, configForRecursive) {
  1533. const filename = options.filename || "<input>";
  1534. const filenameToExpose = normalizeFilename(filename);
  1535. const physicalFilename = options.physicalFilename || filenameToExpose;
  1536. const text = ensureText(textOrSourceCode);
  1537. const preprocess = options.preprocess || (rawText => [rawText]);
  1538. const postprocess = options.postprocess || (messagesList => messagesList.flat());
  1539. const filterCodeBlock =
  1540. options.filterCodeBlock ||
  1541. (blockFilename => blockFilename.endsWith(".js"));
  1542. const originalExtname = path.extname(filename);
  1543. let blocks;
  1544. try {
  1545. blocks = preprocess(text, filenameToExpose);
  1546. } catch (ex) {
  1547. // If the message includes a leading line number, strip it:
  1548. const message = `Preprocessing error: ${ex.message.replace(/^line \d+:/iu, "").trim()}`;
  1549. debug("%s\n%s", message, ex.stack);
  1550. return [
  1551. {
  1552. ruleId: null,
  1553. fatal: true,
  1554. severity: 2,
  1555. message,
  1556. line: ex.lineNumber,
  1557. column: ex.column,
  1558. nodeType: null
  1559. }
  1560. ];
  1561. }
  1562. const messageLists = blocks.map((block, i) => {
  1563. debug("A code block was found: %o", block.filename || "(unnamed)");
  1564. // Keep the legacy behavior.
  1565. if (typeof block === "string") {
  1566. return this._verifyWithoutProcessors(block, config, options);
  1567. }
  1568. const blockText = block.text;
  1569. const blockName = path.join(filename, `${i}_${block.filename}`);
  1570. // Skip this block if filtered.
  1571. if (!filterCodeBlock(blockName, blockText)) {
  1572. debug("This code block was skipped.");
  1573. return [];
  1574. }
  1575. // Resolve configuration again if the file content or extension was changed.
  1576. if (configForRecursive && (text !== blockText || path.extname(blockName) !== originalExtname)) {
  1577. debug("Resolving configuration again because the file content or extension was changed.");
  1578. return this._verifyWithConfigArray(
  1579. blockText,
  1580. configForRecursive,
  1581. { ...options, filename: blockName, physicalFilename }
  1582. );
  1583. }
  1584. // Does lint.
  1585. return this._verifyWithoutProcessors(
  1586. blockText,
  1587. config,
  1588. { ...options, filename: blockName, physicalFilename }
  1589. );
  1590. });
  1591. return postprocess(messageLists, filenameToExpose);
  1592. }
  1593. /**
  1594. * Given a list of reported problems, distinguish problems between normal messages and suppressed messages.
  1595. * The normal messages will be returned and the suppressed messages will be stored as lastSuppressedMessages.
  1596. * @param {Array<LintMessage|SuppressedLintMessage>} problems A list of reported problems.
  1597. * @returns {LintMessage[]} A list of LintMessage.
  1598. */
  1599. _distinguishSuppressedMessages(problems) {
  1600. const messages = [];
  1601. const suppressedMessages = [];
  1602. const slots = internalSlotsMap.get(this);
  1603. for (const problem of problems) {
  1604. if (problem.suppressions) {
  1605. suppressedMessages.push(problem);
  1606. } else {
  1607. messages.push(problem);
  1608. }
  1609. }
  1610. slots.lastSuppressedMessages = suppressedMessages;
  1611. return messages;
  1612. }
  1613. /**
  1614. * Gets the SourceCode object representing the parsed source.
  1615. * @returns {SourceCode} The SourceCode object.
  1616. */
  1617. getSourceCode() {
  1618. return internalSlotsMap.get(this).lastSourceCode;
  1619. }
  1620. /**
  1621. * Gets the list of SuppressedLintMessage produced in the last running.
  1622. * @returns {SuppressedLintMessage[]} The list of SuppressedLintMessage
  1623. */
  1624. getSuppressedMessages() {
  1625. return internalSlotsMap.get(this).lastSuppressedMessages;
  1626. }
  1627. /**
  1628. * Defines a new linting rule.
  1629. * @param {string} ruleId A unique rule identifier
  1630. * @param {Function | Rule} ruleModule Function from context to object mapping AST node types to event handlers
  1631. * @returns {void}
  1632. */
  1633. defineRule(ruleId, ruleModule) {
  1634. assertEslintrcConfig(this);
  1635. internalSlotsMap.get(this).ruleMap.define(ruleId, ruleModule);
  1636. }
  1637. /**
  1638. * Defines many new linting rules.
  1639. * @param {Record<string, Function | Rule>} rulesToDefine map from unique rule identifier to rule
  1640. * @returns {void}
  1641. */
  1642. defineRules(rulesToDefine) {
  1643. assertEslintrcConfig(this);
  1644. Object.getOwnPropertyNames(rulesToDefine).forEach(ruleId => {
  1645. this.defineRule(ruleId, rulesToDefine[ruleId]);
  1646. });
  1647. }
  1648. /**
  1649. * Gets an object with all loaded rules.
  1650. * @returns {Map<string, Rule>} All loaded rules
  1651. */
  1652. getRules() {
  1653. assertEslintrcConfig(this);
  1654. const { lastConfigArray, ruleMap } = internalSlotsMap.get(this);
  1655. return new Map(function *() {
  1656. yield* ruleMap;
  1657. if (lastConfigArray) {
  1658. yield* lastConfigArray.pluginRules;
  1659. }
  1660. }());
  1661. }
  1662. /**
  1663. * Define a new parser module
  1664. * @param {string} parserId Name of the parser
  1665. * @param {Parser} parserModule The parser object
  1666. * @returns {void}
  1667. */
  1668. defineParser(parserId, parserModule) {
  1669. assertEslintrcConfig(this);
  1670. internalSlotsMap.get(this).parserMap.set(parserId, parserModule);
  1671. }
  1672. /**
  1673. * Performs multiple autofix passes over the text until as many fixes as possible
  1674. * have been applied.
  1675. * @param {string} text The source text to apply fixes to.
  1676. * @param {ConfigData|ConfigArray|FlatConfigArray} config The ESLint config object to use.
  1677. * @param {VerifyOptions&ProcessorOptions&FixOptions} options The ESLint options object to use.
  1678. * @returns {{fixed:boolean,messages:LintMessage[],output:string}} The result of the fix operation as returned from the
  1679. * SourceCodeFixer.
  1680. */
  1681. verifyAndFix(text, config, options) {
  1682. let messages = [],
  1683. fixedResult,
  1684. fixed = false,
  1685. passNumber = 0,
  1686. currentText = text;
  1687. const debugTextDescription = options && options.filename || `${text.slice(0, 10)}...`;
  1688. const shouldFix = options && typeof options.fix !== "undefined" ? options.fix : true;
  1689. /**
  1690. * This loop continues until one of the following is true:
  1691. *
  1692. * 1. No more fixes have been applied.
  1693. * 2. Ten passes have been made.
  1694. *
  1695. * That means anytime a fix is successfully applied, there will be another pass.
  1696. * Essentially, guaranteeing a minimum of two passes.
  1697. */
  1698. do {
  1699. passNumber++;
  1700. debug(`Linting code for ${debugTextDescription} (pass ${passNumber})`);
  1701. messages = this.verify(currentText, config, options);
  1702. debug(`Generating fixed text for ${debugTextDescription} (pass ${passNumber})`);
  1703. fixedResult = SourceCodeFixer.applyFixes(currentText, messages, shouldFix);
  1704. /*
  1705. * stop if there are any syntax errors.
  1706. * 'fixedResult.output' is a empty string.
  1707. */
  1708. if (messages.length === 1 && messages[0].fatal) {
  1709. break;
  1710. }
  1711. // keep track if any fixes were ever applied - important for return value
  1712. fixed = fixed || fixedResult.fixed;
  1713. // update to use the fixed output instead of the original text
  1714. currentText = fixedResult.output;
  1715. } while (
  1716. fixedResult.fixed &&
  1717. passNumber < MAX_AUTOFIX_PASSES
  1718. );
  1719. /*
  1720. * If the last result had fixes, we need to lint again to be sure we have
  1721. * the most up-to-date information.
  1722. */
  1723. if (fixedResult.fixed) {
  1724. fixedResult.messages = this.verify(currentText, config, options);
  1725. }
  1726. // ensure the last result properly reflects if fixes were done
  1727. fixedResult.fixed = fixed;
  1728. fixedResult.output = currentText;
  1729. return fixedResult;
  1730. }
  1731. }
  1732. module.exports = {
  1733. Linter,
  1734. /**
  1735. * Get the internal slots of a given Linter instance for tests.
  1736. * @param {Linter} instance The Linter instance to get.
  1737. * @returns {LinterInternalSlots} The internal slots.
  1738. */
  1739. getLinterInternalSlots(instance) {
  1740. return internalSlotsMap.get(instance);
  1741. }
  1742. };