linter.js 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676
  1. /**
  2. * @fileoverview Main Linter Class
  3. * @author Gyandeep Singh
  4. * @author aladdin-add
  5. */
  6. "use strict";
  7. //------------------------------------------------------------------------------
  8. // Requirements
  9. //------------------------------------------------------------------------------
  10. const path = require("node:path"),
  11. eslintScope = require("eslint-scope"),
  12. evk = require("eslint-visitor-keys"),
  13. espree = require("espree"),
  14. merge = require("lodash.merge"),
  15. pkg = require("../../package.json"),
  16. {
  17. Legacy: {
  18. ConfigOps,
  19. ConfigValidator,
  20. environments: BuiltInEnvironments,
  21. },
  22. } = require("@eslint/eslintrc/universal"),
  23. Traverser = require("../shared/traverser"),
  24. { SourceCode } = require("../languages/js/source-code"),
  25. applyDisableDirectives = require("./apply-disable-directives"),
  26. { ConfigCommentParser } = require("@eslint/plugin-kit"),
  27. Rules = require("./rules"),
  28. SourceCodeFixer = require("./source-code-fixer"),
  29. { SourceCodeVisitor } = require("./source-code-visitor"),
  30. timing = require("./timing");
  31. const { FlatConfigArray } = require("../config/flat-config-array");
  32. const { startTime, endTime } = require("../shared/stats");
  33. const { assertIsRuleSeverity } = require("../config/flat-config-schema");
  34. const {
  35. normalizeSeverityToString,
  36. normalizeSeverityToNumber,
  37. } = require("../shared/severity");
  38. const { deepMergeArrays } = require("../shared/deep-merge-arrays");
  39. const jslang = require("../languages/js");
  40. const {
  41. activeFlags,
  42. inactiveFlags,
  43. getInactivityReasonMessage,
  44. } = require("../shared/flags");
  45. const debug = require("debug")("eslint:linter");
  46. const MAX_AUTOFIX_PASSES = 10;
  47. const DEFAULT_PARSER_NAME = "espree";
  48. const DEFAULT_ECMA_VERSION = 5;
  49. const commentParser = new ConfigCommentParser();
  50. const parserSymbol = Symbol.for("eslint.RuleTester.parser");
  51. const { LATEST_ECMA_VERSION } = require("../../conf/ecma-version");
  52. const { VFile } = require("./vfile");
  53. const { ParserService } = require("../services/parser-service");
  54. const { FileContext } = require("./file-context");
  55. const { ProcessorService } = require("../services/processor-service");
  56. const { containsDifferentProperty } = require("../shared/option-utils");
  57. const { Config } = require("../config/config");
  58. const { WarningService } = require("../services/warning-service");
  59. const { SourceCodeTraverser } = require("./source-code-traverser");
  60. const { FileReport, updateLocationInformation } = require("./file-report");
  61. //------------------------------------------------------------------------------
  62. // Typedefs
  63. //------------------------------------------------------------------------------
  64. /** @import { Language, LanguageOptions, RuleConfig, RuleDefinition, RuleSeverity } from "@eslint/core" */
  65. /** @typedef {import("../types").Linter.Config} Config */
  66. /** @typedef {import("../types").ESLint.ConfigData} ConfigData */
  67. /** @typedef {import("../types").ESLint.Environment} Environment */
  68. /** @typedef {import("../types").Linter.GlobalConf} GlobalConf */
  69. /** @typedef {import("../types").Linter.LanguageOptions} JSLanguageOptions */
  70. /** @typedef {import("../types").Linter.LintMessage} LintMessage */
  71. /** @typedef {import("../types").Linter.Parser} Parser */
  72. /** @typedef {import("../types").Linter.ParserOptions} ParserOptions */
  73. /** @typedef {import("../types").Linter.Processor} Processor */
  74. /** @typedef {import("../types").Rule.RuleModule} Rule */
  75. /** @typedef {import("../types").Linter.StringSeverity} StringSeverity */
  76. /** @typedef {import("../types").Linter.SuppressedLintMessage} SuppressedLintMessage */
  77. /** @typedef {import("../types").Linter.TimePass} TimePass */
  78. /* eslint-disable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/4#issuecomment-778805577 */
  79. /**
  80. * @template T
  81. * @typedef {{ [P in keyof T]-?: T[P] }} Required
  82. */
  83. /* eslint-enable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/4#issuecomment-778805577 */
  84. /**
  85. * @typedef {Object} DisableDirective
  86. * @property {("disable"|"enable"|"disable-line"|"disable-next-line")} type Type of directive
  87. * @property {number} line The line number
  88. * @property {number} column The column number
  89. * @property {(string|null)} ruleId The rule ID
  90. * @property {string} justification The justification of directive
  91. */
  92. /**
  93. * The private data for `Linter` instance.
  94. * @typedef {Object} LinterInternalSlots
  95. * @property {ConfigArray|null} lastConfigArray The `ConfigArray` instance that the last `verify()` call used.
  96. * @property {SourceCode|null} lastSourceCode The `SourceCode` instance that the last `verify()` call used.
  97. * @property {SuppressedLintMessage[]} lastSuppressedMessages The `SuppressedLintMessage[]` instance that the last `verify()` call produced.
  98. * @property {Map<string, Parser>} parserMap The loaded parsers.
  99. * @property {{ passes: TimePass[]; }} times The times spent on applying a rule to a file (see `stats` option).
  100. * @property {Rules} ruleMap The loaded rules.
  101. * @property {WarningService} warningService The warning service.
  102. */
  103. /**
  104. * @typedef {Object} VerifyOptions
  105. * @property {boolean} [allowInlineConfig] Allow/disallow inline comments' ability
  106. * to change config once it is set. Defaults to true if not supplied.
  107. * Useful if you want to validate JS without comments overriding rules.
  108. * @property {boolean} [disableFixes] if `true` then the linter doesn't make `fix`
  109. * properties into the lint result.
  110. * @property {string} [filename] the filename of the source code.
  111. * @property {boolean | "off" | "warn" | "error"} [reportUnusedDisableDirectives] Adds reported errors for
  112. * unused `eslint-disable` directives.
  113. * @property {Function} [ruleFilter] A predicate function that determines whether a given rule should run.
  114. */
  115. /**
  116. * @typedef {Object} ProcessorOptions
  117. * @property {(filename:string, text:string) => boolean} [filterCodeBlock] the
  118. * predicate function that selects adopt code blocks.
  119. * @property {Processor.postprocess} [postprocess] postprocessor for report
  120. * messages. If provided, this should accept an array of the message lists
  121. * for each code block returned from the preprocessor, apply a mapping to
  122. * the messages as appropriate, and return a one-dimensional array of
  123. * messages.
  124. * @property {Processor.preprocess} [preprocess] preprocessor for source text.
  125. * If provided, this should accept a string of source text, and return an
  126. * array of code blocks to lint.
  127. */
  128. /**
  129. * @typedef {Object} FixOptions
  130. * @property {boolean | ((message: LintMessage) => boolean)} [fix] Determines
  131. * whether fixes should be applied.
  132. */
  133. /**
  134. * @typedef {Object} InternalOptions
  135. * @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.
  136. * @property {StringSeverity} reportUnusedDisableDirectives Severity to report unused disable directives, if not "off" (boolean values were normalized).
  137. * @property {StringSeverity} reportUnusedInlineConfigs Severity to report unused inline configs, if not "off".
  138. */
  139. //------------------------------------------------------------------------------
  140. // Helpers
  141. //------------------------------------------------------------------------------
  142. /**
  143. * Determines if a given object is Espree.
  144. * @param {Object} parser The parser to check.
  145. * @returns {boolean} True if the parser is Espree or false if not.
  146. */
  147. function isEspree(parser) {
  148. return !!(parser === espree || parser[parserSymbol] === espree);
  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(
  160. globalScope,
  161. configGlobals,
  162. { exportedVariables, enabledGlobals },
  163. ) {
  164. // Define configured global variables.
  165. for (const id of new Set([
  166. ...Object.keys(configGlobals),
  167. ...Object.keys(enabledGlobals),
  168. ])) {
  169. /*
  170. * `ConfigOps.normalizeConfigGlobal` will throw an error if a configured global value is invalid. However, these errors would
  171. * typically be caught when validating a config anyway (validity for inline global comments is checked separately).
  172. */
  173. const configValue =
  174. configGlobals[id] === void 0
  175. ? void 0
  176. : ConfigOps.normalizeConfigGlobal(configGlobals[id]);
  177. const commentValue = enabledGlobals[id] && enabledGlobals[id].value;
  178. const value = commentValue || configValue;
  179. const sourceComments =
  180. enabledGlobals[id] && enabledGlobals[id].comments;
  181. if (value === "off") {
  182. continue;
  183. }
  184. let variable = globalScope.set.get(id);
  185. if (!variable) {
  186. variable = new eslintScope.Variable(id, globalScope);
  187. globalScope.variables.push(variable);
  188. globalScope.set.set(id, variable);
  189. }
  190. variable.eslintImplicitGlobalSetting = configValue;
  191. variable.eslintExplicitGlobal = sourceComments !== void 0;
  192. variable.eslintExplicitGlobalComments = sourceComments;
  193. variable.writeable = value === "writable";
  194. }
  195. // mark all exported variables as such
  196. Object.keys(exportedVariables).forEach(name => {
  197. const variable = globalScope.set.get(name);
  198. if (variable) {
  199. variable.eslintUsed = true;
  200. variable.eslintExported = true;
  201. }
  202. });
  203. /*
  204. * "through" contains all references which definitions cannot be found.
  205. * Since we augment the global scope using configuration, we need to update
  206. * references and remove the ones that were added by configuration.
  207. */
  208. globalScope.through = globalScope.through.filter(reference => {
  209. const name = reference.identifier.name;
  210. const variable = globalScope.set.get(name);
  211. if (variable) {
  212. /*
  213. * Links the variable and the reference.
  214. * And this reference is removed from `Scope#through`.
  215. */
  216. reference.resolved = variable;
  217. variable.references.push(reference);
  218. return false;
  219. }
  220. return true;
  221. });
  222. }
  223. /**
  224. * Wraps the value in an Array if it isn't already one.
  225. * @template T
  226. * @param {T|T[]} value Value to be wrapped.
  227. * @returns {Array} The value as an array.
  228. */
  229. function asArray(value) {
  230. return Array.isArray(value) ? value : [value];
  231. }
  232. /**
  233. * Pushes a problem to inlineConfigProblems if ruleOptions are redundant.
  234. * @param {Config} config Provided config.
  235. * @param {Object} loc A line/column location
  236. * @param {FileReport} report Report that may be added to.
  237. * @param {string} ruleId The rule ID.
  238. * @param {Array} ruleOptions The rule options, merged with the config's.
  239. * @param {Array} ruleOptionsInline The rule options from the comment.
  240. * @param {"error"|"warn"} severity The severity to report.
  241. * @returns {void}
  242. */
  243. function addProblemIfSameSeverityAndOptions(
  244. config,
  245. loc,
  246. report,
  247. ruleId,
  248. ruleOptions,
  249. ruleOptionsInline,
  250. severity,
  251. ) {
  252. const existingConfigRaw = config.rules?.[ruleId];
  253. const existingConfig = existingConfigRaw
  254. ? asArray(existingConfigRaw)
  255. : ["off"];
  256. const existingSeverity = normalizeSeverityToString(existingConfig[0]);
  257. const inlineSeverity = normalizeSeverityToString(ruleOptions[0]);
  258. const sameSeverity = existingSeverity === inlineSeverity;
  259. if (!sameSeverity) {
  260. return;
  261. }
  262. const alreadyConfigured = existingConfigRaw
  263. ? `is already configured to '${existingSeverity}'`
  264. : "is not enabled so can't be turned off";
  265. let message;
  266. if (
  267. (existingConfig.length === 1 && ruleOptions.length === 1) ||
  268. existingSeverity === "off"
  269. ) {
  270. message = `Unused inline config ('${ruleId}' ${alreadyConfigured}).`;
  271. } else if (
  272. !containsDifferentProperty(
  273. ruleOptions.slice(1),
  274. existingConfig.slice(1),
  275. )
  276. ) {
  277. message =
  278. ruleOptionsInline.length === 1
  279. ? `Unused inline config ('${ruleId}' ${alreadyConfigured}).`
  280. : `Unused inline config ('${ruleId}' ${alreadyConfigured} with the same options).`;
  281. }
  282. if (message) {
  283. const numericSeverity = normalizeSeverityToNumber(severity);
  284. const descriptor = {
  285. message,
  286. loc,
  287. };
  288. if (numericSeverity === 1) {
  289. report.addWarning(descriptor);
  290. } else if (numericSeverity === 2) {
  291. report.addError(descriptor);
  292. }
  293. }
  294. }
  295. /**
  296. * Creates a collection of disable directives from a comment
  297. * @param {Object} options to create disable directives
  298. * @param {("disable"|"enable"|"disable-line"|"disable-next-line")} options.type The type of directive comment
  299. * @param {string} options.value The value after the directive in the comment
  300. * comment specified no specific rules, so it applies to all rules (e.g. `eslint-disable`)
  301. * @param {string} options.justification The justification of the directive
  302. * @param {ASTNode|token} options.node The Comment node/token.
  303. * @param {function(string): {create: Function}} ruleMapper A map from rule IDs to defined rules
  304. * @param {Language} language The language to use to adjust the location information.
  305. * @param {SourceCode} sourceCode The SourceCode object to get comments from.
  306. * @param {FileReport} report The report to add problems to.
  307. * @returns {Object[]} Directives from the comment
  308. */
  309. function createDisableDirectives(
  310. { type, value, justification, node },
  311. ruleMapper,
  312. language,
  313. sourceCode,
  314. report,
  315. ) {
  316. const ruleIds = Object.keys(commentParser.parseListConfig(value));
  317. const directiveRules = ruleIds.length ? ruleIds : [null];
  318. const directives = []; // valid disable directives
  319. const parentDirective = { node, value, ruleIds };
  320. for (const ruleId of directiveRules) {
  321. const loc = sourceCode.getLoc(node);
  322. // push to directives, if the rule is defined(including null, e.g. /*eslint enable*/)
  323. if (ruleId === null || !!ruleMapper(ruleId)) {
  324. if (type === "disable-next-line") {
  325. const { line, column } = updateLocationInformation(
  326. loc.end,
  327. language,
  328. );
  329. directives.push({
  330. parentDirective,
  331. type,
  332. line,
  333. column,
  334. ruleId,
  335. justification,
  336. });
  337. } else {
  338. const { line, column } = updateLocationInformation(
  339. loc.start,
  340. language,
  341. );
  342. directives.push({
  343. parentDirective,
  344. type,
  345. line,
  346. column,
  347. ruleId,
  348. justification,
  349. });
  350. }
  351. } else {
  352. report.addError({ ruleId, loc });
  353. }
  354. }
  355. return directives;
  356. }
  357. /**
  358. * Parses comments in file to extract file-specific config of rules, globals
  359. * and environments and merges them with global config; also code blocks
  360. * where reporting is disabled or enabled and merges them with reporting config.
  361. * @param {SourceCode} sourceCode The SourceCode object to get comments from.
  362. * @param {function(string): {create: Function}} ruleMapper A map from rule IDs to defined rules
  363. * @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.
  364. * @param {ConfigData} config Provided config.
  365. * @param {FileReport} report The report to add problems to.
  366. * @returns {{configuredRules: Object, enabledGlobals: {value:string,comment:Token}[], exportedVariables: Object, disableDirectives: DisableDirective[]}}
  367. * A collection of the directive comments that were found, along with any problems that occurred when parsing
  368. */
  369. function getDirectiveComments(
  370. sourceCode,
  371. ruleMapper,
  372. warnInlineConfig,
  373. config,
  374. report,
  375. ) {
  376. const configuredRules = {};
  377. const enabledGlobals = Object.create(null);
  378. const exportedVariables = {};
  379. const disableDirectives = [];
  380. const validator = new ConfigValidator({
  381. builtInRules: Rules,
  382. });
  383. sourceCode
  384. .getInlineConfigNodes()
  385. .filter(token => token.type !== "Shebang")
  386. .forEach(comment => {
  387. const directive = commentParser.parseDirective(comment.value);
  388. if (!directive) {
  389. return;
  390. }
  391. const {
  392. label,
  393. value,
  394. justification: justificationPart,
  395. } = directive;
  396. const lineCommentSupported =
  397. /^eslint-disable-(?:next-)?line$/u.test(label);
  398. if (comment.type === "Line" && !lineCommentSupported) {
  399. return;
  400. }
  401. const loc = sourceCode.getLoc(comment);
  402. if (warnInlineConfig) {
  403. const kind =
  404. comment.type === "Block" ? `/*${label}*/` : `//${label}`;
  405. report.addWarning({
  406. ruleId: null,
  407. message: `'${kind}' has no effect because you have 'noInlineConfig' setting in ${warnInlineConfig}.`,
  408. loc,
  409. });
  410. return;
  411. }
  412. if (
  413. label === "eslint-disable-line" &&
  414. loc.start.line !== loc.end.line
  415. ) {
  416. const message = `${label} comment should not span multiple lines.`;
  417. report.addError({
  418. message,
  419. loc,
  420. });
  421. return;
  422. }
  423. switch (label) {
  424. case "eslint-disable":
  425. case "eslint-enable":
  426. case "eslint-disable-next-line":
  427. case "eslint-disable-line": {
  428. const directiveType = label.slice("eslint-".length);
  429. const directives = createDisableDirectives(
  430. {
  431. type: directiveType,
  432. value,
  433. justification: justificationPart,
  434. node: comment,
  435. },
  436. ruleMapper,
  437. jslang,
  438. sourceCode,
  439. report,
  440. );
  441. disableDirectives.push(...directives);
  442. break;
  443. }
  444. case "exported":
  445. Object.assign(
  446. exportedVariables,
  447. commentParser.parseListConfig(value),
  448. );
  449. break;
  450. case "globals":
  451. case "global":
  452. for (const [id, idSetting] of Object.entries(
  453. commentParser.parseStringConfig(value),
  454. )) {
  455. let normalizedValue;
  456. try {
  457. normalizedValue =
  458. ConfigOps.normalizeConfigGlobal(idSetting);
  459. } catch (err) {
  460. report.addError({
  461. loc,
  462. message: err.message,
  463. });
  464. continue;
  465. }
  466. if (enabledGlobals[id]) {
  467. enabledGlobals[id].comments.push(comment);
  468. enabledGlobals[id].value = normalizedValue;
  469. } else {
  470. enabledGlobals[id] = {
  471. comments: [comment],
  472. value: normalizedValue,
  473. };
  474. }
  475. }
  476. break;
  477. case "eslint": {
  478. const parseResult =
  479. commentParser.parseJSONLikeConfig(value);
  480. if (parseResult.ok) {
  481. Object.keys(parseResult.config).forEach(name => {
  482. const rule = ruleMapper(name);
  483. const ruleValue = parseResult.config[name];
  484. if (!rule) {
  485. report.addError({ ruleId: name, loc });
  486. return;
  487. }
  488. if (Object.hasOwn(configuredRules, name)) {
  489. report.addError({
  490. message: `Rule "${name}" is already configured by another configuration comment in the preceding code. This configuration is ignored.`,
  491. loc,
  492. });
  493. return;
  494. }
  495. let ruleOptions = asArray(ruleValue);
  496. /*
  497. * If the rule was already configured, inline rule configuration that
  498. * only has severity should retain options from the config and just override the severity.
  499. *
  500. * Example:
  501. *
  502. * {
  503. * rules: {
  504. * curly: ["error", "multi"]
  505. * }
  506. * }
  507. *
  508. * /* eslint curly: ["warn"] * /
  509. *
  510. * Results in:
  511. *
  512. * curly: ["warn", "multi"]
  513. */
  514. if (
  515. /*
  516. * If inline config for the rule has only severity
  517. */
  518. ruleOptions.length === 1 &&
  519. /*
  520. * And the rule was already configured
  521. */
  522. config.rules &&
  523. Object.hasOwn(config.rules, name)
  524. ) {
  525. /*
  526. * Then use severity from the inline config and options from the provided config
  527. */
  528. ruleOptions = [
  529. ruleOptions[0], // severity from the inline config
  530. ...asArray(config.rules[name]).slice(1), // options from the provided config
  531. ];
  532. }
  533. try {
  534. validator.validateRuleOptions(
  535. rule,
  536. name,
  537. ruleOptions,
  538. );
  539. } catch (err) {
  540. /*
  541. * If the rule has invalid `meta.schema`, throw the error because
  542. * this is not an invalid inline configuration but an invalid rule.
  543. */
  544. if (
  545. err.code ===
  546. "ESLINT_INVALID_RULE_OPTIONS_SCHEMA"
  547. ) {
  548. throw err;
  549. }
  550. report.addError({
  551. ruleId: name,
  552. message: err.message,
  553. loc,
  554. });
  555. // do not apply the config, if found invalid options.
  556. return;
  557. }
  558. configuredRules[name] = ruleOptions;
  559. });
  560. } else {
  561. report.addFatal({
  562. loc,
  563. message: parseResult.error.message,
  564. });
  565. }
  566. break;
  567. }
  568. // no default
  569. }
  570. });
  571. return {
  572. configuredRules,
  573. enabledGlobals,
  574. exportedVariables,
  575. disableDirectives,
  576. };
  577. }
  578. /**
  579. * Parses comments in file to extract disable directives.
  580. * @param {SourceCode} sourceCode The SourceCode object to get comments from.
  581. * @param {function(string): {create: Function}} ruleMapper A map from rule IDs to defined rules
  582. * @param {Language} language The language to use to adjust the location information
  583. * @param {FileReport} report The report to add problems to.
  584. * @returns {DisableDirective[]}
  585. * A collection of the directive comments that were found, along with any problems that occurred when parsing
  586. */
  587. function getDirectiveCommentsForFlatConfig(
  588. sourceCode,
  589. ruleMapper,
  590. language,
  591. report,
  592. ) {
  593. const disableDirectives = [];
  594. if (sourceCode.getDisableDirectives) {
  595. const { directives: directivesSources, problems: directivesProblems } =
  596. sourceCode.getDisableDirectives();
  597. if (Array.isArray(directivesProblems)) {
  598. directivesProblems.forEach(problem => report.addError(problem));
  599. }
  600. directivesSources.forEach(directive => {
  601. const directives = createDisableDirectives(
  602. directive,
  603. ruleMapper,
  604. language,
  605. sourceCode,
  606. report,
  607. );
  608. disableDirectives.push(...directives);
  609. });
  610. }
  611. return disableDirectives;
  612. }
  613. /**
  614. * Normalize ECMAScript version from the initial config
  615. * @param {Parser} parser The parser which uses this options.
  616. * @param {number} ecmaVersion ECMAScript version from the initial config
  617. * @returns {number} normalized ECMAScript version
  618. */
  619. function normalizeEcmaVersion(parser, ecmaVersion) {
  620. if (isEspree(parser)) {
  621. if (ecmaVersion === "latest") {
  622. return espree.latestEcmaVersion;
  623. }
  624. }
  625. /*
  626. * Calculate ECMAScript edition number from official year version starting with
  627. * ES2015, which corresponds with ES6 (or a difference of 2009).
  628. */
  629. return ecmaVersion >= 2015 ? ecmaVersion - 2009 : ecmaVersion;
  630. }
  631. /**
  632. * Normalize ECMAScript version from the initial config into languageOptions (year)
  633. * format.
  634. * @param {any} [ecmaVersion] ECMAScript version from the initial config
  635. * @returns {number} normalized ECMAScript version
  636. */
  637. function normalizeEcmaVersionForLanguageOptions(ecmaVersion) {
  638. switch (ecmaVersion) {
  639. case 3:
  640. return 3;
  641. // void 0 = no ecmaVersion specified so use the default
  642. case 5:
  643. case void 0:
  644. return 5;
  645. default:
  646. if (typeof ecmaVersion === "number") {
  647. return ecmaVersion >= 2015 ? ecmaVersion : ecmaVersion + 2009;
  648. }
  649. }
  650. /*
  651. * We default to the latest supported ecmaVersion for everything else.
  652. * Remember, this is for languageOptions.ecmaVersion, which sets the version
  653. * that is used for a number of processes inside of ESLint. It's normally
  654. * safe to assume people want the latest unless otherwise specified.
  655. */
  656. return LATEST_ECMA_VERSION;
  657. }
  658. const eslintEnvPattern = /\/\*\s*eslint-env\s.+?(?:\*\/|$)/gsu;
  659. /**
  660. * Checks whether or not there is a comment which has "eslint-env *" in a given text.
  661. * @param {string} text A source code text to check.
  662. * @returns {Object|null} A result of parseListConfig() with "eslint-env *" comment.
  663. */
  664. function findEslintEnv(text) {
  665. let match, retv;
  666. eslintEnvPattern.lastIndex = 0;
  667. while ((match = eslintEnvPattern.exec(text)) !== null) {
  668. if (match[0].endsWith("*/")) {
  669. retv = Object.assign(
  670. retv || {},
  671. commentParser.parseListConfig(
  672. commentParser.parseDirective(match[0].slice(2, -2)).value,
  673. ),
  674. );
  675. }
  676. }
  677. return retv;
  678. }
  679. /**
  680. * Convert "/path/to/<text>" to "<text>".
  681. * `CLIEngine#executeOnText()` method gives "/path/to/<text>" if the filename
  682. * was omitted because `configArray.extractConfig()` requires an absolute path.
  683. * But the linter should pass `<text>` to `RuleContext#filename` in that
  684. * case.
  685. * Also, code blocks can have their virtual filename. If the parent filename was
  686. * `<text>`, the virtual filename is `<text>/0_foo.js` or something like (i.e.,
  687. * it's not an absolute path).
  688. * @param {string} filename The filename to normalize.
  689. * @returns {string} The normalized filename.
  690. */
  691. function normalizeFilename(filename) {
  692. const parts = filename.split(path.sep);
  693. const index = parts.lastIndexOf("<text>");
  694. return index === -1 ? filename : parts.slice(index).join(path.sep);
  695. }
  696. /**
  697. * Normalizes the possible options for `linter.verify` and `linter.verifyAndFix` to a
  698. * consistent shape.
  699. * @param {VerifyOptions} providedOptions Options
  700. * @param {Config|ConfigData} config Config.
  701. * @returns {Required<VerifyOptions> & InternalOptions} Normalized options
  702. */
  703. function normalizeVerifyOptions(providedOptions, config) {
  704. const linterOptions = config.linterOptions || config;
  705. // .noInlineConfig for eslintrc, .linterOptions.noInlineConfig for flat
  706. const disableInlineConfig = linterOptions.noInlineConfig === true;
  707. const ignoreInlineConfig = providedOptions.allowInlineConfig === false;
  708. const configNameOfNoInlineConfig = config.configNameOfNoInlineConfig
  709. ? ` (${config.configNameOfNoInlineConfig})`
  710. : "";
  711. let reportUnusedDisableDirectives =
  712. providedOptions.reportUnusedDisableDirectives;
  713. if (typeof reportUnusedDisableDirectives === "boolean") {
  714. reportUnusedDisableDirectives = reportUnusedDisableDirectives
  715. ? "error"
  716. : "off";
  717. }
  718. if (typeof reportUnusedDisableDirectives !== "string") {
  719. if (typeof linterOptions.reportUnusedDisableDirectives === "boolean") {
  720. reportUnusedDisableDirectives =
  721. linterOptions.reportUnusedDisableDirectives ? "warn" : "off";
  722. } else {
  723. reportUnusedDisableDirectives =
  724. linterOptions.reportUnusedDisableDirectives === void 0
  725. ? "off"
  726. : normalizeSeverityToString(
  727. linterOptions.reportUnusedDisableDirectives,
  728. );
  729. }
  730. }
  731. const reportUnusedInlineConfigs =
  732. linterOptions.reportUnusedInlineConfigs === void 0
  733. ? "off"
  734. : normalizeSeverityToString(
  735. linterOptions.reportUnusedInlineConfigs,
  736. );
  737. let ruleFilter = providedOptions.ruleFilter;
  738. if (typeof ruleFilter !== "function") {
  739. ruleFilter = () => true;
  740. }
  741. return {
  742. filename: normalizeFilename(providedOptions.filename || "<input>"),
  743. allowInlineConfig: !ignoreInlineConfig,
  744. warnInlineConfig:
  745. disableInlineConfig && !ignoreInlineConfig
  746. ? `your config${configNameOfNoInlineConfig}`
  747. : null,
  748. reportUnusedDisableDirectives,
  749. reportUnusedInlineConfigs,
  750. disableFixes: Boolean(providedOptions.disableFixes),
  751. stats: providedOptions.stats,
  752. ruleFilter,
  753. };
  754. }
  755. /**
  756. * Combines the provided parserOptions with the options from environments
  757. * @param {Parser} parser The parser which uses this options.
  758. * @param {ParserOptions} providedOptions The provided 'parserOptions' key in a config
  759. * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments
  760. * @returns {ParserOptions} Resulting parser options after merge
  761. */
  762. function resolveParserOptions(parser, providedOptions, enabledEnvironments) {
  763. const parserOptionsFromEnv = enabledEnvironments
  764. .filter(env => env.parserOptions)
  765. .reduce(
  766. (parserOptions, env) => merge(parserOptions, env.parserOptions),
  767. {},
  768. );
  769. const mergedParserOptions = merge(
  770. parserOptionsFromEnv,
  771. providedOptions || {},
  772. );
  773. const isModule = mergedParserOptions.sourceType === "module";
  774. if (isModule) {
  775. /*
  776. * can't have global return inside of modules
  777. * TODO: espree validate parserOptions.globalReturn when sourceType is setting to module.(@aladdin-add)
  778. */
  779. mergedParserOptions.ecmaFeatures = Object.assign(
  780. {},
  781. mergedParserOptions.ecmaFeatures,
  782. { globalReturn: false },
  783. );
  784. }
  785. mergedParserOptions.ecmaVersion = normalizeEcmaVersion(
  786. parser,
  787. mergedParserOptions.ecmaVersion,
  788. );
  789. return mergedParserOptions;
  790. }
  791. /**
  792. * Converts parserOptions to languageOptions for backwards compatibility with eslintrc.
  793. * @param {ConfigData} config Config object.
  794. * @param {Object} config.globals Global variable definitions.
  795. * @param {Parser} config.parser The parser to use.
  796. * @param {ParserOptions} config.parserOptions The parserOptions to use.
  797. * @returns {JSLanguageOptions} The languageOptions equivalent.
  798. */
  799. function createLanguageOptions({
  800. globals: configuredGlobals,
  801. parser,
  802. parserOptions,
  803. }) {
  804. const { ecmaVersion, sourceType } = parserOptions;
  805. return {
  806. globals: configuredGlobals,
  807. ecmaVersion: normalizeEcmaVersionForLanguageOptions(ecmaVersion),
  808. sourceType,
  809. parser,
  810. parserOptions,
  811. };
  812. }
  813. /**
  814. * Combines the provided globals object with the globals from environments
  815. * @param {Record<string, GlobalConf>} providedGlobals The 'globals' key in a config
  816. * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments
  817. * @returns {Record<string, GlobalConf>} The resolved globals object
  818. */
  819. function resolveGlobals(providedGlobals, enabledEnvironments) {
  820. return Object.assign(
  821. Object.create(null),
  822. ...enabledEnvironments
  823. .filter(env => env.globals)
  824. .map(env => env.globals),
  825. providedGlobals,
  826. );
  827. }
  828. /**
  829. * Store time measurements in map
  830. * @param {number} time Time measurement
  831. * @param {Object} timeOpts Options relating which time was measured
  832. * @param {WeakMap<Linter, LinterInternalSlots>} slots Linter internal slots map
  833. * @returns {void}
  834. */
  835. function storeTime(time, timeOpts, slots) {
  836. const { type, key } = timeOpts;
  837. if (!slots.times) {
  838. slots.times = { passes: [{}] };
  839. }
  840. const passIndex = slots.fixPasses;
  841. if (passIndex > slots.times.passes.length - 1) {
  842. slots.times.passes.push({});
  843. }
  844. if (key) {
  845. slots.times.passes[passIndex][type] ??= {};
  846. slots.times.passes[passIndex][type][key] ??= { total: 0 };
  847. slots.times.passes[passIndex][type][key].total += time;
  848. } else {
  849. slots.times.passes[passIndex][type] ??= { total: 0 };
  850. slots.times.passes[passIndex][type].total += time;
  851. }
  852. }
  853. /**
  854. * Get the options for a rule (not including severity), if any
  855. * @param {RuleConfig} ruleConfig rule configuration
  856. * @param {Object|undefined} defaultOptions rule.meta.defaultOptions
  857. * @returns {Array} of rule options, empty Array if none
  858. */
  859. function getRuleOptions(ruleConfig, defaultOptions) {
  860. if (Array.isArray(ruleConfig)) {
  861. return deepMergeArrays(defaultOptions, ruleConfig.slice(1));
  862. }
  863. return defaultOptions ?? [];
  864. }
  865. /**
  866. * Analyze scope of the given AST.
  867. * @param {ASTNode} ast The `Program` node to analyze.
  868. * @param {JSLanguageOptions} languageOptions The language options.
  869. * @param {Record<string, string[]>} visitorKeys The visitor keys.
  870. * @returns {ScopeManager} The analysis result.
  871. */
  872. function analyzeScope(ast, languageOptions, visitorKeys) {
  873. const parserOptions = languageOptions.parserOptions;
  874. const ecmaFeatures = parserOptions.ecmaFeatures || {};
  875. const ecmaVersion = languageOptions.ecmaVersion || DEFAULT_ECMA_VERSION;
  876. return eslintScope.analyze(ast, {
  877. ignoreEval: true,
  878. nodejsScope: ecmaFeatures.globalReturn,
  879. impliedStrict: ecmaFeatures.impliedStrict,
  880. ecmaVersion: typeof ecmaVersion === "number" ? ecmaVersion : 6,
  881. sourceType: languageOptions.sourceType || "script",
  882. childVisitorKeys: visitorKeys || evk.KEYS,
  883. fallback: Traverser.getKeys,
  884. });
  885. }
  886. /**
  887. * Runs a rule, and gets its listeners
  888. * @param {RuleDefinition} rule A rule object
  889. * @param {Context} ruleContext The context that should be passed to the rule
  890. * @throws {TypeError} If `rule` is not an object with a `create` method
  891. * @throws {any} Any error during the rule's `create`
  892. * @returns {Object} A map of selector listeners provided by the rule
  893. */
  894. function createRuleListeners(rule, ruleContext) {
  895. if (
  896. !rule ||
  897. typeof rule !== "object" ||
  898. typeof rule.create !== "function"
  899. ) {
  900. throw new TypeError(
  901. `Error while loading rule '${ruleContext.id}': Rule must be an object with a \`create\` method`,
  902. );
  903. }
  904. try {
  905. return rule.create(ruleContext);
  906. } catch (ex) {
  907. ex.message = `Error while loading rule '${ruleContext.id}': ${ex.message}`;
  908. throw ex;
  909. }
  910. }
  911. /**
  912. * Runs the given rules on the given SourceCode object
  913. * @param {SourceCode} sourceCode A SourceCode object for the given text
  914. * @param {Object} configuredRules The rules configuration
  915. * @param {function(string): RuleDefinition} ruleMapper A mapper function from rule names to rules
  916. * @param {string | undefined} parserName The name of the parser in the config
  917. * @param {Language} language The language object used for parsing.
  918. * @param {LanguageOptions} languageOptions The options for parsing the code.
  919. * @param {Object} settings The settings that were enabled in the config
  920. * @param {string} filename The reported filename of the code
  921. * @param {boolean} applyDefaultOptions If true, apply rules' meta.defaultOptions in computing their config options.
  922. * @param {string | undefined} cwd cwd of the cli
  923. * @param {string} physicalFilename The full path of the file on disk without any code block information
  924. * @param {Function} ruleFilter A predicate function to filter which rules should be executed.
  925. * @param {boolean} stats If true, stats are collected appended to the result
  926. * @param {WeakMap<Linter, LinterInternalSlots>} slots InternalSlotsMap of linter
  927. * @param {FileReport} report The report to add problems to
  928. * @returns {FileReport} report The report with added problems
  929. * @throws {Error} If traversal into a node fails.
  930. */
  931. function runRules(
  932. sourceCode,
  933. configuredRules,
  934. ruleMapper,
  935. parserName,
  936. language,
  937. languageOptions,
  938. settings,
  939. filename,
  940. applyDefaultOptions,
  941. cwd,
  942. physicalFilename,
  943. ruleFilter,
  944. stats,
  945. slots,
  946. report,
  947. ) {
  948. const visitor = new SourceCodeVisitor();
  949. /*
  950. * Create a frozen object with the ruleContext properties and methods that are shared by all rules.
  951. * All rule contexts will inherit from this object. This avoids the performance penalty of copying all the
  952. * properties once for each rule.
  953. */
  954. const fileContext = new FileContext({
  955. cwd,
  956. filename,
  957. physicalFilename: physicalFilename || filename,
  958. sourceCode,
  959. parserOptions: {
  960. ...languageOptions.parserOptions,
  961. },
  962. parserPath: parserName,
  963. languageOptions,
  964. settings,
  965. });
  966. const steps = sourceCode.traverse();
  967. Object.keys(configuredRules).forEach(ruleId => {
  968. const severity = Config.getRuleNumericSeverity(configuredRules[ruleId]);
  969. // not load disabled rules
  970. if (severity === 0) {
  971. return;
  972. }
  973. if (ruleFilter && !ruleFilter({ ruleId, severity })) {
  974. return;
  975. }
  976. const rule = ruleMapper(ruleId);
  977. if (!rule) {
  978. report.addError({ ruleId });
  979. return;
  980. }
  981. const ruleContext = fileContext.extend({
  982. id: ruleId,
  983. options: getRuleOptions(
  984. configuredRules[ruleId],
  985. applyDefaultOptions ? rule.meta?.defaultOptions : void 0,
  986. ),
  987. report(...args) {
  988. const problem = report.addRuleMessage(
  989. ruleId,
  990. severity,
  991. ...args,
  992. );
  993. if (problem.fix && !(rule.meta && rule.meta.fixable)) {
  994. throw new Error(
  995. 'Fixable rules must set the `meta.fixable` property to "code" or "whitespace".',
  996. );
  997. }
  998. if (
  999. problem.suggestions &&
  1000. !(rule.meta && rule.meta.hasSuggestions === true)
  1001. ) {
  1002. if (
  1003. rule.meta &&
  1004. rule.meta.docs &&
  1005. typeof rule.meta.docs.suggestion !== "undefined"
  1006. ) {
  1007. // Encourage migration from the former property name.
  1008. throw new Error(
  1009. "Rules with suggestions must set the `meta.hasSuggestions` property to `true`. `meta.docs.suggestion` is ignored by ESLint.",
  1010. );
  1011. }
  1012. throw new Error(
  1013. "Rules with suggestions must set the `meta.hasSuggestions` property to `true`.",
  1014. );
  1015. }
  1016. },
  1017. });
  1018. const ruleListenersReturn =
  1019. timing.enabled || stats
  1020. ? timing.time(
  1021. ruleId,
  1022. createRuleListeners,
  1023. stats,
  1024. )(rule, ruleContext)
  1025. : createRuleListeners(rule, ruleContext);
  1026. const ruleListeners = stats
  1027. ? ruleListenersReturn.result
  1028. : ruleListenersReturn;
  1029. if (stats) {
  1030. storeTime(
  1031. ruleListenersReturn.tdiff,
  1032. { type: "rules", key: ruleId },
  1033. slots,
  1034. );
  1035. }
  1036. /**
  1037. * Include `ruleId` in error logs
  1038. * @param {Function} ruleListener A rule method that listens for a node.
  1039. * @returns {Function} ruleListener wrapped in error handler
  1040. */
  1041. function addRuleErrorHandler(ruleListener) {
  1042. return function ruleErrorHandler(...listenerArgs) {
  1043. try {
  1044. const ruleListenerReturn = ruleListener(...listenerArgs);
  1045. const ruleListenerResult = stats
  1046. ? ruleListenerReturn.result
  1047. : ruleListenerReturn;
  1048. if (stats) {
  1049. storeTime(
  1050. ruleListenerReturn.tdiff,
  1051. { type: "rules", key: ruleId },
  1052. slots,
  1053. );
  1054. }
  1055. return ruleListenerResult;
  1056. } catch (e) {
  1057. e.ruleId = ruleId;
  1058. throw e;
  1059. }
  1060. };
  1061. }
  1062. if (typeof ruleListeners === "undefined" || ruleListeners === null) {
  1063. throw new Error(
  1064. `The create() function for rule '${ruleId}' did not return an object.`,
  1065. );
  1066. }
  1067. // add all the selectors from the rule as listeners
  1068. Object.keys(ruleListeners).forEach(selector => {
  1069. const ruleListener =
  1070. timing.enabled || stats
  1071. ? timing.time(ruleId, ruleListeners[selector], stats)
  1072. : ruleListeners[selector];
  1073. visitor.add(selector, addRuleErrorHandler(ruleListener));
  1074. });
  1075. });
  1076. const traverser = SourceCodeTraverser.getInstance(language);
  1077. traverser.traverseSync(sourceCode, visitor, { steps });
  1078. return report;
  1079. }
  1080. /**
  1081. * Ensure the source code to be a string.
  1082. * @param {string|SourceCode} textOrSourceCode The text or source code object.
  1083. * @returns {string} The source code text.
  1084. */
  1085. function ensureText(textOrSourceCode) {
  1086. if (typeof textOrSourceCode === "object") {
  1087. const { hasBOM, text } = textOrSourceCode;
  1088. const bom = hasBOM ? "\uFEFF" : "";
  1089. return bom + text;
  1090. }
  1091. return String(textOrSourceCode);
  1092. }
  1093. /**
  1094. * Get an environment.
  1095. * @param {LinterInternalSlots} slots The internal slots of Linter.
  1096. * @param {string} envId The environment ID to get.
  1097. * @returns {Environment|null} The environment.
  1098. */
  1099. function getEnv(slots, envId) {
  1100. return (
  1101. (slots.lastConfigArray &&
  1102. slots.lastConfigArray.pluginEnvironments.get(envId)) ||
  1103. BuiltInEnvironments.get(envId) ||
  1104. null
  1105. );
  1106. }
  1107. /**
  1108. * Get a rule.
  1109. * @param {LinterInternalSlots} slots The internal slots of Linter.
  1110. * @param {string} ruleId The rule ID to get.
  1111. * @returns {Rule|null} The rule.
  1112. */
  1113. function getRule(slots, ruleId) {
  1114. return (
  1115. (slots.lastConfigArray &&
  1116. slots.lastConfigArray.pluginRules.get(ruleId)) ||
  1117. slots.ruleMap.get(ruleId)
  1118. );
  1119. }
  1120. /**
  1121. * Normalize the value of the cwd
  1122. * @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.
  1123. * @returns {string | undefined} normalized cwd
  1124. */
  1125. function normalizeCwd(cwd) {
  1126. if (cwd) {
  1127. return cwd;
  1128. }
  1129. if (typeof process === "object") {
  1130. return process.cwd();
  1131. }
  1132. // It's more explicit to assign the undefined
  1133. // eslint-disable-next-line no-undefined -- Consistently returning a value
  1134. return undefined;
  1135. }
  1136. /**
  1137. * The map to store private data.
  1138. * @type {WeakMap<Linter, LinterInternalSlots>}
  1139. */
  1140. const internalSlotsMap = new WeakMap();
  1141. /**
  1142. * Throws an error when the given linter is in flat config mode.
  1143. * @param {Linter} linter The linter to check.
  1144. * @returns {void}
  1145. * @throws {Error} If the linter is in flat config mode.
  1146. */
  1147. function assertEslintrcConfig(linter) {
  1148. const { configType } = internalSlotsMap.get(linter);
  1149. if (configType === "flat") {
  1150. throw new Error(
  1151. "This method cannot be used with flat config. Add your entries directly into the config array.",
  1152. );
  1153. }
  1154. }
  1155. //------------------------------------------------------------------------------
  1156. // Public Interface
  1157. //------------------------------------------------------------------------------
  1158. /**
  1159. * Object that is responsible for verifying JavaScript text
  1160. * @name Linter
  1161. */
  1162. class Linter {
  1163. /**
  1164. * Initialize the Linter.
  1165. * @param {Object} [config] the config object
  1166. * @param {string} [config.cwd] path to a directory that should be considered as the current working directory, can be undefined.
  1167. * @param {Array<string>} [config.flags] the feature flags to enable.
  1168. * @param {"flat"|"eslintrc"} [config.configType="flat"] the type of config used.
  1169. * @param {WarningService} [config.warningService] The warning service to use.
  1170. */
  1171. constructor({
  1172. cwd,
  1173. configType = "flat",
  1174. flags = [],
  1175. warningService = new WarningService(),
  1176. } = {}) {
  1177. const processedFlags = [];
  1178. flags.forEach(flag => {
  1179. if (inactiveFlags.has(flag)) {
  1180. const inactiveFlagData = inactiveFlags.get(flag);
  1181. const inactivityReason =
  1182. getInactivityReasonMessage(inactiveFlagData);
  1183. const message = `The flag '${flag}' is inactive: ${inactivityReason}`;
  1184. if (typeof inactiveFlagData.replacedBy === "undefined") {
  1185. throw new Error(message);
  1186. }
  1187. // if there's a replacement, enable it instead of original
  1188. if (typeof inactiveFlagData.replacedBy === "string") {
  1189. processedFlags.push(inactiveFlagData.replacedBy);
  1190. }
  1191. warningService.emitInactiveFlagWarning(flag, message);
  1192. return;
  1193. }
  1194. if (!activeFlags.has(flag)) {
  1195. throw new Error(`Unknown flag '${flag}'.`);
  1196. }
  1197. processedFlags.push(flag);
  1198. });
  1199. internalSlotsMap.set(this, {
  1200. cwd: normalizeCwd(cwd),
  1201. flags: processedFlags,
  1202. lastConfigArray: null,
  1203. lastSourceCode: null,
  1204. lastSuppressedMessages: [],
  1205. configType, // TODO: Remove after flat config conversion
  1206. parserMap: new Map([["espree", espree]]),
  1207. ruleMap: new Rules(),
  1208. warningService,
  1209. });
  1210. this.version = pkg.version;
  1211. }
  1212. /**
  1213. * Getter for package version.
  1214. * @static
  1215. * @returns {string} The version from package.json.
  1216. */
  1217. static get version() {
  1218. return pkg.version;
  1219. }
  1220. /**
  1221. * Indicates if the given feature flag is enabled for this instance.
  1222. * @param {string} flag The feature flag to check.
  1223. * @returns {boolean} `true` if the feature flag is enabled, `false` if not.
  1224. */
  1225. hasFlag(flag) {
  1226. return internalSlotsMap.get(this).flags.includes(flag);
  1227. }
  1228. /**
  1229. * Lint using eslintrc and without processors.
  1230. * @param {VFile} file The file to lint.
  1231. * @param {ConfigData} providedConfig An ESLintConfig instance to configure everything.
  1232. * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked.
  1233. * @throws {Error} If during rule execution.
  1234. * @returns {(LintMessage|SuppressedLintMessage)[]} The results as an array of messages or an empty array if no messages.
  1235. */
  1236. #eslintrcVerifyWithoutProcessors(file, providedConfig, providedOptions) {
  1237. const slots = internalSlotsMap.get(this);
  1238. const config = providedConfig || {};
  1239. const options = normalizeVerifyOptions(providedOptions, config);
  1240. // Resolve parser.
  1241. let parserName = DEFAULT_PARSER_NAME;
  1242. let parser = espree;
  1243. if (typeof config.parser === "object" && config.parser !== null) {
  1244. parserName = config.parser.filePath;
  1245. parser = config.parser.definition;
  1246. } else if (typeof config.parser === "string") {
  1247. if (!slots.parserMap.has(config.parser)) {
  1248. return [
  1249. {
  1250. ruleId: null,
  1251. fatal: true,
  1252. severity: 2,
  1253. message: `Configured parser '${config.parser}' was not found.`,
  1254. line: 0,
  1255. column: 0,
  1256. nodeType: null,
  1257. },
  1258. ];
  1259. }
  1260. parserName = config.parser;
  1261. parser = slots.parserMap.get(config.parser);
  1262. }
  1263. // search and apply "eslint-env *".
  1264. const envInFile =
  1265. options.allowInlineConfig && !options.warnInlineConfig
  1266. ? findEslintEnv(file.body)
  1267. : {};
  1268. const resolvedEnvConfig = Object.assign(
  1269. { builtin: true },
  1270. config.env,
  1271. envInFile,
  1272. );
  1273. const enabledEnvs = Object.keys(resolvedEnvConfig)
  1274. .filter(envName => resolvedEnvConfig[envName])
  1275. .map(envName => getEnv(slots, envName))
  1276. .filter(env => env);
  1277. const parserOptions = resolveParserOptions(
  1278. parser,
  1279. config.parserOptions || {},
  1280. enabledEnvs,
  1281. );
  1282. const configuredGlobals = resolveGlobals(
  1283. config.globals || {},
  1284. enabledEnvs,
  1285. );
  1286. const settings = config.settings || {};
  1287. const languageOptions = createLanguageOptions({
  1288. globals: config.globals,
  1289. parser,
  1290. parserOptions,
  1291. });
  1292. if (!slots.lastSourceCode) {
  1293. let t;
  1294. if (options.stats) {
  1295. t = startTime();
  1296. }
  1297. const parserService = new ParserService();
  1298. const parseResult = parserService.parseSync(file, {
  1299. language: jslang,
  1300. languageOptions,
  1301. });
  1302. if (options.stats) {
  1303. const time = endTime(t);
  1304. const timeOpts = { type: "parse" };
  1305. storeTime(time, timeOpts, slots);
  1306. }
  1307. if (!parseResult.ok) {
  1308. return parseResult.errors;
  1309. }
  1310. slots.lastSourceCode = parseResult.sourceCode;
  1311. } else {
  1312. /*
  1313. * If the given source code object as the first argument does not have scopeManager, analyze the scope.
  1314. * This is for backward compatibility (SourceCode is frozen so it cannot rebind).
  1315. */
  1316. if (!slots.lastSourceCode.scopeManager) {
  1317. slots.lastSourceCode = new SourceCode({
  1318. text: slots.lastSourceCode.text,
  1319. ast: slots.lastSourceCode.ast,
  1320. hasBOM: slots.lastSourceCode.hasBOM,
  1321. parserServices: slots.lastSourceCode.parserServices,
  1322. visitorKeys: slots.lastSourceCode.visitorKeys,
  1323. scopeManager: analyzeScope(
  1324. slots.lastSourceCode.ast,
  1325. languageOptions,
  1326. ),
  1327. });
  1328. }
  1329. }
  1330. const sourceCode = slots.lastSourceCode;
  1331. const report = new FileReport({
  1332. ruleMapper: ruleId => getRule(slots, ruleId),
  1333. language: jslang,
  1334. sourceCode,
  1335. disableFixes: options.disableFixes,
  1336. });
  1337. const commentDirectives = options.allowInlineConfig
  1338. ? getDirectiveComments(
  1339. sourceCode,
  1340. ruleId => getRule(slots, ruleId),
  1341. options.warnInlineConfig,
  1342. config,
  1343. report,
  1344. )
  1345. : {
  1346. configuredRules: {},
  1347. enabledGlobals: {},
  1348. exportedVariables: {},
  1349. disableDirectives: [],
  1350. };
  1351. addDeclaredGlobals(
  1352. sourceCode.scopeManager.scopes[0],
  1353. configuredGlobals,
  1354. {
  1355. exportedVariables: commentDirectives.exportedVariables,
  1356. enabledGlobals: commentDirectives.enabledGlobals,
  1357. },
  1358. );
  1359. const configuredRules = Object.assign(
  1360. {},
  1361. config.rules,
  1362. commentDirectives.configuredRules,
  1363. );
  1364. try {
  1365. runRules(
  1366. sourceCode,
  1367. configuredRules,
  1368. ruleId => getRule(slots, ruleId),
  1369. parserName,
  1370. jslang,
  1371. languageOptions,
  1372. settings,
  1373. options.filename,
  1374. true,
  1375. slots.cwd,
  1376. providedOptions.physicalFilename,
  1377. null,
  1378. options.stats,
  1379. slots,
  1380. report,
  1381. );
  1382. } catch (err) {
  1383. err.message += `\nOccurred while linting ${options.filename}`;
  1384. debug("An error occurred while traversing");
  1385. debug("Filename:", options.filename);
  1386. if (err.currentNode) {
  1387. const { line } = sourceCode.getLoc(err.currentNode).start;
  1388. debug("Line:", line);
  1389. err.message += `:${line}`;
  1390. }
  1391. debug("Parser Options:", parserOptions);
  1392. debug("Parser Path:", parserName);
  1393. debug("Settings:", settings);
  1394. if (err.ruleId) {
  1395. err.message += `\nRule: "${err.ruleId}"`;
  1396. }
  1397. throw err;
  1398. }
  1399. return applyDisableDirectives({
  1400. language: jslang,
  1401. sourceCode,
  1402. directives: commentDirectives.disableDirectives,
  1403. disableFixes: options.disableFixes,
  1404. problems: report.messages.sort(
  1405. (problemA, problemB) =>
  1406. problemA.line - problemB.line ||
  1407. problemA.column - problemB.column,
  1408. ),
  1409. reportUnusedDisableDirectives:
  1410. options.reportUnusedDisableDirectives,
  1411. });
  1412. }
  1413. /**
  1414. * Same as linter.verify, except without support for processors.
  1415. * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
  1416. * @param {ConfigData} providedConfig An ESLintConfig instance to configure everything.
  1417. * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked.
  1418. * @throws {Error} If during rule execution.
  1419. * @returns {(LintMessage|SuppressedLintMessage)[]} The results as an array of messages or an empty array if no messages.
  1420. */
  1421. _verifyWithoutProcessors(
  1422. textOrSourceCode,
  1423. providedConfig,
  1424. providedOptions,
  1425. ) {
  1426. const slots = internalSlotsMap.get(this);
  1427. const filename = normalizeFilename(
  1428. providedOptions.filename || "<input>",
  1429. );
  1430. let text;
  1431. // evaluate arguments
  1432. if (typeof textOrSourceCode === "string") {
  1433. slots.lastSourceCode = null;
  1434. text = textOrSourceCode;
  1435. } else {
  1436. slots.lastSourceCode = textOrSourceCode;
  1437. text = textOrSourceCode.text;
  1438. }
  1439. const file = new VFile(filename, text, {
  1440. physicalPath: providedOptions.physicalFilename,
  1441. });
  1442. return this.#eslintrcVerifyWithoutProcessors(
  1443. file,
  1444. providedConfig,
  1445. providedOptions,
  1446. );
  1447. }
  1448. /**
  1449. * Verifies the text against the rules specified by the second argument.
  1450. * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
  1451. * @param {ConfigData|ConfigArray} config An ESLintConfig instance to configure everything.
  1452. * @param {(string|(VerifyOptions&ProcessorOptions))} [filenameOrOptions] The optional filename of the file being checked.
  1453. * If this is not set, the filename will default to '<input>' in the rule context. If
  1454. * an object, then it has "filename", "allowInlineConfig", and some properties.
  1455. * @returns {LintMessage[]} The results as an array of messages or an empty array if no messages.
  1456. */
  1457. verify(textOrSourceCode, config, filenameOrOptions) {
  1458. debug("Verify");
  1459. const { configType, cwd } = internalSlotsMap.get(this);
  1460. const options =
  1461. typeof filenameOrOptions === "string"
  1462. ? { filename: filenameOrOptions }
  1463. : filenameOrOptions || {};
  1464. const configToUse = config ?? {};
  1465. if (configType !== "eslintrc") {
  1466. /*
  1467. * Because of how Webpack packages up the files, we can't
  1468. * compare directly to `FlatConfigArray` using `instanceof`
  1469. * because it's not the same `FlatConfigArray` as in the tests.
  1470. * So, we work around it by assuming an array is, in fact, a
  1471. * `FlatConfigArray` if it has a `getConfig()` method.
  1472. */
  1473. let configArray = configToUse;
  1474. if (
  1475. !Array.isArray(configToUse) ||
  1476. typeof configToUse.getConfig !== "function"
  1477. ) {
  1478. configArray = new FlatConfigArray(configToUse, {
  1479. basePath: cwd,
  1480. });
  1481. configArray.normalizeSync();
  1482. }
  1483. return this._distinguishSuppressedMessages(
  1484. this._verifyWithFlatConfigArray(
  1485. textOrSourceCode,
  1486. configArray,
  1487. options,
  1488. true,
  1489. ),
  1490. );
  1491. }
  1492. if (typeof configToUse.extractConfig === "function") {
  1493. return this._distinguishSuppressedMessages(
  1494. this._verifyWithConfigArray(
  1495. textOrSourceCode,
  1496. configToUse,
  1497. options,
  1498. ),
  1499. );
  1500. }
  1501. /*
  1502. * If we get to here, it means `config` is just an object rather
  1503. * than a config array so we can go right into linting.
  1504. */
  1505. /*
  1506. * `Linter` doesn't support `overrides` property in configuration.
  1507. * So we cannot apply multiple processors.
  1508. */
  1509. if (options.preprocess || options.postprocess) {
  1510. return this._distinguishSuppressedMessages(
  1511. this._verifyWithProcessor(
  1512. textOrSourceCode,
  1513. configToUse,
  1514. options,
  1515. ),
  1516. );
  1517. }
  1518. return this._distinguishSuppressedMessages(
  1519. this._verifyWithoutProcessors(
  1520. textOrSourceCode,
  1521. configToUse,
  1522. options,
  1523. ),
  1524. );
  1525. }
  1526. /**
  1527. * Verify with a processor.
  1528. * @param {string|SourceCode} textOrSourceCode The source code.
  1529. * @param {Config} config The config array.
  1530. * @param {VerifyOptions&ProcessorOptions} options The options.
  1531. * @param {FlatConfigArray} [configForRecursive] The `ConfigArray` object to apply multiple processors recursively.
  1532. * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems.
  1533. */
  1534. _verifyWithFlatConfigArrayAndProcessor(
  1535. textOrSourceCode,
  1536. config,
  1537. options,
  1538. configForRecursive,
  1539. ) {
  1540. const slots = internalSlotsMap.get(this);
  1541. const filename = options.filename || "<input>";
  1542. const filenameToExpose = normalizeFilename(filename);
  1543. const physicalFilename = options.physicalFilename || filenameToExpose;
  1544. const text = ensureText(textOrSourceCode);
  1545. const file = new VFile(filenameToExpose, text, {
  1546. physicalPath: physicalFilename,
  1547. });
  1548. const preprocess = options.preprocess || (rawText => [rawText]);
  1549. const postprocess =
  1550. options.postprocess || (messagesList => messagesList.flat());
  1551. const processorService = new ProcessorService();
  1552. const preprocessResult = processorService.preprocessSync(file, {
  1553. processor: {
  1554. preprocess,
  1555. postprocess,
  1556. },
  1557. });
  1558. if (!preprocessResult.ok) {
  1559. return preprocessResult.errors;
  1560. }
  1561. const filterCodeBlock =
  1562. options.filterCodeBlock ||
  1563. (blockFilename => blockFilename.endsWith(".js"));
  1564. const originalExtname = path.extname(filename);
  1565. const { files } = preprocessResult;
  1566. const messageLists = files.map(block => {
  1567. debug("A code block was found: %o", block.path || "(unnamed)");
  1568. // Keep the legacy behavior.
  1569. if (typeof block === "string") {
  1570. return this._verifyWithFlatConfigArrayAndWithoutProcessors(
  1571. block,
  1572. config,
  1573. options,
  1574. );
  1575. }
  1576. // Skip this block if filtered.
  1577. if (!filterCodeBlock(block.path, block.body)) {
  1578. debug("This code block was skipped.");
  1579. return [];
  1580. }
  1581. // Resolve configuration again if the file content or extension was changed.
  1582. if (
  1583. configForRecursive &&
  1584. (text !== block.rawBody ||
  1585. path.extname(block.path) !== originalExtname)
  1586. ) {
  1587. debug(
  1588. "Resolving configuration again because the file content or extension was changed.",
  1589. );
  1590. return this._verifyWithFlatConfigArray(
  1591. block.rawBody,
  1592. configForRecursive,
  1593. {
  1594. ...options,
  1595. filename: block.path,
  1596. physicalFilename: block.physicalPath,
  1597. },
  1598. );
  1599. }
  1600. slots.lastSourceCode = null;
  1601. // Does lint.
  1602. return this.#flatVerifyWithoutProcessors(block, config, {
  1603. ...options,
  1604. filename: block.path,
  1605. physicalFilename: block.physicalPath,
  1606. });
  1607. });
  1608. return processorService.postprocessSync(file, messageLists, {
  1609. processor: {
  1610. preprocess,
  1611. postprocess,
  1612. },
  1613. });
  1614. }
  1615. /**
  1616. * Verify using flat config and without any processors.
  1617. * @param {VFile} file The file to lint.
  1618. * @param {Config} providedConfig An ESLintConfig instance to configure everything.
  1619. * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked.
  1620. * @throws {Error} If during rule execution.
  1621. * @returns {(LintMessage|SuppressedLintMessage)[]} The results as an array of messages or an empty array if no messages.
  1622. */
  1623. #flatVerifyWithoutProcessors(file, providedConfig, providedOptions) {
  1624. const slots = internalSlotsMap.get(this);
  1625. const config = providedConfig || {};
  1626. const { settings = {}, languageOptions } = config;
  1627. const options = normalizeVerifyOptions(providedOptions, config);
  1628. if (!slots.lastSourceCode) {
  1629. let t;
  1630. if (options.stats) {
  1631. t = startTime();
  1632. }
  1633. const parserService = new ParserService();
  1634. const parseResult = parserService.parseSync(file, config);
  1635. if (options.stats) {
  1636. const time = endTime(t);
  1637. storeTime(time, { type: "parse" }, slots);
  1638. }
  1639. if (!parseResult.ok) {
  1640. return parseResult.errors;
  1641. }
  1642. slots.lastSourceCode = parseResult.sourceCode;
  1643. } else {
  1644. /*
  1645. * If the given source code object as the first argument does not have scopeManager, analyze the scope.
  1646. * This is for backward compatibility (SourceCode is frozen so it cannot rebind).
  1647. *
  1648. * We check explicitly for `null` to ensure that this is a JS-flavored language.
  1649. * For non-JS languages we don't want to do this.
  1650. *
  1651. * TODO: Remove this check when we stop exporting the `SourceCode` object.
  1652. */
  1653. if (slots.lastSourceCode.scopeManager === null) {
  1654. slots.lastSourceCode = new SourceCode({
  1655. text: slots.lastSourceCode.text,
  1656. ast: slots.lastSourceCode.ast,
  1657. hasBOM: slots.lastSourceCode.hasBOM,
  1658. parserServices: slots.lastSourceCode.parserServices,
  1659. visitorKeys: slots.lastSourceCode.visitorKeys,
  1660. scopeManager: analyzeScope(
  1661. slots.lastSourceCode.ast,
  1662. languageOptions,
  1663. ),
  1664. });
  1665. }
  1666. }
  1667. const sourceCode = slots.lastSourceCode;
  1668. const report = new FileReport({
  1669. ruleMapper: ruleId => config.getRuleDefinition(ruleId),
  1670. language: config.language,
  1671. sourceCode,
  1672. disableFixes: options.disableFixes,
  1673. });
  1674. /*
  1675. * Make adjustments based on the language options. For JavaScript,
  1676. * this is primarily about adding variables into the global scope
  1677. * to account for ecmaVersion and configured globals.
  1678. */
  1679. sourceCode.applyLanguageOptions?.(languageOptions);
  1680. const mergedInlineConfig = {
  1681. rules: {},
  1682. };
  1683. /*
  1684. * Inline config can be either enabled or disabled. If disabled, it's possible
  1685. * to detect the inline config and emit a warning (though this is not required).
  1686. * So we first check to see if inline config is allowed at all, and if so, we
  1687. * need to check if it's a warning or not.
  1688. */
  1689. if (options.allowInlineConfig) {
  1690. // if inline config should warn then add the warnings
  1691. if (options.warnInlineConfig) {
  1692. if (sourceCode.getInlineConfigNodes) {
  1693. sourceCode.getInlineConfigNodes().forEach(node => {
  1694. const loc = sourceCode.getLoc(node);
  1695. const range = sourceCode.getRange(node);
  1696. report.addWarning({
  1697. message: `'${sourceCode.text.slice(range[0], range[1])}' has no effect because you have 'noInlineConfig' setting in ${options.warnInlineConfig}.`,
  1698. loc,
  1699. });
  1700. });
  1701. }
  1702. } else {
  1703. if (config.language === jslang) {
  1704. for (const comment of sourceCode.getInlineConfigNodes()) {
  1705. const { label } = commentParser.parseDirective(
  1706. comment.value,
  1707. );
  1708. if (label === "eslint-env") {
  1709. slots.warningService.emitESLintEnvWarning(
  1710. options.filename,
  1711. comment.loc.start.line,
  1712. );
  1713. }
  1714. }
  1715. }
  1716. const inlineConfigResult = sourceCode.applyInlineConfig?.();
  1717. if (inlineConfigResult) {
  1718. inlineConfigResult.problems.forEach(problem => {
  1719. report.addFatal(problem);
  1720. });
  1721. for (const {
  1722. config: inlineConfig,
  1723. loc,
  1724. } of inlineConfigResult.configs) {
  1725. Object.keys(inlineConfig.rules).forEach(ruleId => {
  1726. const rule = config.getRuleDefinition(ruleId);
  1727. const ruleValue = inlineConfig.rules[ruleId];
  1728. if (!rule) {
  1729. report.addError({
  1730. ruleId,
  1731. loc,
  1732. });
  1733. return;
  1734. }
  1735. if (
  1736. Object.hasOwn(mergedInlineConfig.rules, ruleId)
  1737. ) {
  1738. report.addError({
  1739. message: `Rule "${ruleId}" is already configured by another configuration comment in the preceding code. This configuration is ignored.`,
  1740. loc,
  1741. });
  1742. return;
  1743. }
  1744. try {
  1745. const ruleOptionsInline = asArray(ruleValue);
  1746. let ruleOptions = ruleOptionsInline;
  1747. assertIsRuleSeverity(ruleId, ruleOptions[0]);
  1748. /*
  1749. * If the rule was already configured, inline rule configuration that
  1750. * only has severity should retain options from the config and just override the severity.
  1751. *
  1752. * Example:
  1753. *
  1754. * {
  1755. * rules: {
  1756. * curly: ["error", "multi"]
  1757. * }
  1758. * }
  1759. *
  1760. * /* eslint curly: ["warn"] * /
  1761. *
  1762. * Results in:
  1763. *
  1764. * curly: ["warn", "multi"]
  1765. */
  1766. let shouldValidateOptions = true;
  1767. if (
  1768. /*
  1769. * If inline config for the rule has only severity
  1770. */
  1771. ruleOptions.length === 1 &&
  1772. /*
  1773. * And the rule was already configured
  1774. */
  1775. config.rules &&
  1776. Object.hasOwn(config.rules, ruleId)
  1777. ) {
  1778. /*
  1779. * Then use severity from the inline config and options from the provided config
  1780. */
  1781. ruleOptions = [
  1782. ruleOptions[0], // severity from the inline config
  1783. ...config.rules[ruleId].slice(1), // options from the provided config
  1784. ];
  1785. // if the rule was enabled, the options have already been validated
  1786. if (config.rules[ruleId][0] > 0) {
  1787. shouldValidateOptions = false;
  1788. }
  1789. } else {
  1790. /**
  1791. * Since we know the user provided options, apply defaults on top of them
  1792. */
  1793. const slicedOptions = ruleOptions.slice(1);
  1794. const mergedOptions = deepMergeArrays(
  1795. rule.meta?.defaultOptions,
  1796. slicedOptions,
  1797. );
  1798. if (mergedOptions.length) {
  1799. ruleOptions = [
  1800. ruleOptions[0],
  1801. ...mergedOptions,
  1802. ];
  1803. }
  1804. }
  1805. if (
  1806. options.reportUnusedInlineConfigs !== "off"
  1807. ) {
  1808. addProblemIfSameSeverityAndOptions(
  1809. config,
  1810. loc,
  1811. report,
  1812. ruleId,
  1813. ruleOptions,
  1814. ruleOptionsInline,
  1815. options.reportUnusedInlineConfigs,
  1816. );
  1817. }
  1818. if (shouldValidateOptions) {
  1819. config.validateRulesConfig({
  1820. [ruleId]: ruleOptions,
  1821. });
  1822. }
  1823. mergedInlineConfig.rules[ruleId] = ruleOptions;
  1824. } catch (err) {
  1825. /*
  1826. * If the rule has invalid `meta.schema`, throw the error because
  1827. * this is not an invalid inline configuration but an invalid rule.
  1828. */
  1829. if (
  1830. err.code ===
  1831. "ESLINT_INVALID_RULE_OPTIONS_SCHEMA"
  1832. ) {
  1833. throw err;
  1834. }
  1835. let baseMessage = err.message
  1836. .slice(
  1837. err.message.startsWith('Key "rules":')
  1838. ? err.message.indexOf(":", 12) + 1
  1839. : err.message.indexOf(":") + 1,
  1840. )
  1841. .trim();
  1842. if (err.messageTemplate) {
  1843. baseMessage += ` You passed "${ruleValue}".`;
  1844. }
  1845. report.addError({
  1846. ruleId,
  1847. message: `Inline configuration for rule "${ruleId}" is invalid:\n\t${baseMessage}\n`,
  1848. loc,
  1849. });
  1850. }
  1851. });
  1852. }
  1853. }
  1854. }
  1855. }
  1856. const commentDirectives =
  1857. options.allowInlineConfig && !options.warnInlineConfig
  1858. ? getDirectiveCommentsForFlatConfig(
  1859. sourceCode,
  1860. ruleId => config.getRuleDefinition(ruleId),
  1861. config.language,
  1862. report,
  1863. )
  1864. : [];
  1865. const configuredRules = Object.assign(
  1866. {},
  1867. config.rules,
  1868. mergedInlineConfig.rules,
  1869. );
  1870. sourceCode.finalize?.();
  1871. try {
  1872. runRules(
  1873. sourceCode,
  1874. configuredRules,
  1875. ruleId => config.getRuleDefinition(ruleId),
  1876. void 0,
  1877. config.language,
  1878. languageOptions,
  1879. settings,
  1880. options.filename,
  1881. false,
  1882. slots.cwd,
  1883. providedOptions.physicalFilename,
  1884. options.ruleFilter,
  1885. options.stats,
  1886. slots,
  1887. report,
  1888. );
  1889. } catch (err) {
  1890. err.message += `\nOccurred while linting ${options.filename}`;
  1891. debug("An error occurred while traversing");
  1892. debug("Filename:", options.filename);
  1893. if (err.currentNode) {
  1894. const { line } = sourceCode.getLoc(err.currentNode).start;
  1895. debug("Line:", line);
  1896. err.message += `:${line}`;
  1897. }
  1898. debug("Parser Options:", languageOptions.parserOptions);
  1899. // debug("Parser Path:", parserName);
  1900. debug("Settings:", settings);
  1901. if (err.ruleId) {
  1902. err.message += `\nRule: "${err.ruleId}"`;
  1903. }
  1904. throw err;
  1905. }
  1906. return applyDisableDirectives({
  1907. language: config.language,
  1908. sourceCode,
  1909. directives: commentDirectives,
  1910. disableFixes: options.disableFixes,
  1911. problems: report.messages.sort(
  1912. (problemA, problemB) =>
  1913. problemA.line - problemB.line ||
  1914. problemA.column - problemB.column,
  1915. ),
  1916. reportUnusedDisableDirectives:
  1917. options.reportUnusedDisableDirectives,
  1918. ruleFilter: options.ruleFilter,
  1919. configuredRules,
  1920. });
  1921. }
  1922. /**
  1923. * Same as linter.verify, except without support for processors.
  1924. * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
  1925. * @param {Config} providedConfig An ESLintConfig instance to configure everything.
  1926. * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked.
  1927. * @throws {Error} If during rule execution.
  1928. * @returns {(LintMessage|SuppressedLintMessage)[]} The results as an array of messages or an empty array if no messages.
  1929. */
  1930. _verifyWithFlatConfigArrayAndWithoutProcessors(
  1931. textOrSourceCode,
  1932. providedConfig,
  1933. providedOptions,
  1934. ) {
  1935. const slots = internalSlotsMap.get(this);
  1936. const filename = normalizeFilename(
  1937. providedOptions.filename || "<input>",
  1938. );
  1939. let text;
  1940. // evaluate arguments
  1941. if (typeof textOrSourceCode === "string") {
  1942. slots.lastSourceCode = null;
  1943. text = textOrSourceCode;
  1944. } else {
  1945. slots.lastSourceCode = textOrSourceCode;
  1946. text = textOrSourceCode.text;
  1947. }
  1948. const file = new VFile(filename, text, {
  1949. physicalPath: providedOptions.physicalFilename,
  1950. });
  1951. return this.#flatVerifyWithoutProcessors(
  1952. file,
  1953. providedConfig,
  1954. providedOptions,
  1955. );
  1956. }
  1957. /**
  1958. * Verify a given code with `ConfigArray`.
  1959. * @param {string|SourceCode} textOrSourceCode The source code.
  1960. * @param {ConfigArray} configArray The config array.
  1961. * @param {VerifyOptions&ProcessorOptions} options The options.
  1962. * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems.
  1963. */
  1964. _verifyWithConfigArray(textOrSourceCode, configArray, options) {
  1965. debug("With ConfigArray: %s", options.filename);
  1966. // Store the config array in order to get plugin envs and rules later.
  1967. internalSlotsMap.get(this).lastConfigArray = configArray;
  1968. // Extract the final config for this file.
  1969. const config = configArray.extractConfig(options.filename);
  1970. const processor =
  1971. config.processor &&
  1972. configArray.pluginProcessors.get(config.processor);
  1973. // Verify.
  1974. if (processor) {
  1975. debug("Apply the processor: %o", config.processor);
  1976. const { preprocess, postprocess, supportsAutofix } = processor;
  1977. const disableFixes = options.disableFixes || !supportsAutofix;
  1978. return this._verifyWithProcessor(
  1979. textOrSourceCode,
  1980. config,
  1981. { ...options, disableFixes, postprocess, preprocess },
  1982. configArray,
  1983. );
  1984. }
  1985. return this._verifyWithoutProcessors(textOrSourceCode, config, options);
  1986. }
  1987. /**
  1988. * Verify a given code with a flat config.
  1989. * @param {string|SourceCode} textOrSourceCode The source code.
  1990. * @param {FlatConfigArray} configArray The config array.
  1991. * @param {VerifyOptions&ProcessorOptions} options The options.
  1992. * @param {boolean} [firstCall=false] Indicates if this is being called directly
  1993. * from verify(). (TODO: Remove once eslintrc is removed.)
  1994. * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems.
  1995. */
  1996. _verifyWithFlatConfigArray(
  1997. textOrSourceCode,
  1998. configArray,
  1999. options,
  2000. firstCall = false,
  2001. ) {
  2002. debug("With flat config: %s", options.filename);
  2003. // we need a filename to match configs against
  2004. const filename = options.filename || "__placeholder__.js";
  2005. // Store the config array in order to get plugin envs and rules later.
  2006. internalSlotsMap.get(this).lastConfigArray = configArray;
  2007. const config = configArray.getConfig(filename);
  2008. if (!config) {
  2009. return [
  2010. {
  2011. ruleId: null,
  2012. severity: 1,
  2013. message: `No matching configuration found for ${filename}.`,
  2014. line: 0,
  2015. column: 0,
  2016. nodeType: null,
  2017. },
  2018. ];
  2019. }
  2020. // Verify.
  2021. if (config.processor) {
  2022. debug("Apply the processor: %o", config.processor);
  2023. const { preprocess, postprocess, supportsAutofix } =
  2024. config.processor;
  2025. const disableFixes = options.disableFixes || !supportsAutofix;
  2026. return this._verifyWithFlatConfigArrayAndProcessor(
  2027. textOrSourceCode,
  2028. config,
  2029. { ...options, filename, disableFixes, postprocess, preprocess },
  2030. configArray,
  2031. );
  2032. }
  2033. // check for options-based processing
  2034. if (firstCall && (options.preprocess || options.postprocess)) {
  2035. return this._verifyWithFlatConfigArrayAndProcessor(
  2036. textOrSourceCode,
  2037. config,
  2038. options,
  2039. );
  2040. }
  2041. return this._verifyWithFlatConfigArrayAndWithoutProcessors(
  2042. textOrSourceCode,
  2043. config,
  2044. options,
  2045. );
  2046. }
  2047. /**
  2048. * Verify with a processor.
  2049. * @param {string|SourceCode} textOrSourceCode The source code.
  2050. * @param {ConfigData|ExtractedConfig} config The config array.
  2051. * @param {VerifyOptions&ProcessorOptions} options The options.
  2052. * @param {ConfigArray} [configForRecursive] The `ConfigArray` object to apply multiple processors recursively.
  2053. * @returns {(LintMessage|SuppressedLintMessage)[]} The found problems.
  2054. */
  2055. _verifyWithProcessor(
  2056. textOrSourceCode,
  2057. config,
  2058. options,
  2059. configForRecursive,
  2060. ) {
  2061. const slots = internalSlotsMap.get(this);
  2062. const filename = options.filename || "<input>";
  2063. const filenameToExpose = normalizeFilename(filename);
  2064. const physicalFilename = options.physicalFilename || filenameToExpose;
  2065. const text = ensureText(textOrSourceCode);
  2066. const file = new VFile(filenameToExpose, text, {
  2067. physicalPath: physicalFilename,
  2068. });
  2069. const preprocess = options.preprocess || (rawText => [rawText]);
  2070. const postprocess =
  2071. options.postprocess || (messagesList => messagesList.flat());
  2072. const processorService = new ProcessorService();
  2073. const preprocessResult = processorService.preprocessSync(file, {
  2074. processor: {
  2075. preprocess,
  2076. postprocess,
  2077. },
  2078. });
  2079. if (!preprocessResult.ok) {
  2080. return preprocessResult.errors;
  2081. }
  2082. const filterCodeBlock =
  2083. options.filterCodeBlock ||
  2084. (blockFilePath => blockFilePath.endsWith(".js"));
  2085. const originalExtname = path.extname(filename);
  2086. const { files } = preprocessResult;
  2087. const messageLists = files.map(block => {
  2088. debug("A code block was found: %o", block.path ?? "(unnamed)");
  2089. // Keep the legacy behavior.
  2090. if (typeof block === "string") {
  2091. return this._verifyWithoutProcessors(block, config, options);
  2092. }
  2093. // Skip this block if filtered.
  2094. if (!filterCodeBlock(block.path, block.body)) {
  2095. debug("This code block was skipped.");
  2096. return [];
  2097. }
  2098. // Resolve configuration again if the file content or extension was changed.
  2099. if (
  2100. configForRecursive &&
  2101. (text !== block.rawBody ||
  2102. path.extname(block.path) !== originalExtname)
  2103. ) {
  2104. debug(
  2105. "Resolving configuration again because the file content or extension was changed.",
  2106. );
  2107. return this._verifyWithConfigArray(
  2108. block.rawBody,
  2109. configForRecursive,
  2110. {
  2111. ...options,
  2112. filename: block.path,
  2113. physicalFilename: block.physicalPath,
  2114. },
  2115. );
  2116. }
  2117. slots.lastSourceCode = null;
  2118. // Does lint.
  2119. return this.#eslintrcVerifyWithoutProcessors(block, config, {
  2120. ...options,
  2121. filename: block.path,
  2122. physicalFilename: block.physicalPath,
  2123. });
  2124. });
  2125. return processorService.postprocessSync(file, messageLists, {
  2126. processor: {
  2127. preprocess,
  2128. postprocess,
  2129. },
  2130. });
  2131. }
  2132. /**
  2133. * Given a list of reported problems, distinguish problems between normal messages and suppressed messages.
  2134. * The normal messages will be returned and the suppressed messages will be stored as lastSuppressedMessages.
  2135. * @param {Array<LintMessage|SuppressedLintMessage>} problems A list of reported problems.
  2136. * @returns {LintMessage[]} A list of LintMessage.
  2137. */
  2138. _distinguishSuppressedMessages(problems) {
  2139. const messages = [];
  2140. const suppressedMessages = [];
  2141. const slots = internalSlotsMap.get(this);
  2142. for (const problem of problems) {
  2143. if (problem.suppressions) {
  2144. suppressedMessages.push(problem);
  2145. } else {
  2146. messages.push(problem);
  2147. }
  2148. }
  2149. slots.lastSuppressedMessages = suppressedMessages;
  2150. return messages;
  2151. }
  2152. /**
  2153. * Gets the SourceCode object representing the parsed source.
  2154. * @returns {SourceCode} The SourceCode object.
  2155. */
  2156. getSourceCode() {
  2157. return internalSlotsMap.get(this).lastSourceCode;
  2158. }
  2159. /**
  2160. * Gets the times spent on (parsing, fixing, linting) a file.
  2161. * @returns {{ passes: TimePass[]; }} The times.
  2162. */
  2163. getTimes() {
  2164. return internalSlotsMap.get(this).times ?? { passes: [] };
  2165. }
  2166. /**
  2167. * Gets the number of autofix passes that were made in the last run.
  2168. * @returns {number} The number of autofix passes.
  2169. */
  2170. getFixPassCount() {
  2171. return internalSlotsMap.get(this).fixPasses ?? 0;
  2172. }
  2173. /**
  2174. * Gets the list of SuppressedLintMessage produced in the last running.
  2175. * @returns {SuppressedLintMessage[]} The list of SuppressedLintMessage
  2176. */
  2177. getSuppressedMessages() {
  2178. return internalSlotsMap.get(this).lastSuppressedMessages;
  2179. }
  2180. /**
  2181. * Defines a new linting rule.
  2182. * @param {string} ruleId A unique rule identifier
  2183. * @param {Rule} rule A rule object
  2184. * @returns {void}
  2185. */
  2186. defineRule(ruleId, rule) {
  2187. assertEslintrcConfig(this);
  2188. internalSlotsMap.get(this).ruleMap.define(ruleId, rule);
  2189. }
  2190. /**
  2191. * Defines many new linting rules.
  2192. * @param {Record<string, Rule>} rulesToDefine map from unique rule identifier to rule
  2193. * @returns {void}
  2194. */
  2195. defineRules(rulesToDefine) {
  2196. assertEslintrcConfig(this);
  2197. Object.getOwnPropertyNames(rulesToDefine).forEach(ruleId => {
  2198. this.defineRule(ruleId, rulesToDefine[ruleId]);
  2199. });
  2200. }
  2201. /**
  2202. * Gets an object with all loaded rules.
  2203. * @returns {Map<string, Rule>} All loaded rules
  2204. */
  2205. getRules() {
  2206. assertEslintrcConfig(this);
  2207. const { lastConfigArray, ruleMap } = internalSlotsMap.get(this);
  2208. return new Map(
  2209. (function* () {
  2210. yield* ruleMap;
  2211. if (lastConfigArray) {
  2212. yield* lastConfigArray.pluginRules;
  2213. }
  2214. })(),
  2215. );
  2216. }
  2217. /**
  2218. * Define a new parser module
  2219. * @param {string} parserId Name of the parser
  2220. * @param {Parser} parserModule The parser object
  2221. * @returns {void}
  2222. */
  2223. defineParser(parserId, parserModule) {
  2224. assertEslintrcConfig(this);
  2225. internalSlotsMap.get(this).parserMap.set(parserId, parserModule);
  2226. }
  2227. /**
  2228. * Performs multiple autofix passes over the text until as many fixes as possible
  2229. * have been applied.
  2230. * @param {string} text The source text to apply fixes to.
  2231. * @param {ConfigData|ConfigArray|FlatConfigArray} config The ESLint config object to use.
  2232. * @param {VerifyOptions&ProcessorOptions&FixOptions} options The ESLint options object to use.
  2233. * @returns {{fixed:boolean,messages:LintMessage[],output:string}} The result of the fix operation as returned from the
  2234. * SourceCodeFixer.
  2235. */
  2236. verifyAndFix(text, config, options) {
  2237. let messages,
  2238. fixedResult,
  2239. fixed = false,
  2240. passNumber = 0,
  2241. currentText = text,
  2242. secondPreviousText,
  2243. previousText;
  2244. const debugTextDescription =
  2245. (options && options.filename) || `${text.slice(0, 10)}...`;
  2246. const shouldFix =
  2247. options && typeof options.fix !== "undefined" ? options.fix : true;
  2248. const stats = options?.stats;
  2249. const slots = internalSlotsMap.get(this);
  2250. // Remove lint times from the last run.
  2251. if (stats) {
  2252. delete slots.times;
  2253. slots.fixPasses = 0;
  2254. }
  2255. /**
  2256. * This loop continues until one of the following is true:
  2257. *
  2258. * 1. No more fixes have been applied.
  2259. * 2. Ten passes have been made.
  2260. *
  2261. * That means anytime a fix is successfully applied, there will be another pass.
  2262. * Essentially, guaranteeing a minimum of two passes.
  2263. */
  2264. do {
  2265. passNumber++;
  2266. let tTotal;
  2267. if (stats) {
  2268. tTotal = startTime();
  2269. }
  2270. debug(
  2271. `Linting code for ${debugTextDescription} (pass ${passNumber})`,
  2272. );
  2273. messages = this.verify(currentText, config, options);
  2274. debug(
  2275. `Generating fixed text for ${debugTextDescription} (pass ${passNumber})`,
  2276. );
  2277. let t;
  2278. if (stats) {
  2279. t = startTime();
  2280. }
  2281. fixedResult = SourceCodeFixer.applyFixes(
  2282. currentText,
  2283. messages,
  2284. shouldFix,
  2285. );
  2286. if (stats) {
  2287. if (fixedResult.fixed) {
  2288. const time = endTime(t);
  2289. storeTime(time, { type: "fix" }, slots);
  2290. slots.fixPasses++;
  2291. } else {
  2292. storeTime(0, { type: "fix" }, slots);
  2293. }
  2294. }
  2295. /*
  2296. * stop if there are any syntax errors.
  2297. * 'fixedResult.output' is a empty string.
  2298. */
  2299. if (messages.length === 1 && messages[0].fatal) {
  2300. break;
  2301. }
  2302. // keep track if any fixes were ever applied - important for return value
  2303. fixed = fixed || fixedResult.fixed;
  2304. // update to use the fixed output instead of the original text
  2305. secondPreviousText = previousText;
  2306. previousText = currentText;
  2307. currentText = fixedResult.output;
  2308. if (stats) {
  2309. tTotal = endTime(tTotal);
  2310. const passIndex = slots.times.passes.length - 1;
  2311. slots.times.passes[passIndex].total = tTotal;
  2312. }
  2313. // Stop if we've made a circular fix
  2314. if (
  2315. passNumber > 1 &&
  2316. currentText.length === secondPreviousText.length &&
  2317. currentText === secondPreviousText
  2318. ) {
  2319. debug(
  2320. `Circular fixes detected after pass ${passNumber}. Exiting fix loop.`,
  2321. );
  2322. slots.warningService.emitCircularFixesWarning(
  2323. options?.filename ?? "text",
  2324. );
  2325. break;
  2326. }
  2327. } while (fixedResult.fixed && passNumber < MAX_AUTOFIX_PASSES);
  2328. /*
  2329. * If the last result had fixes, we need to lint again to be sure we have
  2330. * the most up-to-date information.
  2331. */
  2332. if (fixedResult.fixed) {
  2333. let tTotal;
  2334. if (stats) {
  2335. tTotal = startTime();
  2336. }
  2337. fixedResult.messages = this.verify(currentText, config, options);
  2338. if (stats) {
  2339. storeTime(0, { type: "fix" }, slots);
  2340. slots.times.passes.at(-1).total = endTime(tTotal);
  2341. }
  2342. }
  2343. // ensure the last result properly reflects if fixes were done
  2344. fixedResult.fixed = fixed;
  2345. fixedResult.output = currentText;
  2346. return fixedResult;
  2347. }
  2348. }
  2349. module.exports = {
  2350. Linter,
  2351. /**
  2352. * Get the internal slots of a given Linter instance for tests.
  2353. * @param {Linter} instance The Linter instance to get.
  2354. * @returns {LinterInternalSlots} The internal slots.
  2355. */
  2356. getLinterInternalSlots(instance) {
  2357. return internalSlotsMap.get(instance);
  2358. },
  2359. };