multiline-comment-style.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. /**
  2. * @fileoverview enforce a particular style for multiline comments
  3. * @author Teddy Katz
  4. */
  5. "use strict";
  6. const astUtils = require("./utils/ast-utils");
  7. //------------------------------------------------------------------------------
  8. // Rule Definition
  9. //------------------------------------------------------------------------------
  10. /** @type {import('../shared/types').Rule} */
  11. module.exports = {
  12. meta: {
  13. type: "suggestion",
  14. docs: {
  15. description: "Enforce a particular style for multiline comments",
  16. recommended: false,
  17. url: "https://eslint.org/docs/rules/multiline-comment-style"
  18. },
  19. fixable: "whitespace",
  20. schema: [{ enum: ["starred-block", "separate-lines", "bare-block"] }],
  21. messages: {
  22. expectedBlock: "Expected a block comment instead of consecutive line comments.",
  23. expectedBareBlock: "Expected a block comment without padding stars.",
  24. startNewline: "Expected a linebreak after '/*'.",
  25. endNewline: "Expected a linebreak before '*/'.",
  26. missingStar: "Expected a '*' at the start of this line.",
  27. alignment: "Expected this line to be aligned with the start of the comment.",
  28. expectedLines: "Expected multiple line comments instead of a block comment."
  29. }
  30. },
  31. create(context) {
  32. const sourceCode = context.getSourceCode();
  33. const option = context.options[0] || "starred-block";
  34. //----------------------------------------------------------------------
  35. // Helpers
  36. //----------------------------------------------------------------------
  37. /**
  38. * Checks if a comment line is starred.
  39. * @param {string} line A string representing a comment line.
  40. * @returns {boolean} Whether or not the comment line is starred.
  41. */
  42. function isStarredCommentLine(line) {
  43. return /^\s*\*/u.test(line);
  44. }
  45. /**
  46. * Checks if a comment group is in starred-block form.
  47. * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment.
  48. * @returns {boolean} Whether or not the comment group is in starred block form.
  49. */
  50. function isStarredBlockComment([firstComment]) {
  51. if (firstComment.type !== "Block") {
  52. return false;
  53. }
  54. const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER);
  55. // The first and last lines can only contain whitespace.
  56. return lines.length > 0 && lines.every((line, i) => (i === 0 || i === lines.length - 1 ? /^\s*$/u : /^\s*\*/u).test(line));
  57. }
  58. /**
  59. * Checks if a comment group is in JSDoc form.
  60. * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment.
  61. * @returns {boolean} Whether or not the comment group is in JSDoc form.
  62. */
  63. function isJSDocComment([firstComment]) {
  64. if (firstComment.type !== "Block") {
  65. return false;
  66. }
  67. const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER);
  68. return /^\*\s*$/u.test(lines[0]) &&
  69. lines.slice(1, -1).every(line => /^\s* /u.test(line)) &&
  70. /^\s*$/u.test(lines[lines.length - 1]);
  71. }
  72. /**
  73. * Processes a comment group that is currently in separate-line form, calculating the offset for each line.
  74. * @param {Token[]} commentGroup A group of comments containing multiple line comments.
  75. * @returns {string[]} An array of the processed lines.
  76. */
  77. function processSeparateLineComments(commentGroup) {
  78. const allLinesHaveLeadingSpace = commentGroup
  79. .map(({ value }) => value)
  80. .filter(line => line.trim().length)
  81. .every(line => line.startsWith(" "));
  82. return commentGroup.map(({ value }) => (allLinesHaveLeadingSpace ? value.replace(/^ /u, "") : value));
  83. }
  84. /**
  85. * Processes a comment group that is currently in starred-block form, calculating the offset for each line.
  86. * @param {Token} comment A single block comment token in starred-block form.
  87. * @returns {string[]} An array of the processed lines.
  88. */
  89. function processStarredBlockComment(comment) {
  90. const lines = comment.value.split(astUtils.LINEBREAK_MATCHER)
  91. .filter((line, i, linesArr) => !(i === 0 || i === linesArr.length - 1))
  92. .map(line => line.replace(/^\s*$/u, ""));
  93. const allLinesHaveLeadingSpace = lines
  94. .map(line => line.replace(/\s*\*/u, ""))
  95. .filter(line => line.trim().length)
  96. .every(line => line.startsWith(" "));
  97. return lines.map(line => line.replace(allLinesHaveLeadingSpace ? /\s*\* ?/u : /\s*\*/u, ""));
  98. }
  99. /**
  100. * Processes a comment group that is currently in bare-block form, calculating the offset for each line.
  101. * @param {Token} comment A single block comment token in bare-block form.
  102. * @returns {string[]} An array of the processed lines.
  103. */
  104. function processBareBlockComment(comment) {
  105. const lines = comment.value.split(astUtils.LINEBREAK_MATCHER).map(line => line.replace(/^\s*$/u, ""));
  106. const leadingWhitespace = `${sourceCode.text.slice(comment.range[0] - comment.loc.start.column, comment.range[0])} `;
  107. let offset = "";
  108. /*
  109. * Calculate the offset of the least indented line and use that as the basis for offsetting all the lines.
  110. * The first line should not be checked because it is inline with the opening block comment delimiter.
  111. */
  112. for (const [i, line] of lines.entries()) {
  113. if (!line.trim().length || i === 0) {
  114. continue;
  115. }
  116. const [, lineOffset] = line.match(/^(\s*\*?\s*)/u);
  117. if (lineOffset.length < leadingWhitespace.length) {
  118. const newOffset = leadingWhitespace.slice(lineOffset.length - leadingWhitespace.length);
  119. if (newOffset.length > offset.length) {
  120. offset = newOffset;
  121. }
  122. }
  123. }
  124. return lines.map(line => {
  125. const match = line.match(/^(\s*\*?\s*)(.*)/u);
  126. const [, lineOffset, lineContents] = match;
  127. if (lineOffset.length > leadingWhitespace.length) {
  128. return `${lineOffset.slice(leadingWhitespace.length - (offset.length + lineOffset.length))}${lineContents}`;
  129. }
  130. if (lineOffset.length < leadingWhitespace.length) {
  131. return `${lineOffset.slice(leadingWhitespace.length)}${lineContents}`;
  132. }
  133. return lineContents;
  134. });
  135. }
  136. /**
  137. * Gets a list of comment lines in a group, formatting leading whitespace as necessary.
  138. * @param {Token[]} commentGroup A group of comments containing either multiple line comments or a single block comment.
  139. * @returns {string[]} A list of comment lines.
  140. */
  141. function getCommentLines(commentGroup) {
  142. const [firstComment] = commentGroup;
  143. if (firstComment.type === "Line") {
  144. return processSeparateLineComments(commentGroup);
  145. }
  146. if (isStarredBlockComment(commentGroup)) {
  147. return processStarredBlockComment(firstComment);
  148. }
  149. return processBareBlockComment(firstComment);
  150. }
  151. /**
  152. * Gets the initial offset (whitespace) from the beginning of a line to a given comment token.
  153. * @param {Token} comment The token to check.
  154. * @returns {string} The offset from the beginning of a line to the token.
  155. */
  156. function getInitialOffset(comment) {
  157. return sourceCode.text.slice(comment.range[0] - comment.loc.start.column, comment.range[0]);
  158. }
  159. /**
  160. * Converts a comment into starred-block form
  161. * @param {Token} firstComment The first comment of the group being converted
  162. * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
  163. * @returns {string} A representation of the comment value in starred-block form, excluding start and end markers
  164. */
  165. function convertToStarredBlock(firstComment, commentLinesList) {
  166. const initialOffset = getInitialOffset(firstComment);
  167. return `/*\n${commentLinesList.map(line => `${initialOffset} * ${line}`).join("\n")}\n${initialOffset} */`;
  168. }
  169. /**
  170. * Converts a comment into separate-line form
  171. * @param {Token} firstComment The first comment of the group being converted
  172. * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
  173. * @returns {string} A representation of the comment value in separate-line form
  174. */
  175. function convertToSeparateLines(firstComment, commentLinesList) {
  176. return commentLinesList.map(line => `// ${line}`).join(`\n${getInitialOffset(firstComment)}`);
  177. }
  178. /**
  179. * Converts a comment into bare-block form
  180. * @param {Token} firstComment The first comment of the group being converted
  181. * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
  182. * @returns {string} A representation of the comment value in bare-block form
  183. */
  184. function convertToBlock(firstComment, commentLinesList) {
  185. return `/* ${commentLinesList.join(`\n${getInitialOffset(firstComment)} `)} */`;
  186. }
  187. /**
  188. * Each method checks a group of comments to see if it's valid according to the given option.
  189. * @param {Token[]} commentGroup A list of comments that appear together. This will either contain a single
  190. * block comment or multiple line comments.
  191. * @returns {void}
  192. */
  193. const commentGroupCheckers = {
  194. "starred-block"(commentGroup) {
  195. const [firstComment] = commentGroup;
  196. const commentLines = getCommentLines(commentGroup);
  197. if (commentLines.some(value => value.includes("*/"))) {
  198. return;
  199. }
  200. if (commentGroup.length > 1) {
  201. context.report({
  202. loc: {
  203. start: firstComment.loc.start,
  204. end: commentGroup[commentGroup.length - 1].loc.end
  205. },
  206. messageId: "expectedBlock",
  207. fix(fixer) {
  208. const range = [firstComment.range[0], commentGroup[commentGroup.length - 1].range[1]];
  209. return commentLines.some(value => value.startsWith("/"))
  210. ? null
  211. : fixer.replaceTextRange(range, convertToStarredBlock(firstComment, commentLines));
  212. }
  213. });
  214. } else {
  215. const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER);
  216. const expectedLeadingWhitespace = getInitialOffset(firstComment);
  217. const expectedLinePrefix = `${expectedLeadingWhitespace} *`;
  218. if (!/^\*?\s*$/u.test(lines[0])) {
  219. const start = firstComment.value.startsWith("*") ? firstComment.range[0] + 1 : firstComment.range[0];
  220. context.report({
  221. loc: {
  222. start: firstComment.loc.start,
  223. end: { line: firstComment.loc.start.line, column: firstComment.loc.start.column + 2 }
  224. },
  225. messageId: "startNewline",
  226. fix: fixer => fixer.insertTextAfterRange([start, start + 2], `\n${expectedLinePrefix}`)
  227. });
  228. }
  229. if (!/^\s*$/u.test(lines[lines.length - 1])) {
  230. context.report({
  231. loc: {
  232. start: { line: firstComment.loc.end.line, column: firstComment.loc.end.column - 2 },
  233. end: firstComment.loc.end
  234. },
  235. messageId: "endNewline",
  236. fix: fixer => fixer.replaceTextRange([firstComment.range[1] - 2, firstComment.range[1]], `\n${expectedLinePrefix}/`)
  237. });
  238. }
  239. for (let lineNumber = firstComment.loc.start.line + 1; lineNumber <= firstComment.loc.end.line; lineNumber++) {
  240. const lineText = sourceCode.lines[lineNumber - 1];
  241. const errorType = isStarredCommentLine(lineText)
  242. ? "alignment"
  243. : "missingStar";
  244. if (!lineText.startsWith(expectedLinePrefix)) {
  245. context.report({
  246. loc: {
  247. start: { line: lineNumber, column: 0 },
  248. end: { line: lineNumber, column: lineText.length }
  249. },
  250. messageId: errorType,
  251. fix(fixer) {
  252. const lineStartIndex = sourceCode.getIndexFromLoc({ line: lineNumber, column: 0 });
  253. if (errorType === "alignment") {
  254. const [, commentTextPrefix = ""] = lineText.match(/^(\s*\*)/u) || [];
  255. const commentTextStartIndex = lineStartIndex + commentTextPrefix.length;
  256. return fixer.replaceTextRange([lineStartIndex, commentTextStartIndex], expectedLinePrefix);
  257. }
  258. const [, commentTextPrefix = ""] = lineText.match(/^(\s*)/u) || [];
  259. const commentTextStartIndex = lineStartIndex + commentTextPrefix.length;
  260. let offset;
  261. for (const [idx, line] of lines.entries()) {
  262. if (!/\S+/u.test(line)) {
  263. continue;
  264. }
  265. const lineTextToAlignWith = sourceCode.lines[firstComment.loc.start.line - 1 + idx];
  266. const [, prefix = "", initialOffset = ""] = lineTextToAlignWith.match(/^(\s*(?:\/?\*)?(\s*))/u) || [];
  267. offset = `${commentTextPrefix.slice(prefix.length)}${initialOffset}`;
  268. if (/^\s*\//u.test(lineText) && offset.length === 0) {
  269. offset += " ";
  270. }
  271. break;
  272. }
  273. return fixer.replaceTextRange([lineStartIndex, commentTextStartIndex], `${expectedLinePrefix}${offset}`);
  274. }
  275. });
  276. }
  277. }
  278. }
  279. },
  280. "separate-lines"(commentGroup) {
  281. const [firstComment] = commentGroup;
  282. if (firstComment.type !== "Block" || isJSDocComment(commentGroup)) {
  283. return;
  284. }
  285. const commentLines = getCommentLines(commentGroup);
  286. const tokenAfter = sourceCode.getTokenAfter(firstComment, { includeComments: true });
  287. if (tokenAfter && firstComment.loc.end.line === tokenAfter.loc.start.line) {
  288. return;
  289. }
  290. context.report({
  291. loc: {
  292. start: firstComment.loc.start,
  293. end: { line: firstComment.loc.start.line, column: firstComment.loc.start.column + 2 }
  294. },
  295. messageId: "expectedLines",
  296. fix(fixer) {
  297. return fixer.replaceText(firstComment, convertToSeparateLines(firstComment, commentLines));
  298. }
  299. });
  300. },
  301. "bare-block"(commentGroup) {
  302. if (isJSDocComment(commentGroup)) {
  303. return;
  304. }
  305. const [firstComment] = commentGroup;
  306. const commentLines = getCommentLines(commentGroup);
  307. // Disallows consecutive line comments in favor of using a block comment.
  308. if (firstComment.type === "Line" && commentLines.length > 1 &&
  309. !commentLines.some(value => value.includes("*/"))) {
  310. context.report({
  311. loc: {
  312. start: firstComment.loc.start,
  313. end: commentGroup[commentGroup.length - 1].loc.end
  314. },
  315. messageId: "expectedBlock",
  316. fix(fixer) {
  317. return fixer.replaceTextRange(
  318. [firstComment.range[0], commentGroup[commentGroup.length - 1].range[1]],
  319. convertToBlock(firstComment, commentLines)
  320. );
  321. }
  322. });
  323. }
  324. // Prohibits block comments from having a * at the beginning of each line.
  325. if (isStarredBlockComment(commentGroup)) {
  326. context.report({
  327. loc: {
  328. start: firstComment.loc.start,
  329. end: { line: firstComment.loc.start.line, column: firstComment.loc.start.column + 2 }
  330. },
  331. messageId: "expectedBareBlock",
  332. fix(fixer) {
  333. return fixer.replaceText(firstComment, convertToBlock(firstComment, commentLines));
  334. }
  335. });
  336. }
  337. }
  338. };
  339. //----------------------------------------------------------------------
  340. // Public
  341. //----------------------------------------------------------------------
  342. return {
  343. Program() {
  344. return sourceCode.getAllComments()
  345. .filter(comment => comment.type !== "Shebang")
  346. .filter(comment => !astUtils.COMMENTS_IGNORE_PATTERN.test(comment.value))
  347. .filter(comment => {
  348. const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
  349. return !tokenBefore || tokenBefore.loc.end.line < comment.loc.start.line;
  350. })
  351. .reduce((commentGroups, comment, index, commentList) => {
  352. const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
  353. if (
  354. comment.type === "Line" &&
  355. index && commentList[index - 1].type === "Line" &&
  356. tokenBefore && tokenBefore.loc.end.line === comment.loc.start.line - 1 &&
  357. tokenBefore === commentList[index - 1]
  358. ) {
  359. commentGroups[commentGroups.length - 1].push(comment);
  360. } else {
  361. commentGroups.push([comment]);
  362. }
  363. return commentGroups;
  364. }, [])
  365. .filter(commentGroup => !(commentGroup.length === 1 && commentGroup[0].loc.start.line === commentGroup[0].loc.end.line))
  366. .forEach(commentGroupCheckers[option]);
  367. }
  368. };
  369. }
  370. };