linter.js 54 KB

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