multiline-comment-style.js 21 KB

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