linter.js 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057
  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: Problem[], 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#getFilename()` 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: Problem}|{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. }
  738. };
  739. }
  740. }
  741. /**
  742. * Marks a variable as used in the current scope
  743. * @param {SourceCode} sourceCode The source code for the currently linted file.
  744. * @param {ASTNode} currentNode The node currently being traversed
  745. * @param {LanguageOptions} languageOptions The options used to parse this text
  746. * @param {string} name The name of the variable that should be marked as used.
  747. * @returns {boolean} True if the variable was found and marked as used, false if not.
  748. */
  749. function markVariableAsUsed(sourceCode, currentNode, languageOptions, name) {
  750. const parserOptions = languageOptions.parserOptions;
  751. const sourceType = languageOptions.sourceType;
  752. const hasGlobalReturn =
  753. (parserOptions.ecmaFeatures && parserOptions.ecmaFeatures.globalReturn) ||
  754. sourceType === "commonjs";
  755. const specialScope = hasGlobalReturn || sourceType === "module";
  756. const currentScope = sourceCode.getScope(currentNode);
  757. // Special Node.js scope means we need to start one level deeper
  758. const initialScope = currentScope.type === "global" && specialScope ? currentScope.childScopes[0] : currentScope;
  759. for (let scope = initialScope; scope; scope = scope.upper) {
  760. const variable = scope.variables.find(scopeVar => scopeVar.name === name);
  761. if (variable) {
  762. variable.eslintUsed = true;
  763. return true;
  764. }
  765. }
  766. return false;
  767. }
  768. /**
  769. * Runs a rule, and gets its listeners
  770. * @param {Rule} rule A normalized rule with a `create` method
  771. * @param {Context} ruleContext The context that should be passed to the rule
  772. * @throws {any} Any error during the rule's `create`
  773. * @returns {Object} A map of selector listeners provided by the rule
  774. */
  775. function createRuleListeners(rule, ruleContext) {
  776. try {
  777. return rule.create(ruleContext);
  778. } catch (ex) {
  779. ex.message = `Error while loading rule '${ruleContext.id}': ${ex.message}`;
  780. throw ex;
  781. }
  782. }
  783. /**
  784. * Gets all the ancestors of a given node
  785. * @param {ASTNode} node The node
  786. * @returns {ASTNode[]} All the ancestor nodes in the AST, not including the provided node, starting
  787. * from the root node and going inwards to the parent node.
  788. */
  789. function getAncestors(node) {
  790. const ancestorsStartingAtParent = [];
  791. for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) {
  792. ancestorsStartingAtParent.push(ancestor);
  793. }
  794. return ancestorsStartingAtParent.reverse();
  795. }
  796. // methods that exist on SourceCode object
  797. const DEPRECATED_SOURCECODE_PASSTHROUGHS = {
  798. getSource: "getText",
  799. getSourceLines: "getLines",
  800. getAllComments: "getAllComments",
  801. getNodeByRangeIndex: "getNodeByRangeIndex",
  802. getComments: "getComments",
  803. getCommentsBefore: "getCommentsBefore",
  804. getCommentsAfter: "getCommentsAfter",
  805. getCommentsInside: "getCommentsInside",
  806. getJSDocComment: "getJSDocComment",
  807. getFirstToken: "getFirstToken",
  808. getFirstTokens: "getFirstTokens",
  809. getLastToken: "getLastToken",
  810. getLastTokens: "getLastTokens",
  811. getTokenAfter: "getTokenAfter",
  812. getTokenBefore: "getTokenBefore",
  813. getTokenByRangeStart: "getTokenByRangeStart",
  814. getTokens: "getTokens",
  815. getTokensAfter: "getTokensAfter",
  816. getTokensBefore: "getTokensBefore",
  817. getTokensBetween: "getTokensBetween"
  818. };
  819. const BASE_TRAVERSAL_CONTEXT = Object.freeze(
  820. Object.keys(DEPRECATED_SOURCECODE_PASSTHROUGHS).reduce(
  821. (contextInfo, methodName) =>
  822. Object.assign(contextInfo, {
  823. [methodName](...args) {
  824. return this.getSourceCode()[DEPRECATED_SOURCECODE_PASSTHROUGHS[methodName]](...args);
  825. }
  826. }),
  827. {}
  828. )
  829. );
  830. /**
  831. * Runs the given rules on the given SourceCode object
  832. * @param {SourceCode} sourceCode A SourceCode object for the given text
  833. * @param {Object} configuredRules The rules configuration
  834. * @param {function(string): Rule} ruleMapper A mapper function from rule names to rules
  835. * @param {string | undefined} parserName The name of the parser in the config
  836. * @param {LanguageOptions} languageOptions The options for parsing the code.
  837. * @param {Object} settings The settings that were enabled in the config
  838. * @param {string} filename The reported filename of the code
  839. * @param {boolean} disableFixes If true, it doesn't make `fix` properties.
  840. * @param {string | undefined} cwd cwd of the cli
  841. * @param {string} physicalFilename The full path of the file on disk without any code block information
  842. * @returns {Problem[]} An array of reported problems
  843. */
  844. function runRules(sourceCode, configuredRules, ruleMapper, parserName, languageOptions, settings, filename, disableFixes, cwd, physicalFilename) {
  845. const emitter = createEmitter();
  846. const nodeQueue = [];
  847. let currentNode = sourceCode.ast;
  848. Traverser.traverse(sourceCode.ast, {
  849. enter(node, parent) {
  850. node.parent = parent;
  851. nodeQueue.push({ isEntering: true, node });
  852. },
  853. leave(node) {
  854. nodeQueue.push({ isEntering: false, node });
  855. },
  856. visitorKeys: sourceCode.visitorKeys
  857. });
  858. /*
  859. * Create a frozen object with the ruleContext properties and methods that are shared by all rules.
  860. * All rule contexts will inherit from this object. This avoids the performance penalty of copying all the
  861. * properties once for each rule.
  862. */
  863. const sharedTraversalContext = Object.freeze(
  864. Object.assign(
  865. Object.create(BASE_TRAVERSAL_CONTEXT),
  866. {
  867. getAncestors: () => getAncestors(currentNode),
  868. getDeclaredVariables: sourceCode.scopeManager.getDeclaredVariables.bind(sourceCode.scopeManager),
  869. getCwd: () => cwd,
  870. getFilename: () => filename,
  871. getPhysicalFilename: () => physicalFilename || filename,
  872. getScope: () => sourceCode.getScope(currentNode),
  873. getSourceCode: () => sourceCode,
  874. markVariableAsUsed: name => markVariableAsUsed(sourceCode, currentNode, languageOptions, name),
  875. parserOptions: {
  876. ...languageOptions.parserOptions
  877. },
  878. parserPath: parserName,
  879. languageOptions,
  880. parserServices: sourceCode.parserServices,
  881. settings
  882. }
  883. )
  884. );
  885. const lintingProblems = [];
  886. Object.keys(configuredRules).forEach(ruleId => {
  887. const severity = ConfigOps.getRuleSeverity(configuredRules[ruleId]);
  888. // not load disabled rules
  889. if (severity === 0) {
  890. return;
  891. }
  892. const rule = ruleMapper(ruleId);
  893. if (!rule) {
  894. lintingProblems.push(createLintingProblem({ ruleId }));
  895. return;
  896. }
  897. const messageIds = rule.meta && rule.meta.messages;
  898. let reportTranslator = null;
  899. const ruleContext = Object.freeze(
  900. Object.assign(
  901. Object.create(sharedTraversalContext),
  902. {
  903. id: ruleId,
  904. options: getRuleOptions(configuredRules[ruleId]),
  905. report(...args) {
  906. /*
  907. * Create a report translator lazily.
  908. * In a vast majority of cases, any given rule reports zero errors on a given
  909. * piece of code. Creating a translator lazily avoids the performance cost of
  910. * creating a new translator function for each rule that usually doesn't get
  911. * called.
  912. *
  913. * Using lazy report translators improves end-to-end performance by about 3%
  914. * with Node 8.4.0.
  915. */
  916. if (reportTranslator === null) {
  917. reportTranslator = createReportTranslator({
  918. ruleId,
  919. severity,
  920. sourceCode,
  921. messageIds,
  922. disableFixes
  923. });
  924. }
  925. const problem = reportTranslator(...args);
  926. if (problem.fix && !(rule.meta && rule.meta.fixable)) {
  927. throw new Error("Fixable rules must set the `meta.fixable` property to \"code\" or \"whitespace\".");
  928. }
  929. if (problem.suggestions && !(rule.meta && rule.meta.hasSuggestions === true)) {
  930. if (rule.meta && rule.meta.docs && typeof rule.meta.docs.suggestion !== "undefined") {
  931. // Encourage migration from the former property name.
  932. throw new Error("Rules with suggestions must set the `meta.hasSuggestions` property to `true`. `meta.docs.suggestion` is ignored by ESLint.");
  933. }
  934. throw new Error("Rules with suggestions must set the `meta.hasSuggestions` property to `true`.");
  935. }
  936. lintingProblems.push(problem);
  937. }
  938. }
  939. )
  940. );
  941. const ruleListeners = timing.enabled ? timing.time(ruleId, createRuleListeners)(rule, ruleContext) : createRuleListeners(rule, ruleContext);
  942. /**
  943. * Include `ruleId` in error logs
  944. * @param {Function} ruleListener A rule method that listens for a node.
  945. * @returns {Function} ruleListener wrapped in error handler
  946. */
  947. function addRuleErrorHandler(ruleListener) {
  948. return function ruleErrorHandler(...listenerArgs) {
  949. try {
  950. return ruleListener(...listenerArgs);
  951. } catch (e) {
  952. e.ruleId = ruleId;
  953. throw e;
  954. }
  955. };
  956. }
  957. if (typeof ruleListeners === "undefined" || ruleListeners === null) {
  958. throw new Error(`The create() function for rule '${ruleId}' did not return an object.`);
  959. }
  960. // add all the selectors from the rule as listeners
  961. Object.keys(ruleListeners).forEach(selector => {
  962. const ruleListener = timing.enabled
  963. ? timing.time(ruleId, ruleListeners[selector])
  964. : ruleListeners[selector];
  965. emitter.on(
  966. selector,
  967. addRuleErrorHandler(ruleListener)
  968. );
  969. });
  970. });
  971. // only run code path analyzer if the top level node is "Program", skip otherwise
  972. const eventGenerator = nodeQueue[0].node.type === "Program"
  973. ? new CodePathAnalyzer(new NodeEventGenerator(emitter, { visitorKeys: sourceCode.visitorKeys, fallback: Traverser.getKeys }))
  974. : new NodeEventGenerator(emitter, { visitorKeys: sourceCode.visitorKeys, fallback: Traverser.getKeys });
  975. nodeQueue.forEach(traversalInfo => {
  976. currentNode = traversalInfo.node;
  977. try {
  978. if (traversalInfo.isEntering) {
  979. eventGenerator.enterNode(currentNode);
  980. } else {
  981. eventGenerator.leaveNode(currentNode);
  982. }
  983. } catch (err) {
  984. err.currentNode = currentNode;
  985. throw err;
  986. }
  987. });
  988. return lintingProblems;
  989. }
  990. /**
  991. * Ensure the source code to be a string.
  992. * @param {string|SourceCode} textOrSourceCode The text or source code object.
  993. * @returns {string} The source code text.
  994. */
  995. function ensureText(textOrSourceCode) {
  996. if (typeof textOrSourceCode === "object") {
  997. const { hasBOM, text } = textOrSourceCode;
  998. const bom = hasBOM ? "\uFEFF" : "";
  999. return bom + text;
  1000. }
  1001. return String(textOrSourceCode);
  1002. }
  1003. /**
  1004. * Get an environment.
  1005. * @param {LinterInternalSlots} slots The internal slots of Linter.
  1006. * @param {string} envId The environment ID to get.
  1007. * @returns {Environment|null} The environment.
  1008. */
  1009. function getEnv(slots, envId) {
  1010. return (
  1011. (slots.lastConfigArray && slots.lastConfigArray.pluginEnvironments.get(envId)) ||
  1012. BuiltInEnvironments.get(envId) ||
  1013. null
  1014. );
  1015. }
  1016. /**
  1017. * Get a rule.
  1018. * @param {LinterInternalSlots} slots The internal slots of Linter.
  1019. * @param {string} ruleId The rule ID to get.
  1020. * @returns {Rule|null} The rule.
  1021. */
  1022. function getRule(slots, ruleId) {
  1023. return (
  1024. (slots.lastConfigArray && slots.lastConfigArray.pluginRules.get(ruleId)) ||
  1025. slots.ruleMap.get(ruleId)
  1026. );
  1027. }
  1028. /**
  1029. * Normalize the value of the cwd
  1030. * @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.
  1031. * @returns {string | undefined} normalized cwd
  1032. */
  1033. function normalizeCwd(cwd) {
  1034. if (cwd) {
  1035. return cwd;
  1036. }
  1037. if (typeof process === "object") {
  1038. return process.cwd();
  1039. }
  1040. // It's more explicit to assign the undefined
  1041. // eslint-disable-next-line no-undefined -- Consistently returning a value
  1042. return undefined;
  1043. }
  1044. /**
  1045. * The map to store private data.
  1046. * @type {WeakMap<Linter, LinterInternalSlots>}
  1047. */
  1048. const internalSlotsMap = new WeakMap();
  1049. /**
  1050. * Throws an error when the given linter is in flat config mode.
  1051. * @param {Linter} linter The linter to check.
  1052. * @returns {void}
  1053. * @throws {Error} If the linter is in flat config mode.
  1054. */
  1055. function assertEslintrcConfig(linter) {
  1056. const { configType } = internalSlotsMap.get(linter);
  1057. if (configType === "flat") {
  1058. throw new Error("This method cannot be used with flat config. Add your entries directly into the config array.");
  1059. }
  1060. }
  1061. //------------------------------------------------------------------------------
  1062. // Public Interface
  1063. //------------------------------------------------------------------------------
  1064. /**
  1065. * Object that is responsible for verifying JavaScript text
  1066. * @name Linter
  1067. */
  1068. class Linter {
  1069. /**
  1070. * Initialize the Linter.
  1071. * @param {Object} [config] the config object
  1072. * @param {string} [config.cwd] path to a directory that should be considered as the current working directory, can be undefined.
  1073. * @param {"flat"|"eslintrc"} [config.configType="eslintrc"] the type of config used.
  1074. */
  1075. constructor({ cwd, configType } = {}) {
  1076. internalSlotsMap.set(this, {
  1077. cwd: normalizeCwd(cwd),
  1078. lastConfigArray: null,
  1079. lastSourceCode: null,
  1080. lastSuppressedMessages: [],
  1081. configType, // TODO: Remove after flat config conversion
  1082. parserMap: new Map([["espree", espree]]),
  1083. ruleMap: new Rules()
  1084. });
  1085. this.version = pkg.version;
  1086. }
  1087. /**
  1088. * Getter for package version.
  1089. * @static
  1090. * @returns {string} The version from package.json.
  1091. */
  1092. static get version() {
  1093. return pkg.version;
  1094. }
  1095. /**
  1096. * Same as linter.verify, except without support for processors.
  1097. * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
  1098. * @param {ConfigData} providedConfig An ESLintConfig instance to configure everything.
  1099. * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked.
  1100. * @throws {Error} If during rule execution.
  1101. * @returns {(LintMessage|SuppressedLintMessage)[]} The results as an array of messages or an empty array if no messages.
  1102. */
  1103. _verifyWithoutProcessors(textOrSourceCode, providedConfig, providedOptions) {
  1104. const slots = internalSlotsMap.get(this);
  1105. const config = providedConfig || {};
  1106. const options = normalizeVerifyOptions(providedOptions, config);
  1107. let text;
  1108. // evaluate arguments
  1109. if (typeof textOrSourceCode === "string") {
  1110. slots.lastSourceCode = null;
  1111. text = textOrSourceCode;
  1112. } else {
  1113. slots.lastSourceCode = textOrSourceCode;
  1114. text = textOrSourceCode.text;
  1115. }
  1116. // Resolve parser.
  1117. let parserName = DEFAULT_PARSER_NAME;
  1118. let parser = espree;
  1119. if (typeof config.parser === "object" && config.parser !== null) {
  1120. parserName = config.parser.filePath;
  1121. parser = config.parser.definition;
  1122. } else if (typeof config.parser === "string") {
  1123. if (!slots.parserMap.has(config.parser)) {
  1124. return [{
  1125. ruleId: null,
  1126. fatal: true,
  1127. severity: 2,
  1128. message: `Configured parser '${config.parser}' was not found.`,
  1129. line: 0,
  1130. column: 0
  1131. }];
  1132. }
  1133. parserName = config.parser;
  1134. parser = slots.parserMap.get(config.parser);
  1135. }
  1136. // search and apply "eslint-env *".
  1137. const envInFile = options.allowInlineConfig && !options.warnInlineConfig
  1138. ? findEslintEnv(text)
  1139. : {};
  1140. const resolvedEnvConfig = Object.assign({ builtin: true }, config.env, envInFile);
  1141. const enabledEnvs = Object.keys(resolvedEnvConfig)
  1142. .filter(envName => resolvedEnvConfig[envName])
  1143. .map(envName => getEnv(slots, envName))
  1144. .filter(env => env);
  1145. const parserOptions = resolveParserOptions(parser, config.parserOptions || {}, enabledEnvs);
  1146. const configuredGlobals = resolveGlobals(config.globals || {}, enabledEnvs);
  1147. const settings = config.settings || {};
  1148. const languageOptions = createLanguageOptions({
  1149. globals: config.globals,
  1150. parser,
  1151. parserOptions
  1152. });
  1153. if (!slots.lastSourceCode) {
  1154. const parseResult = parse(
  1155. text,
  1156. languageOptions,
  1157. options.filename
  1158. );
  1159. if (!parseResult.success) {
  1160. return [parseResult.error];
  1161. }
  1162. slots.lastSourceCode = parseResult.sourceCode;
  1163. } else {
  1164. /*
  1165. * If the given source code object as the first argument does not have scopeManager, analyze the scope.
  1166. * This is for backward compatibility (SourceCode is frozen so it cannot rebind).
  1167. */
  1168. if (!slots.lastSourceCode.scopeManager) {
  1169. slots.lastSourceCode = new SourceCode({
  1170. text: slots.lastSourceCode.text,
  1171. ast: slots.lastSourceCode.ast,
  1172. parserServices: slots.lastSourceCode.parserServices,
  1173. visitorKeys: slots.lastSourceCode.visitorKeys,
  1174. scopeManager: analyzeScope(slots.lastSourceCode.ast, languageOptions)
  1175. });
  1176. }
  1177. }
  1178. const sourceCode = slots.lastSourceCode;
  1179. const commentDirectives = options.allowInlineConfig
  1180. ? getDirectiveComments(sourceCode.ast, ruleId => getRule(slots, ruleId), options.warnInlineConfig)
  1181. : { configuredRules: {}, enabledGlobals: {}, exportedVariables: {}, problems: [], disableDirectives: [] };
  1182. // augment global scope with declared global variables
  1183. addDeclaredGlobals(
  1184. sourceCode.scopeManager.scopes[0],
  1185. configuredGlobals,
  1186. { exportedVariables: commentDirectives.exportedVariables, enabledGlobals: commentDirectives.enabledGlobals }
  1187. );
  1188. const configuredRules = Object.assign({}, config.rules, commentDirectives.configuredRules);
  1189. let lintingProblems;
  1190. try {
  1191. lintingProblems = runRules(
  1192. sourceCode,
  1193. configuredRules,
  1194. ruleId => getRule(slots, ruleId),
  1195. parserName,
  1196. languageOptions,
  1197. settings,
  1198. options.filename,
  1199. options.disableFixes,
  1200. slots.cwd,
  1201. providedOptions.physicalFilename
  1202. );
  1203. } catch (err) {
  1204. err.message += `\nOccurred while linting ${options.filename}`;
  1205. debug("An error occurred while traversing");
  1206. debug("Filename:", options.filename);
  1207. if (err.currentNode) {
  1208. const { line } = err.currentNode.loc.start;
  1209. debug("Line:", line);
  1210. err.message += `:${line}`;
  1211. }
  1212. debug("Parser Options:", parserOptions);
  1213. debug("Parser Path:", parserName);
  1214. debug("Settings:", settings);
  1215. if (err.ruleId) {
  1216. err.message += `\nRule: "${err.ruleId}"`;
  1217. }
  1218. throw err;
  1219. }
  1220. return applyDisableDirectives({
  1221. directives: commentDirectives.disableDirectives,
  1222. disableFixes: options.disableFixes,
  1223. problems: lintingProblems
  1224. .concat(commentDirectives.problems)
  1225. .sort((problemA, problemB) => problemA.line - problemB.line || problemA.column - problemB.column),
  1226. reportUnusedDisableDirectives: options.reportUnusedDisableDirectives
  1227. });
  1228. }
  1229. /**
  1230. * Verifies the text against the rules specified by the second argument.
  1231. * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
  1232. * @param {ConfigData|ConfigArray} config An ESLintConfig instance to configure everything.
  1233. * @param {(string|(VerifyOptions&ProcessorOptions))} [filenameOrOptions] The optional filename of the file being checked.
  1234. * If this is not set, the filename will default to '<input>' in the rule context. If
  1235. * an object, then it has "filename", "allowInlineConfig", and some properties.
  1236. * @returns {LintMessage[]} The results as an array of messages or an empty array if no messages.
  1237. */
  1238. verify(textOrSourceCode, config, filenameOrOptions) {
  1239. debug("Verify");
  1240. const { configType } = internalSlotsMap.get(this);
  1241. const options = typeof filenameOrOptions === "string"
  1242. ? { filename: filenameOrOptions }
  1243. : filenameOrOptions || {};
  1244. if (config) {
  1245. if (configType === "flat") {
  1246. /*
  1247. * Because of how Webpack packages up the files, we can't
  1248. * compare directly to `FlatConfigArray` using `instanceof`
  1249. * because it's not the same `FlatConfigArray` as in the tests.
  1250. * So, we work around it by assuming an array is, in fact, a
  1251. * `FlatConfigArray` if it has a `getConfig()` method.
  1252. */
  1253. let configArray = config;
  1254. if (!Array.isArray(config) || typeof config.getConfig !== "function") {
  1255. configArray = new FlatConfigArray(config);
  1256. configArray.normalizeSync();
  1257. }
  1258. return this._distinguishSuppressedMessages(this._verifyWithFlatConfigArray(textOrSourceCode, configArray, options, true));
  1259. }
  1260. if (typeof config.extractConfig === "function") {
  1261. return this._distinguishSuppressedMessages(this._verifyWithConfigArray(textOrSourceCode, config, options));
  1262. }
  1263. }
  1264. /*
  1265. * If we get to here, it means `config` is just an object rather
  1266. * than a config array so we can go right into linting.
  1267. */
  1268. /*
  1269. * `Linter` doesn't support `overrides` property in configuration.
  1270. * So we cannot apply multiple processors.
  1271. */
  1272. if (options.preprocess || options.postprocess) {
  1273. return this._distinguishSuppressedMessages(this._verifyWithProcessor(textOrSourceCode, config, options));
  1274. }
  1275. return this._distinguishSuppressedMessages(this._verifyWithoutProcessors(textOrSourceCode, config, options));
  1276. }
  1277. /**
  1278. * Verify with a processor.
  1279. * @param {string|SourceCode} textOrSourceCode The source code.
  1280. * @param {FlatConfig} config The config array.
  1281. * @param {VerifyOptions&ProcessorOptions} options The options.
  1282. * @param {FlatConfigArray} [configForRecursive] The `ConfigArray` object to apply multiple processors recursively.
  1283. * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems.
  1284. */
  1285. _verifyWithFlatConfigArrayAndProcessor(textOrSourceCode, config, options, configForRecursive) {
  1286. const filename = options.filename || "<input>";
  1287. const filenameToExpose = normalizeFilename(filename);
  1288. const physicalFilename = options.physicalFilename || filenameToExpose;
  1289. const text = ensureText(textOrSourceCode);
  1290. const preprocess = options.preprocess || (rawText => [rawText]);
  1291. const postprocess = options.postprocess || (messagesList => messagesList.flat());
  1292. const filterCodeBlock =
  1293. options.filterCodeBlock ||
  1294. (blockFilename => blockFilename.endsWith(".js"));
  1295. const originalExtname = path.extname(filename);
  1296. let blocks;
  1297. try {
  1298. blocks = preprocess(text, filenameToExpose);
  1299. } catch (ex) {
  1300. // If the message includes a leading line number, strip it:
  1301. const message = `Preprocessing error: ${ex.message.replace(/^line \d+:/iu, "").trim()}`;
  1302. debug("%s\n%s", message, ex.stack);
  1303. return [
  1304. {
  1305. ruleId: null,
  1306. fatal: true,
  1307. severity: 2,
  1308. message,
  1309. line: ex.lineNumber,
  1310. column: ex.column
  1311. }
  1312. ];
  1313. }
  1314. const messageLists = blocks.map((block, i) => {
  1315. debug("A code block was found: %o", block.filename || "(unnamed)");
  1316. // Keep the legacy behavior.
  1317. if (typeof block === "string") {
  1318. return this._verifyWithFlatConfigArrayAndWithoutProcessors(block, config, options);
  1319. }
  1320. const blockText = block.text;
  1321. const blockName = path.join(filename, `${i}_${block.filename}`);
  1322. // Skip this block if filtered.
  1323. if (!filterCodeBlock(blockName, blockText)) {
  1324. debug("This code block was skipped.");
  1325. return [];
  1326. }
  1327. // Resolve configuration again if the file content or extension was changed.
  1328. if (configForRecursive && (text !== blockText || path.extname(blockName) !== originalExtname)) {
  1329. debug("Resolving configuration again because the file content or extension was changed.");
  1330. return this._verifyWithFlatConfigArray(
  1331. blockText,
  1332. configForRecursive,
  1333. { ...options, filename: blockName, physicalFilename }
  1334. );
  1335. }
  1336. // Does lint.
  1337. return this._verifyWithFlatConfigArrayAndWithoutProcessors(
  1338. blockText,
  1339. config,
  1340. { ...options, filename: blockName, physicalFilename }
  1341. );
  1342. });
  1343. return postprocess(messageLists, filenameToExpose);
  1344. }
  1345. /**
  1346. * Same as linter.verify, except without support for processors.
  1347. * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
  1348. * @param {FlatConfig} providedConfig An ESLintConfig instance to configure everything.
  1349. * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked.
  1350. * @throws {Error} If during rule execution.
  1351. * @returns {(LintMessage|SuppressedLintMessage)[]} The results as an array of messages or an empty array if no messages.
  1352. */
  1353. _verifyWithFlatConfigArrayAndWithoutProcessors(textOrSourceCode, providedConfig, providedOptions) {
  1354. const slots = internalSlotsMap.get(this);
  1355. const config = providedConfig || {};
  1356. const options = normalizeVerifyOptions(providedOptions, config);
  1357. let text;
  1358. // evaluate arguments
  1359. if (typeof textOrSourceCode === "string") {
  1360. slots.lastSourceCode = null;
  1361. text = textOrSourceCode;
  1362. } else {
  1363. slots.lastSourceCode = textOrSourceCode;
  1364. text = textOrSourceCode.text;
  1365. }
  1366. const languageOptions = config.languageOptions;
  1367. languageOptions.ecmaVersion = normalizeEcmaVersionForLanguageOptions(
  1368. languageOptions.ecmaVersion
  1369. );
  1370. /*
  1371. * add configured globals and language globals
  1372. *
  1373. * using Object.assign instead of object spread for performance reasons
  1374. * https://github.com/eslint/eslint/issues/16302
  1375. */
  1376. const configuredGlobals = Object.assign(
  1377. {},
  1378. getGlobalsForEcmaVersion(languageOptions.ecmaVersion),
  1379. languageOptions.sourceType === "commonjs" ? globals.commonjs : void 0,
  1380. languageOptions.globals
  1381. );
  1382. // double check that there is a parser to avoid mysterious error messages
  1383. if (!languageOptions.parser) {
  1384. throw new TypeError(`No parser specified for ${options.filename}`);
  1385. }
  1386. // Espree expects this information to be passed in
  1387. if (isEspree(languageOptions.parser)) {
  1388. const parserOptions = languageOptions.parserOptions;
  1389. if (languageOptions.sourceType) {
  1390. parserOptions.sourceType = languageOptions.sourceType;
  1391. if (
  1392. parserOptions.sourceType === "module" &&
  1393. parserOptions.ecmaFeatures &&
  1394. parserOptions.ecmaFeatures.globalReturn
  1395. ) {
  1396. parserOptions.ecmaFeatures.globalReturn = false;
  1397. }
  1398. }
  1399. }
  1400. const settings = config.settings || {};
  1401. if (!slots.lastSourceCode) {
  1402. const parseResult = parse(
  1403. text,
  1404. languageOptions,
  1405. options.filename
  1406. );
  1407. if (!parseResult.success) {
  1408. return [parseResult.error];
  1409. }
  1410. slots.lastSourceCode = parseResult.sourceCode;
  1411. } else {
  1412. /*
  1413. * If the given source code object as the first argument does not have scopeManager, analyze the scope.
  1414. * This is for backward compatibility (SourceCode is frozen so it cannot rebind).
  1415. */
  1416. if (!slots.lastSourceCode.scopeManager) {
  1417. slots.lastSourceCode = new SourceCode({
  1418. text: slots.lastSourceCode.text,
  1419. ast: slots.lastSourceCode.ast,
  1420. parserServices: slots.lastSourceCode.parserServices,
  1421. visitorKeys: slots.lastSourceCode.visitorKeys,
  1422. scopeManager: analyzeScope(slots.lastSourceCode.ast, languageOptions)
  1423. });
  1424. }
  1425. }
  1426. const sourceCode = slots.lastSourceCode;
  1427. const commentDirectives = options.allowInlineConfig
  1428. ? getDirectiveComments(
  1429. sourceCode.ast,
  1430. ruleId => getRuleFromConfig(ruleId, config),
  1431. options.warnInlineConfig
  1432. )
  1433. : { configuredRules: {}, enabledGlobals: {}, exportedVariables: {}, problems: [], disableDirectives: [] };
  1434. // augment global scope with declared global variables
  1435. addDeclaredGlobals(
  1436. sourceCode.scopeManager.scopes[0],
  1437. configuredGlobals,
  1438. { exportedVariables: commentDirectives.exportedVariables, enabledGlobals: commentDirectives.enabledGlobals }
  1439. );
  1440. const configuredRules = Object.assign({}, config.rules, commentDirectives.configuredRules);
  1441. let lintingProblems;
  1442. try {
  1443. lintingProblems = runRules(
  1444. sourceCode,
  1445. configuredRules,
  1446. ruleId => getRuleFromConfig(ruleId, config),
  1447. void 0,
  1448. languageOptions,
  1449. settings,
  1450. options.filename,
  1451. options.disableFixes,
  1452. slots.cwd,
  1453. providedOptions.physicalFilename
  1454. );
  1455. } catch (err) {
  1456. err.message += `\nOccurred while linting ${options.filename}`;
  1457. debug("An error occurred while traversing");
  1458. debug("Filename:", options.filename);
  1459. if (err.currentNode) {
  1460. const { line } = err.currentNode.loc.start;
  1461. debug("Line:", line);
  1462. err.message += `:${line}`;
  1463. }
  1464. debug("Parser Options:", languageOptions.parserOptions);
  1465. // debug("Parser Path:", parserName);
  1466. debug("Settings:", settings);
  1467. if (err.ruleId) {
  1468. err.message += `\nRule: "${err.ruleId}"`;
  1469. }
  1470. throw err;
  1471. }
  1472. return applyDisableDirectives({
  1473. directives: commentDirectives.disableDirectives,
  1474. disableFixes: options.disableFixes,
  1475. problems: lintingProblems
  1476. .concat(commentDirectives.problems)
  1477. .sort((problemA, problemB) => problemA.line - problemB.line || problemA.column - problemB.column),
  1478. reportUnusedDisableDirectives: options.reportUnusedDisableDirectives
  1479. });
  1480. }
  1481. /**
  1482. * Verify a given code with `ConfigArray`.
  1483. * @param {string|SourceCode} textOrSourceCode The source code.
  1484. * @param {ConfigArray} configArray The config array.
  1485. * @param {VerifyOptions&ProcessorOptions} options The options.
  1486. * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems.
  1487. */
  1488. _verifyWithConfigArray(textOrSourceCode, configArray, options) {
  1489. debug("With ConfigArray: %s", options.filename);
  1490. // Store the config array in order to get plugin envs and rules later.
  1491. internalSlotsMap.get(this).lastConfigArray = configArray;
  1492. // Extract the final config for this file.
  1493. const config = configArray.extractConfig(options.filename);
  1494. const processor =
  1495. config.processor &&
  1496. configArray.pluginProcessors.get(config.processor);
  1497. // Verify.
  1498. if (processor) {
  1499. debug("Apply the processor: %o", config.processor);
  1500. const { preprocess, postprocess, supportsAutofix } = processor;
  1501. const disableFixes = options.disableFixes || !supportsAutofix;
  1502. return this._verifyWithProcessor(
  1503. textOrSourceCode,
  1504. config,
  1505. { ...options, disableFixes, postprocess, preprocess },
  1506. configArray
  1507. );
  1508. }
  1509. return this._verifyWithoutProcessors(textOrSourceCode, config, options);
  1510. }
  1511. /**
  1512. * Verify a given code with a flat config.
  1513. * @param {string|SourceCode} textOrSourceCode The source code.
  1514. * @param {FlatConfigArray} configArray The config array.
  1515. * @param {VerifyOptions&ProcessorOptions} options The options.
  1516. * @param {boolean} [firstCall=false] Indicates if this is being called directly
  1517. * from verify(). (TODO: Remove once eslintrc is removed.)
  1518. * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems.
  1519. */
  1520. _verifyWithFlatConfigArray(textOrSourceCode, configArray, options, firstCall = false) {
  1521. debug("With flat config: %s", options.filename);
  1522. // we need a filename to match configs against
  1523. const filename = options.filename || "__placeholder__.js";
  1524. // Store the config array in order to get plugin envs and rules later.
  1525. internalSlotsMap.get(this).lastConfigArray = configArray;
  1526. const config = configArray.getConfig(filename);
  1527. if (!config) {
  1528. return [
  1529. {
  1530. ruleId: null,
  1531. severity: 1,
  1532. message: `No matching configuration found for ${filename}.`,
  1533. line: 0,
  1534. column: 0
  1535. }
  1536. ];
  1537. }
  1538. // Verify.
  1539. if (config.processor) {
  1540. debug("Apply the processor: %o", config.processor);
  1541. const { preprocess, postprocess, supportsAutofix } = config.processor;
  1542. const disableFixes = options.disableFixes || !supportsAutofix;
  1543. return this._verifyWithFlatConfigArrayAndProcessor(
  1544. textOrSourceCode,
  1545. config,
  1546. { ...options, filename, disableFixes, postprocess, preprocess },
  1547. configArray
  1548. );
  1549. }
  1550. // check for options-based processing
  1551. if (firstCall && (options.preprocess || options.postprocess)) {
  1552. return this._verifyWithFlatConfigArrayAndProcessor(textOrSourceCode, config, options);
  1553. }
  1554. return this._verifyWithFlatConfigArrayAndWithoutProcessors(textOrSourceCode, config, options);
  1555. }
  1556. /**
  1557. * Verify with a processor.
  1558. * @param {string|SourceCode} textOrSourceCode The source code.
  1559. * @param {ConfigData|ExtractedConfig} config The config array.
  1560. * @param {VerifyOptions&ProcessorOptions} options The options.
  1561. * @param {ConfigArray} [configForRecursive] The `ConfigArray` object to apply multiple processors recursively.
  1562. * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems.
  1563. */
  1564. _verifyWithProcessor(textOrSourceCode, config, options, configForRecursive) {
  1565. const filename = options.filename || "<input>";
  1566. const filenameToExpose = normalizeFilename(filename);
  1567. const physicalFilename = options.physicalFilename || filenameToExpose;
  1568. const text = ensureText(textOrSourceCode);
  1569. const preprocess = options.preprocess || (rawText => [rawText]);
  1570. const postprocess = options.postprocess || (messagesList => messagesList.flat());
  1571. const filterCodeBlock =
  1572. options.filterCodeBlock ||
  1573. (blockFilename => blockFilename.endsWith(".js"));
  1574. const originalExtname = path.extname(filename);
  1575. let blocks;
  1576. try {
  1577. blocks = preprocess(text, filenameToExpose);
  1578. } catch (ex) {
  1579. // If the message includes a leading line number, strip it:
  1580. const message = `Preprocessing error: ${ex.message.replace(/^line \d+:/iu, "").trim()}`;
  1581. debug("%s\n%s", message, ex.stack);
  1582. return [
  1583. {
  1584. ruleId: null,
  1585. fatal: true,
  1586. severity: 2,
  1587. message,
  1588. line: ex.lineNumber,
  1589. column: ex.column
  1590. }
  1591. ];
  1592. }
  1593. const messageLists = blocks.map((block, i) => {
  1594. debug("A code block was found: %o", block.filename || "(unnamed)");
  1595. // Keep the legacy behavior.
  1596. if (typeof block === "string") {
  1597. return this._verifyWithoutProcessors(block, config, options);
  1598. }
  1599. const blockText = block.text;
  1600. const blockName = path.join(filename, `${i}_${block.filename}`);
  1601. // Skip this block if filtered.
  1602. if (!filterCodeBlock(blockName, blockText)) {
  1603. debug("This code block was skipped.");
  1604. return [];
  1605. }
  1606. // Resolve configuration again if the file content or extension was changed.
  1607. if (configForRecursive && (text !== blockText || path.extname(blockName) !== originalExtname)) {
  1608. debug("Resolving configuration again because the file content or extension was changed.");
  1609. return this._verifyWithConfigArray(
  1610. blockText,
  1611. configForRecursive,
  1612. { ...options, filename: blockName, physicalFilename }
  1613. );
  1614. }
  1615. // Does lint.
  1616. return this._verifyWithoutProcessors(
  1617. blockText,
  1618. config,
  1619. { ...options, filename: blockName, physicalFilename }
  1620. );
  1621. });
  1622. return postprocess(messageLists, filenameToExpose);
  1623. }
  1624. /**
  1625. * Given a list of reported problems, distinguish problems between normal messages and suppressed messages.
  1626. * The normal messages will be returned and the suppressed messages will be stored as lastSuppressedMessages.
  1627. * @param {Problem[]} problems A list of reported problems.
  1628. * @returns {LintMessage[]} A list of LintMessage.
  1629. */
  1630. _distinguishSuppressedMessages(problems) {
  1631. const messages = [];
  1632. const suppressedMessages = [];
  1633. const slots = internalSlotsMap.get(this);
  1634. for (const problem of problems) {
  1635. if (problem.suppressions) {
  1636. suppressedMessages.push(problem);
  1637. } else {
  1638. messages.push(problem);
  1639. }
  1640. }
  1641. slots.lastSuppressedMessages = suppressedMessages;
  1642. return messages;
  1643. }
  1644. /**
  1645. * Gets the SourceCode object representing the parsed source.
  1646. * @returns {SourceCode} The SourceCode object.
  1647. */
  1648. getSourceCode() {
  1649. return internalSlotsMap.get(this).lastSourceCode;
  1650. }
  1651. /**
  1652. * Gets the list of SuppressedLintMessage produced in the last running.
  1653. * @returns {SuppressedLintMessage[]} The list of SuppressedLintMessage
  1654. */
  1655. getSuppressedMessages() {
  1656. return internalSlotsMap.get(this).lastSuppressedMessages;
  1657. }
  1658. /**
  1659. * Defines a new linting rule.
  1660. * @param {string} ruleId A unique rule identifier
  1661. * @param {Function | Rule} ruleModule Function from context to object mapping AST node types to event handlers
  1662. * @returns {void}
  1663. */
  1664. defineRule(ruleId, ruleModule) {
  1665. assertEslintrcConfig(this);
  1666. internalSlotsMap.get(this).ruleMap.define(ruleId, ruleModule);
  1667. }
  1668. /**
  1669. * Defines many new linting rules.
  1670. * @param {Record<string, Function | Rule>} rulesToDefine map from unique rule identifier to rule
  1671. * @returns {void}
  1672. */
  1673. defineRules(rulesToDefine) {
  1674. assertEslintrcConfig(this);
  1675. Object.getOwnPropertyNames(rulesToDefine).forEach(ruleId => {
  1676. this.defineRule(ruleId, rulesToDefine[ruleId]);
  1677. });
  1678. }
  1679. /**
  1680. * Gets an object with all loaded rules.
  1681. * @returns {Map<string, Rule>} All loaded rules
  1682. */
  1683. getRules() {
  1684. assertEslintrcConfig(this);
  1685. const { lastConfigArray, ruleMap } = internalSlotsMap.get(this);
  1686. return new Map(function *() {
  1687. yield* ruleMap;
  1688. if (lastConfigArray) {
  1689. yield* lastConfigArray.pluginRules;
  1690. }
  1691. }());
  1692. }
  1693. /**
  1694. * Define a new parser module
  1695. * @param {string} parserId Name of the parser
  1696. * @param {Parser} parserModule The parser object
  1697. * @returns {void}
  1698. */
  1699. defineParser(parserId, parserModule) {
  1700. assertEslintrcConfig(this);
  1701. internalSlotsMap.get(this).parserMap.set(parserId, parserModule);
  1702. }
  1703. /**
  1704. * Performs multiple autofix passes over the text until as many fixes as possible
  1705. * have been applied.
  1706. * @param {string} text The source text to apply fixes to.
  1707. * @param {ConfigData|ConfigArray|FlatConfigArray} config The ESLint config object to use.
  1708. * @param {VerifyOptions&ProcessorOptions&FixOptions} options The ESLint options object to use.
  1709. * @returns {{fixed:boolean,messages:LintMessage[],output:string}} The result of the fix operation as returned from the
  1710. * SourceCodeFixer.
  1711. */
  1712. verifyAndFix(text, config, options) {
  1713. let messages = [],
  1714. fixedResult,
  1715. fixed = false,
  1716. passNumber = 0,
  1717. currentText = text;
  1718. const debugTextDescription = options && options.filename || `${text.slice(0, 10)}...`;
  1719. const shouldFix = options && typeof options.fix !== "undefined" ? options.fix : true;
  1720. /**
  1721. * This loop continues until one of the following is true:
  1722. *
  1723. * 1. No more fixes have been applied.
  1724. * 2. Ten passes have been made.
  1725. *
  1726. * That means anytime a fix is successfully applied, there will be another pass.
  1727. * Essentially, guaranteeing a minimum of two passes.
  1728. */
  1729. do {
  1730. passNumber++;
  1731. debug(`Linting code for ${debugTextDescription} (pass ${passNumber})`);
  1732. messages = this.verify(currentText, config, options);
  1733. debug(`Generating fixed text for ${debugTextDescription} (pass ${passNumber})`);
  1734. fixedResult = SourceCodeFixer.applyFixes(currentText, messages, shouldFix);
  1735. /*
  1736. * stop if there are any syntax errors.
  1737. * 'fixedResult.output' is a empty string.
  1738. */
  1739. if (messages.length === 1 && messages[0].fatal) {
  1740. break;
  1741. }
  1742. // keep track if any fixes were ever applied - important for return value
  1743. fixed = fixed || fixedResult.fixed;
  1744. // update to use the fixed output instead of the original text
  1745. currentText = fixedResult.output;
  1746. } while (
  1747. fixedResult.fixed &&
  1748. passNumber < MAX_AUTOFIX_PASSES
  1749. );
  1750. /*
  1751. * If the last result had fixes, we need to lint again to be sure we have
  1752. * the most up-to-date information.
  1753. */
  1754. if (fixedResult.fixed) {
  1755. fixedResult.messages = this.verify(currentText, config, options);
  1756. }
  1757. // ensure the last result properly reflects if fixes were done
  1758. fixedResult.fixed = fixed;
  1759. fixedResult.output = currentText;
  1760. return fixedResult;
  1761. }
  1762. }
  1763. module.exports = {
  1764. Linter,
  1765. /**
  1766. * Get the internal slots of a given Linter instance for tests.
  1767. * @param {Linter} instance The Linter instance to get.
  1768. * @returns {LinterInternalSlots} The internal slots.
  1769. */
  1770. getLinterInternalSlots(instance) {
  1771. return internalSlotsMap.get(instance);
  1772. }
  1773. };