2 * @fileoverview enforce a particular style for multiline comments
7 const astUtils
= require("./utils/ast-utils");
9 //------------------------------------------------------------------------------
11 //------------------------------------------------------------------------------
13 /** @type {import('../shared/types').Rule} */
19 description
: "enforce a particular style for multiline comments",
21 url
: "https://eslint.org/docs/rules/multiline-comment-style"
24 fixable
: "whitespace",
25 schema
: [{ enum: ["starred-block", "separate-lines", "bare-block"] }],
27 expectedBlock
: "Expected a block comment instead of consecutive line comments.",
28 expectedBareBlock
: "Expected a block comment without padding stars.",
29 startNewline
: "Expected a linebreak after '/*'.",
30 endNewline
: "Expected a linebreak before '*/'.",
31 missingStar
: "Expected a '*' at the start of this line.",
32 alignment
: "Expected this line to be aligned with the start of the comment.",
33 expectedLines
: "Expected multiple line comments instead of a block comment."
38 const sourceCode
= context
.getSourceCode();
39 const option
= context
.options
[0] || "starred-block";
41 //----------------------------------------------------------------------
43 //----------------------------------------------------------------------
46 * Checks if a comment line is starred.
47 * @param {string} line A string representing a comment line.
48 * @returns {boolean} Whether or not the comment line is starred.
50 function isStarredCommentLine(line
) {
51 return /^\s*\*/u.test(line
);
55 * Checks if a comment group is in starred-block form.
56 * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment.
57 * @returns {boolean} Whether or not the comment group is in starred block form.
59 function isStarredBlockComment([firstComment
]) {
60 if (firstComment
.type
!== "Block") {
64 const lines
= firstComment
.value
.split(astUtils
.LINEBREAK_MATCHER
);
66 // The first and last lines can only contain whitespace.
67 return lines
.length
> 0 && lines
.every((line
, i
) => (i
=== 0 || i
=== lines
.length
- 1 ? /^\s*$/u : /^\s*\*/u).test(line
));
71 * Checks if a comment group is in JSDoc form.
72 * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment.
73 * @returns {boolean} Whether or not the comment group is in JSDoc form.
75 function isJSDocComment([firstComment
]) {
76 if (firstComment
.type
!== "Block") {
80 const lines
= firstComment
.value
.split(astUtils
.LINEBREAK_MATCHER
);
82 return /^\*\s*$/u.test(lines
[0]) &&
83 lines
.slice(1, -1).every(line
=> /^\s* /u.test(line
)) &&
84 /^\s*$/u.test(lines
[lines
.length
- 1]);
88 * Processes a comment group that is currently in separate-line form, calculating the offset for each line.
89 * @param {Token[]} commentGroup A group of comments containing multiple line comments.
90 * @returns {string[]} An array of the processed lines.
92 function processSeparateLineComments(commentGroup
) {
93 const allLinesHaveLeadingSpace
= commentGroup
94 .map(({ value
}) => value
)
95 .filter(line
=> line
.trim().length
)
96 .every(line
=> line
.startsWith(" "));
98 return commentGroup
.map(({ value
}) => (allLinesHaveLeadingSpace
? value
.replace(/^ /u, "") : value
));
102 * Processes a comment group that is currently in starred-block form, calculating the offset for each line.
103 * @param {Token} comment A single block comment token in starred-block form.
104 * @returns {string[]} An array of the processed lines.
106 function processStarredBlockComment(comment
) {
107 const lines
= comment
.value
.split(astUtils
.LINEBREAK_MATCHER
)
108 .filter((line
, i
, linesArr
) => !(i
=== 0 || i
=== linesArr
.length
- 1))
109 .map(line
=> line
.replace(/^\s*$/u, ""));
110 const allLinesHaveLeadingSpace
= lines
111 .map(line
=> line
.replace(/\s*\*/u, ""))
112 .filter(line
=> line
.trim().length
)
113 .every(line
=> line
.startsWith(" "));
115 return lines
.map(line
=> line
.replace(allLinesHaveLeadingSpace
? /\s*\* ?/u : /\s*\*/u, ""));
119 * Processes a comment group that is currently in bare-block form, calculating the offset for each line.
120 * @param {Token} comment A single block comment token in bare-block form.
121 * @returns {string[]} An array of the processed lines.
123 function processBareBlockComment(comment
) {
124 const lines
= comment
.value
.split(astUtils
.LINEBREAK_MATCHER
).map(line
=> line
.replace(/^\s*$/u, ""));
125 const leadingWhitespace
= `${sourceCode.text.slice(comment.range[0] - comment.loc.start.column, comment.range[0])} `;
129 * Calculate the offset of the least indented line and use that as the basis for offsetting all the lines.
130 * The first line should not be checked because it is inline with the opening block comment delimiter.
132 for (const [i
, line
] of lines
.entries()) {
133 if (!line
.trim().length
|| i
=== 0) {
137 const [, lineOffset
] = line
.match(/^(\s*\*?\s*)/u);
139 if (lineOffset
.length
< leadingWhitespace
.length
) {
140 const newOffset
= leadingWhitespace
.slice(lineOffset
.length
- leadingWhitespace
.length
);
142 if (newOffset
.length
> offset
.length
) {
148 return lines
.map(line
=> {
149 const match
= line
.match(/^(\s*\*?\s*)(.*)/u);
150 const [, lineOffset
, lineContents
] = match
;
152 if (lineOffset
.length
> leadingWhitespace
.length
) {
153 return `${lineOffset.slice(leadingWhitespace.length - (offset.length + lineOffset.length))}${lineContents}`;
156 if (lineOffset
.length
< leadingWhitespace
.length
) {
157 return `${lineOffset.slice(leadingWhitespace.length)}${lineContents}`;
165 * Gets a list of comment lines in a group, formatting leading whitespace as necessary.
166 * @param {Token[]} commentGroup A group of comments containing either multiple line comments or a single block comment.
167 * @returns {string[]} A list of comment lines.
169 function getCommentLines(commentGroup
) {
170 const [firstComment
] = commentGroup
;
172 if (firstComment
.type
=== "Line") {
173 return processSeparateLineComments(commentGroup
);
176 if (isStarredBlockComment(commentGroup
)) {
177 return processStarredBlockComment(firstComment
);
180 return processBareBlockComment(firstComment
);
184 * Gets the initial offset (whitespace) from the beginning of a line to a given comment token.
185 * @param {Token} comment The token to check.
186 * @returns {string} The offset from the beginning of a line to the token.
188 function getInitialOffset(comment
) {
189 return sourceCode
.text
.slice(comment
.range
[0] - comment
.loc
.start
.column
, comment
.range
[0]);
193 * Converts a comment into starred-block form
194 * @param {Token} firstComment The first comment of the group being converted
195 * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
196 * @returns {string} A representation of the comment value in starred-block form, excluding start and end markers
198 function convertToStarredBlock(firstComment
, commentLinesList
) {
199 const initialOffset
= getInitialOffset(firstComment
);
201 return `/*\n${commentLinesList.map(line => `${initialOffset} * ${line}`).join("\n")}\n${initialOffset} */
`;
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
210 function convertToSeparateLines(firstComment, commentLinesList) {
211 return commentLinesList.map(line => `// ${line}`).join(`\n${getInitialOffset(firstComment)}`);
215 * Converts a comment into bare-block form
216 * @param {Token} firstComment The first comment of the group being converted
217 * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
218 * @returns {string} A representation of the comment value in bare-block form
220 function convertToBlock(firstComment
, commentLinesList
) {
221 return `/* ${commentLinesList.join(`\n${getInitialOffset(firstComment)} `)} */
`;
225 * Each method checks a group of comments to see if it's valid according to the given option.
226 * @param {Token[]} commentGroup A list of comments that appear together. This will either contain a single
227 * block comment or multiple line comments.
230 const commentGroupCheckers = {
231 "starred-block"(commentGroup) {
232 const [firstComment] = commentGroup;
233 const commentLines = getCommentLines(commentGroup);
235 if (commentLines.some(value => value.includes("*/"))) {
239 if (commentGroup.length > 1) {
242 start: firstComment.loc.start,
243 end: commentGroup[commentGroup.length - 1].loc.end
245 messageId: "expectedBlock",
247 const range = [firstComment.range[0], commentGroup[commentGroup.length - 1].range[1]];
249 return commentLines.some(value => value.startsWith("/"))
251 : fixer.replaceTextRange(range, convertToStarredBlock(firstComment, commentLines));
255 const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER);
256 const expectedLeadingWhitespace = getInitialOffset(firstComment);
257 const expectedLinePrefix = `${expectedLeadingWhitespace}
*`;
259 if (!/^\*?\s*$/u.test(lines[0])) {
260 const start = firstComment.value.startsWith("*") ? firstComment.range[0] + 1 : firstComment.range[0];
264 start: firstComment.loc.start,
265 end: { line: firstComment.loc.start.line, column: firstComment.loc.start.column + 2 }
267 messageId: "startNewline",
268 fix: fixer => fixer.insertTextAfterRange([start, start + 2], `\n${expectedLinePrefix}
`)
272 if (!/^\s*$/u.test(lines[lines.length - 1])) {
275 start: { line: firstComment.loc.end.line, column: firstComment.loc.end.column - 2 },
276 end: firstComment.loc.end
278 messageId: "endNewline",
279 fix: fixer => fixer.replaceTextRange([firstComment.range[1] - 2, firstComment.range[1]], `\n${expectedLinePrefix}
/`)
283 for (let lineNumber = firstComment.loc.start.line + 1; lineNumber <= firstComment.loc.end.line; lineNumber++) {
284 const lineText = sourceCode.lines[lineNumber - 1];
285 const errorType = isStarredCommentLine(lineText)
289 if (!lineText.startsWith(expectedLinePrefix)) {
292 start: { line: lineNumber, column: 0 },
293 end: { line: lineNumber, column: lineText.length }
295 messageId: errorType,
297 const lineStartIndex = sourceCode.getIndexFromLoc({ line: lineNumber, column: 0 });
299 if (errorType === "alignment") {
300 const [, commentTextPrefix = ""] = lineText.match(/^(\s*\*)/u) || [];
301 const commentTextStartIndex = lineStartIndex + commentTextPrefix.length;
303 return fixer.replaceTextRange([lineStartIndex, commentTextStartIndex], expectedLinePrefix);
306 const [, commentTextPrefix = ""] = lineText.match(/^(\s*)/u) || [];
307 const commentTextStartIndex = lineStartIndex + commentTextPrefix.length;
310 for (const [idx, line] of lines.entries()) {
311 if (!/\S+/u.test(line)) {
315 const lineTextToAlignWith = sourceCode.lines[firstComment.loc.start.line - 1 + idx];
316 const [, prefix = "", initialOffset = ""] = lineTextToAlignWith.match(/^(\s*(?:\/?\*)?(\s*))/u) || [];
318 offset = `${commentTextPrefix.slice(prefix.length)}${initialOffset}
`;
320 if (/^\s*\//u.test(lineText) && offset.length === 0) {
326 return fixer.replaceTextRange([lineStartIndex, commentTextStartIndex], `${expectedLinePrefix}${offset}
`);
333 "separate-lines"(commentGroup) {
334 const [firstComment] = commentGroup;
336 if (firstComment.type !== "Block" || isJSDocComment(commentGroup)) {
340 const commentLines = getCommentLines(commentGroup);
341 const tokenAfter = sourceCode.getTokenAfter(firstComment, { includeComments: true });
343 if (tokenAfter && firstComment.loc.end.line === tokenAfter.loc.start.line) {
349 start: firstComment.loc.start,
350 end: { line: firstComment.loc.start.line, column: firstComment.loc.start.column + 2 }
352 messageId: "expectedLines",
354 return fixer.replaceText(firstComment, convertToSeparateLines(firstComment, commentLines));
358 "bare-block"(commentGroup) {
359 if (isJSDocComment(commentGroup)) {
363 const [firstComment] = commentGroup;
364 const commentLines = getCommentLines(commentGroup);
366 // Disallows consecutive line comments in favor of using a block comment.
367 if (firstComment.type === "Line" && commentLines.length > 1 &&
368 !commentLines.some(value => value.includes("*/"))) {
371 start: firstComment.loc.start,
372 end: commentGroup[commentGroup.length - 1].loc.end
374 messageId: "expectedBlock",
376 return fixer.replaceTextRange(
377 [firstComment.range[0], commentGroup[commentGroup.length - 1].range[1]],
378 convertToBlock(firstComment, commentLines)
384 // Prohibits block comments from having a * at the beginning of each line.
385 if (isStarredBlockComment(commentGroup)) {
388 start: firstComment.loc.start,
389 end: { line: firstComment.loc.start.line, column: firstComment.loc.start.column + 2 }
391 messageId: "expectedBareBlock",
393 return fixer.replaceText(firstComment, convertToBlock(firstComment, commentLines));
400 //----------------------------------------------------------------------
402 //----------------------------------------------------------------------
406 return sourceCode.getAllComments()
407 .filter(comment => comment.type !== "Shebang")
408 .filter(comment => !astUtils.COMMENTS_IGNORE_PATTERN.test(comment.value))
410 const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
412 return !tokenBefore || tokenBefore.loc.end.line < comment.loc.start.line;
414 .reduce((commentGroups, comment, index, commentList) => {
415 const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
418 comment.type === "Line" &&
419 index && commentList[index - 1].type === "Line" &&
420 tokenBefore && tokenBefore.loc.end.line === comment.loc.start.line - 1 &&
421 tokenBefore === commentList[index - 1]
423 commentGroups[commentGroups.length - 1].push(comment);
425 commentGroups.push([comment]);
428 return commentGroups;
430 .filter(commentGroup => !(commentGroup.length === 1 && commentGroup[0].loc.start.line === commentGroup[0].loc.end.line))
431 .forEach(commentGroupCheckers[option]);