apply-disable-directives.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. /**
  2. * @fileoverview A module that filters reported problems based on `eslint-disable` and `eslint-enable` comments
  3. * @author Teddy Katz
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Typedefs
  8. //------------------------------------------------------------------------------
  9. /** @typedef {import("../shared/types").LintMessage} LintMessage */
  10. //------------------------------------------------------------------------------
  11. // Module Definition
  12. //------------------------------------------------------------------------------
  13. const escapeRegExp = require("escape-string-regexp");
  14. /**
  15. * Compares the locations of two objects in a source file
  16. * @param {{line: number, column: number}} itemA The first object
  17. * @param {{line: number, column: number}} itemB The second object
  18. * @returns {number} A value less than 1 if itemA appears before itemB in the source file, greater than 1 if
  19. * itemA appears after itemB in the source file, or 0 if itemA and itemB have the same location.
  20. */
  21. function compareLocations(itemA, itemB) {
  22. return itemA.line - itemB.line || itemA.column - itemB.column;
  23. }
  24. /**
  25. * Groups a set of directives into sub-arrays by their parent comment.
  26. * @param {Directive[]} directives Unused directives to be removed.
  27. * @returns {Directive[][]} Directives grouped by their parent comment.
  28. */
  29. function groupByParentComment(directives) {
  30. const groups = new Map();
  31. for (const directive of directives) {
  32. const { unprocessedDirective: { parentComment } } = directive;
  33. if (groups.has(parentComment)) {
  34. groups.get(parentComment).push(directive);
  35. } else {
  36. groups.set(parentComment, [directive]);
  37. }
  38. }
  39. return [...groups.values()];
  40. }
  41. /**
  42. * Creates removal details for a set of directives within the same comment.
  43. * @param {Directive[]} directives Unused directives to be removed.
  44. * @param {Token} commentToken The backing Comment token.
  45. * @returns {{ description, fix, unprocessedDirective }[]} Details for later creation of output Problems.
  46. */
  47. function createIndividualDirectivesRemoval(directives, commentToken) {
  48. /*
  49. * `commentToken.value` starts right after `//` or `/*`.
  50. * All calculated offsets will be relative to this index.
  51. */
  52. const commentValueStart = commentToken.range[0] + "//".length;
  53. // Find where the list of rules starts. `\S+` matches with the directive name (e.g. `eslint-disable-line`)
  54. const listStartOffset = /^\s*\S+\s+/u.exec(commentToken.value)[0].length;
  55. /*
  56. * Get the list text without any surrounding whitespace. In order to preserve the original
  57. * formatting, we don't want to change that whitespace.
  58. *
  59. * // eslint-disable-line rule-one , rule-two , rule-three -- comment
  60. * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  61. */
  62. const listText = commentToken.value
  63. .slice(listStartOffset) // remove directive name and all whitespace before the list
  64. .split(/\s-{2,}\s/u)[0] // remove `-- comment`, if it exists
  65. .trimEnd(); // remove all whitespace after the list
  66. /*
  67. * We can assume that `listText` contains multiple elements.
  68. * Otherwise, this function wouldn't be called - if there is
  69. * only one rule in the list, then the whole comment must be removed.
  70. */
  71. return directives.map(directive => {
  72. const { ruleId } = directive;
  73. const regex = new RegExp(String.raw`(?:^|\s*,\s*)${escapeRegExp(ruleId)}(?:\s*,\s*|$)`, "u");
  74. const match = regex.exec(listText);
  75. const matchedText = match[0];
  76. const matchStartOffset = listStartOffset + match.index;
  77. const matchEndOffset = matchStartOffset + matchedText.length;
  78. const firstIndexOfComma = matchedText.indexOf(",");
  79. const lastIndexOfComma = matchedText.lastIndexOf(",");
  80. let removalStartOffset, removalEndOffset;
  81. if (firstIndexOfComma !== lastIndexOfComma) {
  82. /*
  83. * Since there are two commas, this must one of the elements in the middle of the list.
  84. * Matched range starts where the previous rule name ends, and ends where the next rule name starts.
  85. *
  86. * // eslint-disable-line rule-one , rule-two , rule-three -- comment
  87. * ^^^^^^^^^^^^^^
  88. *
  89. * We want to remove only the content between the two commas, and also one of the commas.
  90. *
  91. * // eslint-disable-line rule-one , rule-two , rule-three -- comment
  92. * ^^^^^^^^^^^
  93. */
  94. removalStartOffset = matchStartOffset + firstIndexOfComma;
  95. removalEndOffset = matchStartOffset + lastIndexOfComma;
  96. } else {
  97. /*
  98. * This is either the first element or the last element.
  99. *
  100. * If this is the first element, matched range starts where the first rule name starts
  101. * and ends where the second rule name starts. This is exactly the range we want
  102. * to remove so that the second rule name will start where the first one was starting
  103. * and thus preserve the original formatting.
  104. *
  105. * // eslint-disable-line rule-one , rule-two , rule-three -- comment
  106. * ^^^^^^^^^^^
  107. *
  108. * Similarly, if this is the last element, we've already matched the range we want to
  109. * remove. The previous rule name will end where the last one was ending, relative
  110. * to the content on the right side.
  111. *
  112. * // eslint-disable-line rule-one , rule-two , rule-three -- comment
  113. * ^^^^^^^^^^^^^
  114. */
  115. removalStartOffset = matchStartOffset;
  116. removalEndOffset = matchEndOffset;
  117. }
  118. return {
  119. description: `'${ruleId}'`,
  120. fix: {
  121. range: [
  122. commentValueStart + removalStartOffset,
  123. commentValueStart + removalEndOffset
  124. ],
  125. text: ""
  126. },
  127. unprocessedDirective: directive.unprocessedDirective
  128. };
  129. });
  130. }
  131. /**
  132. * Creates a description of deleting an entire unused disable comment.
  133. * @param {Directive[]} directives Unused directives to be removed.
  134. * @param {Token} commentToken The backing Comment token.
  135. * @returns {{ description, fix, unprocessedDirective }} Details for later creation of an output Problem.
  136. */
  137. function createCommentRemoval(directives, commentToken) {
  138. const { range } = commentToken;
  139. const ruleIds = directives.filter(directive => directive.ruleId).map(directive => `'${directive.ruleId}'`);
  140. return {
  141. description: ruleIds.length <= 2
  142. ? ruleIds.join(" or ")
  143. : `${ruleIds.slice(0, ruleIds.length - 1).join(", ")}, or ${ruleIds[ruleIds.length - 1]}`,
  144. fix: {
  145. range,
  146. text: " "
  147. },
  148. unprocessedDirective: directives[0].unprocessedDirective
  149. };
  150. }
  151. /**
  152. * Parses details from directives to create output Problems.
  153. * @param {Directive[]} allDirectives Unused directives to be removed.
  154. * @returns {{ description, fix, unprocessedDirective }[]} Details for later creation of output Problems.
  155. */
  156. function processUnusedDisableDirectives(allDirectives) {
  157. const directiveGroups = groupByParentComment(allDirectives);
  158. return directiveGroups.flatMap(
  159. directives => {
  160. const { parentComment } = directives[0].unprocessedDirective;
  161. const remainingRuleIds = new Set(parentComment.ruleIds);
  162. for (const directive of directives) {
  163. remainingRuleIds.delete(directive.ruleId);
  164. }
  165. return remainingRuleIds.size
  166. ? createIndividualDirectivesRemoval(directives, parentComment.commentToken)
  167. : [createCommentRemoval(directives, parentComment.commentToken)];
  168. }
  169. );
  170. }
  171. /**
  172. * This is the same as the exported function, except that it
  173. * doesn't handle disable-line and disable-next-line directives, and it always reports unused
  174. * disable directives.
  175. * @param {Object} options options for applying directives. This is the same as the options
  176. * for the exported function, except that `reportUnusedDisableDirectives` is not supported
  177. * (this function always reports unused disable directives).
  178. * @returns {{problems: LintMessage[], unusedDisableDirectives: LintMessage[]}} An object with a list
  179. * of problems (including suppressed ones) and unused eslint-disable directives
  180. */
  181. function applyDirectives(options) {
  182. const problems = [];
  183. const usedDisableDirectives = new Set();
  184. for (const problem of options.problems) {
  185. let disableDirectivesForProblem = [];
  186. let nextDirectiveIndex = 0;
  187. while (
  188. nextDirectiveIndex < options.directives.length &&
  189. compareLocations(options.directives[nextDirectiveIndex], problem) <= 0
  190. ) {
  191. const directive = options.directives[nextDirectiveIndex++];
  192. if (directive.ruleId === null || directive.ruleId === problem.ruleId) {
  193. switch (directive.type) {
  194. case "disable":
  195. disableDirectivesForProblem.push(directive);
  196. break;
  197. case "enable":
  198. disableDirectivesForProblem = [];
  199. break;
  200. // no default
  201. }
  202. }
  203. }
  204. if (disableDirectivesForProblem.length > 0) {
  205. const suppressions = disableDirectivesForProblem.map(directive => ({
  206. kind: "directive",
  207. justification: directive.unprocessedDirective.justification
  208. }));
  209. if (problem.suppressions) {
  210. problem.suppressions = problem.suppressions.concat(suppressions);
  211. } else {
  212. problem.suppressions = suppressions;
  213. usedDisableDirectives.add(disableDirectivesForProblem[disableDirectivesForProblem.length - 1]);
  214. }
  215. }
  216. problems.push(problem);
  217. }
  218. const unusedDisableDirectivesToReport = options.directives
  219. .filter(directive => directive.type === "disable" && !usedDisableDirectives.has(directive));
  220. const processed = processUnusedDisableDirectives(unusedDisableDirectivesToReport);
  221. const unusedDisableDirectives = processed
  222. .map(({ description, fix, unprocessedDirective }) => {
  223. const { parentComment, type, line, column } = unprocessedDirective;
  224. return {
  225. ruleId: null,
  226. message: description
  227. ? `Unused eslint-disable directive (no problems were reported from ${description}).`
  228. : "Unused eslint-disable directive (no problems were reported).",
  229. line: type === "disable-next-line" ? parentComment.commentToken.loc.start.line : line,
  230. column: type === "disable-next-line" ? parentComment.commentToken.loc.start.column + 1 : column,
  231. severity: options.reportUnusedDisableDirectives === "warn" ? 1 : 2,
  232. nodeType: null,
  233. ...options.disableFixes ? {} : { fix }
  234. };
  235. });
  236. return { problems, unusedDisableDirectives };
  237. }
  238. /**
  239. * Given a list of directive comments (i.e. metadata about eslint-disable and eslint-enable comments) and a list
  240. * of reported problems, adds the suppression information to the problems.
  241. * @param {Object} options Information about directives and problems
  242. * @param {{
  243. * type: ("disable"|"enable"|"disable-line"|"disable-next-line"),
  244. * ruleId: (string|null),
  245. * line: number,
  246. * column: number,
  247. * justification: string
  248. * }} options.directives Directive comments found in the file, with one-based columns.
  249. * Two directive comments can only have the same location if they also have the same type (e.g. a single eslint-disable
  250. * comment for two different rules is represented as two directives).
  251. * @param {{ruleId: (string|null), line: number, column: number}[]} options.problems
  252. * A list of problems reported by rules, sorted by increasing location in the file, with one-based columns.
  253. * @param {"off" | "warn" | "error"} options.reportUnusedDisableDirectives If `"warn"` or `"error"`, adds additional problems for unused directives
  254. * @param {boolean} options.disableFixes If true, it doesn't make `fix` properties.
  255. * @returns {{ruleId: (string|null), line: number, column: number, suppressions?: {kind: string, justification: string}}[]}
  256. * An object with a list of reported problems, the suppressed of which contain the suppression information.
  257. */
  258. module.exports = ({ directives, disableFixes, problems, reportUnusedDisableDirectives = "off" }) => {
  259. const blockDirectives = directives
  260. .filter(directive => directive.type === "disable" || directive.type === "enable")
  261. .map(directive => Object.assign({}, directive, { unprocessedDirective: directive }))
  262. .sort(compareLocations);
  263. const lineDirectives = directives.flatMap(directive => {
  264. switch (directive.type) {
  265. case "disable":
  266. case "enable":
  267. return [];
  268. case "disable-line":
  269. return [
  270. { type: "disable", line: directive.line, column: 1, ruleId: directive.ruleId, unprocessedDirective: directive },
  271. { type: "enable", line: directive.line + 1, column: 0, ruleId: directive.ruleId, unprocessedDirective: directive }
  272. ];
  273. case "disable-next-line":
  274. return [
  275. { type: "disable", line: directive.line + 1, column: 1, ruleId: directive.ruleId, unprocessedDirective: directive },
  276. { type: "enable", line: directive.line + 2, column: 0, ruleId: directive.ruleId, unprocessedDirective: directive }
  277. ];
  278. default:
  279. throw new TypeError(`Unrecognized directive type '${directive.type}'`);
  280. }
  281. }).sort(compareLocations);
  282. const blockDirectivesResult = applyDirectives({
  283. problems,
  284. directives: blockDirectives,
  285. disableFixes,
  286. reportUnusedDisableDirectives
  287. });
  288. const lineDirectivesResult = applyDirectives({
  289. problems: blockDirectivesResult.problems,
  290. directives: lineDirectives,
  291. disableFixes,
  292. reportUnusedDisableDirectives
  293. });
  294. return reportUnusedDisableDirectives !== "off"
  295. ? lineDirectivesResult.problems
  296. .concat(blockDirectivesResult.unusedDisableDirectives)
  297. .concat(lineDirectivesResult.unusedDisableDirectives)
  298. .sort(compareLocations)
  299. : lineDirectivesResult.problems;
  300. };