multiline-comment-style.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /**
  2. * @fileoverview enforce a particular style for multiline comments
  3. * @author Teddy Katz
  4. */
  5. "use strict";
  6. const astUtils = require("../util/ast-utils");
  7. //------------------------------------------------------------------------------
  8. // Rule Definition
  9. //------------------------------------------------------------------------------
  10. module.exports = {
  11. meta: {
  12. type: "suggestion",
  13. docs: {
  14. description: "enforce a particular style for multiline comments",
  15. category: "Stylistic Issues",
  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. startNewline: "Expected a linebreak after '/*'.",
  24. endNewline: "Expected a linebreak before '*/'.",
  25. missingStar: "Expected a '*' at the start of this line.",
  26. alignment: "Expected this line to be aligned with the start of the comment.",
  27. expectedLines: "Expected multiple line comments instead of a block comment."
  28. }
  29. },
  30. create(context) {
  31. const sourceCode = context.getSourceCode();
  32. const option = context.options[0] || "starred-block";
  33. //----------------------------------------------------------------------
  34. // Helpers
  35. //----------------------------------------------------------------------
  36. /**
  37. * Gets a list of comment lines in a group
  38. * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment
  39. * @returns {string[]} A list of comment lines
  40. */
  41. function getCommentLines(commentGroup) {
  42. if (commentGroup[0].type === "Line") {
  43. return commentGroup.map(comment => comment.value);
  44. }
  45. return commentGroup[0].value
  46. .split(astUtils.LINEBREAK_MATCHER)
  47. .map(line => line.replace(/^\s*\*?/u, ""));
  48. }
  49. /**
  50. * Converts a comment into starred-block form
  51. * @param {Token} firstComment The first comment of the group being converted
  52. * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
  53. * @returns {string} A representation of the comment value in starred-block form, excluding start and end markers
  54. */
  55. function convertToStarredBlock(firstComment, commentLinesList) {
  56. const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
  57. const starredLines = commentLinesList.map(line => `${initialOffset} *${line}`);
  58. return `\n${starredLines.join("\n")}\n${initialOffset} `;
  59. }
  60. /**
  61. * Converts a comment into separate-line form
  62. * @param {Token} firstComment The first comment of the group being converted
  63. * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
  64. * @returns {string} A representation of the comment value in separate-line form
  65. */
  66. function convertToSeparateLines(firstComment, commentLinesList) {
  67. const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
  68. const separateLines = commentLinesList.map(line => `// ${line.trim()}`);
  69. return separateLines.join(`\n${initialOffset}`);
  70. }
  71. /**
  72. * Converts a comment into bare-block form
  73. * @param {Token} firstComment The first comment of the group being converted
  74. * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
  75. * @returns {string} A representation of the comment value in bare-block form
  76. */
  77. function convertToBlock(firstComment, commentLinesList) {
  78. const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
  79. const blockLines = commentLinesList.map(line => line.trim());
  80. return `/* ${blockLines.join(`\n${initialOffset} `)} */`;
  81. }
  82. /**
  83. * Check a comment is JSDoc form
  84. * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment
  85. * @returns {boolean} if commentGroup is JSDoc form, return true
  86. */
  87. function isJSDoc(commentGroup) {
  88. const lines = commentGroup[0].value.split(astUtils.LINEBREAK_MATCHER);
  89. return commentGroup[0].type === "Block" &&
  90. /^\*\s*$/u.test(lines[0]) &&
  91. lines.slice(1, -1).every(line => /^\s* /u.test(line)) &&
  92. /^\s*$/u.test(lines[lines.length - 1]);
  93. }
  94. /**
  95. * Each method checks a group of comments to see if it's valid according to the given option.
  96. * @param {Token[]} commentGroup A list of comments that appear together. This will either contain a single
  97. * block comment or multiple line comments.
  98. * @returns {void}
  99. */
  100. const commentGroupCheckers = {
  101. "starred-block"(commentGroup) {
  102. const commentLines = getCommentLines(commentGroup);
  103. if (commentLines.some(value => value.includes("*/"))) {
  104. return;
  105. }
  106. if (commentGroup.length > 1) {
  107. context.report({
  108. loc: {
  109. start: commentGroup[0].loc.start,
  110. end: commentGroup[commentGroup.length - 1].loc.end
  111. },
  112. messageId: "expectedBlock",
  113. fix(fixer) {
  114. const range = [commentGroup[0].range[0], commentGroup[commentGroup.length - 1].range[1]];
  115. const starredBlock = `/*${convertToStarredBlock(commentGroup[0], commentLines)}*/`;
  116. return commentLines.some(value => value.startsWith("/"))
  117. ? null
  118. : fixer.replaceTextRange(range, starredBlock);
  119. }
  120. });
  121. } else {
  122. const block = commentGroup[0];
  123. const lines = block.value.split(astUtils.LINEBREAK_MATCHER);
  124. const expectedLinePrefix = `${sourceCode.text.slice(block.range[0] - block.loc.start.column, block.range[0])} *`;
  125. if (!/^\*?\s*$/u.test(lines[0])) {
  126. const start = block.value.startsWith("*") ? block.range[0] + 1 : block.range[0];
  127. context.report({
  128. loc: {
  129. start: block.loc.start,
  130. end: { line: block.loc.start.line, column: block.loc.start.column + 2 }
  131. },
  132. messageId: "startNewline",
  133. fix: fixer => fixer.insertTextAfterRange([start, start + 2], `\n${expectedLinePrefix}`)
  134. });
  135. }
  136. if (!/^\s*$/u.test(lines[lines.length - 1])) {
  137. context.report({
  138. loc: {
  139. start: { line: block.loc.end.line, column: block.loc.end.column - 2 },
  140. end: block.loc.end
  141. },
  142. messageId: "endNewline",
  143. fix: fixer => fixer.replaceTextRange([block.range[1] - 2, block.range[1]], `\n${expectedLinePrefix}/`)
  144. });
  145. }
  146. for (let lineNumber = block.loc.start.line + 1; lineNumber <= block.loc.end.line; lineNumber++) {
  147. const lineText = sourceCode.lines[lineNumber - 1];
  148. if (!lineText.startsWith(expectedLinePrefix)) {
  149. context.report({
  150. loc: {
  151. start: { line: lineNumber, column: 0 },
  152. end: { line: lineNumber, column: sourceCode.lines[lineNumber - 1].length }
  153. },
  154. messageId: /^\s*\*/u.test(lineText)
  155. ? "alignment"
  156. : "missingStar",
  157. fix(fixer) {
  158. const lineStartIndex = sourceCode.getIndexFromLoc({ line: lineNumber, column: 0 });
  159. const linePrefixLength = lineText.match(/^\s*\*? ?/u)[0].length;
  160. const commentStartIndex = lineStartIndex + linePrefixLength;
  161. const replacementText = lineNumber === block.loc.end.line || lineText.length === linePrefixLength
  162. ? expectedLinePrefix
  163. : `${expectedLinePrefix} `;
  164. return fixer.replaceTextRange([lineStartIndex, commentStartIndex], replacementText);
  165. }
  166. });
  167. }
  168. }
  169. }
  170. },
  171. "separate-lines"(commentGroup) {
  172. if (!isJSDoc(commentGroup) && commentGroup[0].type === "Block") {
  173. const commentLines = getCommentLines(commentGroup);
  174. const block = commentGroup[0];
  175. const tokenAfter = sourceCode.getTokenAfter(block, { includeComments: true });
  176. if (tokenAfter && block.loc.end.line === tokenAfter.loc.start.line) {
  177. return;
  178. }
  179. context.report({
  180. loc: {
  181. start: block.loc.start,
  182. end: { line: block.loc.start.line, column: block.loc.start.column + 2 }
  183. },
  184. messageId: "expectedLines",
  185. fix(fixer) {
  186. return fixer.replaceText(block, convertToSeparateLines(block, commentLines.filter(line => line)));
  187. }
  188. });
  189. }
  190. },
  191. "bare-block"(commentGroup) {
  192. if (!isJSDoc(commentGroup)) {
  193. const commentLines = getCommentLines(commentGroup);
  194. // disallows consecutive line comments in favor of using a block comment.
  195. if (commentGroup[0].type === "Line" && commentLines.length > 1 &&
  196. !commentLines.some(value => value.includes("*/"))) {
  197. context.report({
  198. loc: {
  199. start: commentGroup[0].loc.start,
  200. end: commentGroup[commentGroup.length - 1].loc.end
  201. },
  202. messageId: "expectedBlock",
  203. fix(fixer) {
  204. const range = [commentGroup[0].range[0], commentGroup[commentGroup.length - 1].range[1]];
  205. const block = convertToBlock(commentGroup[0], commentLines.filter(line => line));
  206. return fixer.replaceTextRange(range, block);
  207. }
  208. });
  209. }
  210. // prohibits block comments from having a * at the beginning of each line.
  211. if (commentGroup[0].type === "Block") {
  212. const block = commentGroup[0];
  213. const lines = block.value.split(astUtils.LINEBREAK_MATCHER).filter(line => line.trim());
  214. if (lines.length > 0 && lines.every(line => /^\s*\*/u.test(line))) {
  215. context.report({
  216. loc: {
  217. start: block.loc.start,
  218. end: { line: block.loc.start.line, column: block.loc.start.column + 2 }
  219. },
  220. messageId: "expectedBlock",
  221. fix(fixer) {
  222. return fixer.replaceText(block, convertToBlock(block, commentLines.filter(line => line)));
  223. }
  224. });
  225. }
  226. }
  227. }
  228. }
  229. };
  230. //----------------------------------------------------------------------
  231. // Public
  232. //----------------------------------------------------------------------
  233. return {
  234. Program() {
  235. return sourceCode.getAllComments()
  236. .filter(comment => comment.type !== "Shebang")
  237. .filter(comment => !astUtils.COMMENTS_IGNORE_PATTERN.test(comment.value))
  238. .filter(comment => {
  239. const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
  240. return !tokenBefore || tokenBefore.loc.end.line < comment.loc.start.line;
  241. })
  242. .reduce((commentGroups, comment, index, commentList) => {
  243. const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
  244. if (
  245. comment.type === "Line" &&
  246. index && commentList[index - 1].type === "Line" &&
  247. tokenBefore && tokenBefore.loc.end.line === comment.loc.start.line - 1 &&
  248. tokenBefore === commentList[index - 1]
  249. ) {
  250. commentGroups[commentGroups.length - 1].push(comment);
  251. } else {
  252. commentGroups.push([comment]);
  253. }
  254. return commentGroups;
  255. }, [])
  256. .filter(commentGroup => !(commentGroup.length === 1 && commentGroup[0].loc.start.line === commentGroup[0].loc.end.line))
  257. .forEach(commentGroupCheckers[option]);
  258. }
  259. };
  260. }
  261. };