1/** 2 * @fileoverview enforce a particular style for multiline comments 3 * @author Teddy Katz 4 */ 5"use strict"; 6 7const astUtils = require("./utils/ast-utils"); 8 9//------------------------------------------------------------------------------ 10// Rule Definition 11//------------------------------------------------------------------------------ 12 13module.exports = { 14 meta: { 15 type: "suggestion", 16 17 docs: { 18 description: "enforce a particular style for multiline comments", 19 category: "Stylistic Issues", 20 recommended: false, 21 url: "https://eslint.org/docs/rules/multiline-comment-style" 22 }, 23 24 fixable: "whitespace", 25 schema: [{ enum: ["starred-block", "separate-lines", "bare-block"] }], 26 messages: { 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." 34 } 35 }, 36 37 create(context) { 38 const sourceCode = context.getSourceCode(); 39 const option = context.options[0] || "starred-block"; 40 41 //---------------------------------------------------------------------- 42 // Helpers 43 //---------------------------------------------------------------------- 44 45 /** 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. 49 */ 50 function isStarredCommentLine(line) { 51 return /^\s*\*/u.test(line); 52 } 53 54 /** 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. 58 */ 59 function isStarredBlockComment([firstComment]) { 60 if (firstComment.type !== "Block") { 61 return false; 62 } 63 64 const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER); 65 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)); 68 } 69 70 /** 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. 74 */ 75 function isJSDocComment([firstComment]) { 76 if (firstComment.type !== "Block") { 77 return false; 78 } 79 80 const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER); 81 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]); 85 } 86 87 /** 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. 91 */ 92 function processSeparateLineComments(commentGroup) { 93 const allLinesHaveLeadingSpace = commentGroup 94 .map(({ value }) => value) 95 .filter(line => line.trim().length) 96 .every(line => line.startsWith(" ")); 97 98 return commentGroup.map(({ value }) => (allLinesHaveLeadingSpace ? value.replace(/^ /u, "") : value)); 99 } 100 101 /** 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. 105 */ 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(" ")); 114 115 return lines.map(line => line.replace(allLinesHaveLeadingSpace ? /\s*\* ?/u : /\s*\*/u, "")); 116 } 117 118 /** 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. 122 */ 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])} `; 126 let offset = ""; 127 128 /* 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. 131 */ 132 for (const [i, line] of lines.entries()) { 133 if (!line.trim().length || i === 0) { 134 continue; 135 } 136 137 const [, lineOffset] = line.match(/^(\s*\*?\s*)/u); 138 139 if (lineOffset.length < leadingWhitespace.length) { 140 const newOffset = leadingWhitespace.slice(lineOffset.length - leadingWhitespace.length); 141 142 if (newOffset.length > offset.length) { 143 offset = newOffset; 144 } 145 } 146 } 147 148 return lines.map(line => { 149 const match = line.match(/^(\s*\*?\s*)(.*)/u); 150 const [, lineOffset, lineContents] = match; 151 152 if (lineOffset.length > leadingWhitespace.length) { 153 return `${lineOffset.slice(leadingWhitespace.length - (offset.length + lineOffset.length))}${lineContents}`; 154 } 155 156 if (lineOffset.length < leadingWhitespace.length) { 157 return `${lineOffset.slice(leadingWhitespace.length)}${lineContents}`; 158 } 159 160 return lineContents; 161 }); 162 } 163 164 /** 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. 168 */ 169 function getCommentLines(commentGroup) { 170 const [firstComment] = commentGroup; 171 172 if (firstComment.type === "Line") { 173 return processSeparateLineComments(commentGroup); 174 } 175 176 if (isStarredBlockComment(commentGroup)) { 177 return processStarredBlockComment(firstComment); 178 } 179 180 return processBareBlockComment(firstComment); 181 } 182 183 /** 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. 187 */ 188 function getInitialOffset(comment) { 189 return sourceCode.text.slice(comment.range[0] - comment.loc.start.column, comment.range[0]); 190 } 191 192 /** 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 197 */ 198 function convertToStarredBlock(firstComment, commentLinesList) { 199 const initialOffset = getInitialOffset(firstComment); 200 201 return `/*\n${commentLinesList.map(line => `${initialOffset} * ${line}`).join("\n")}\n${initialOffset} */`; 202 } 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 /** 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 219 */ 220 function convertToBlock(firstComment, commentLinesList) { 221 return `/* ${commentLinesList.join(`\n${getInitialOffset(firstComment)} `)} */`; 222 } 223 224 /** 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. 228 * @returns {void} 229 */ 230 const commentGroupCheckers = { 231 "starred-block"(commentGroup) { 232 const [firstComment] = commentGroup; 233 const commentLines = getCommentLines(commentGroup); 234 235 if (commentLines.some(value => value.includes("*/"))) { 236 return; 237 } 238 239 if (commentGroup.length > 1) { 240 context.report({ 241 loc: { 242 start: firstComment.loc.start, 243 end: commentGroup[commentGroup.length - 1].loc.end 244 }, 245 messageId: "expectedBlock", 246 fix(fixer) { 247 const range = [firstComment.range[0], commentGroup[commentGroup.length - 1].range[1]]; 248 249 return commentLines.some(value => value.startsWith("/")) 250 ? null 251 : fixer.replaceTextRange(range, convertToStarredBlock(firstComment, commentLines)); 252 } 253 }); 254 } else { 255 const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER); 256 const expectedLeadingWhitespace = getInitialOffset(firstComment); 257 const expectedLinePrefix = `${expectedLeadingWhitespace} *`; 258 259 if (!/^\*?\s*$/u.test(lines[0])) { 260 const start = firstComment.value.startsWith("*") ? firstComment.range[0] + 1 : firstComment.range[0]; 261 262 context.report({ 263 loc: { 264 start: firstComment.loc.start, 265 end: { line: firstComment.loc.start.line, column: firstComment.loc.start.column + 2 } 266 }, 267 messageId: "startNewline", 268 fix: fixer => fixer.insertTextAfterRange([start, start + 2], `\n${expectedLinePrefix}`) 269 }); 270 } 271 272 if (!/^\s*$/u.test(lines[lines.length - 1])) { 273 context.report({ 274 loc: { 275 start: { line: firstComment.loc.end.line, column: firstComment.loc.end.column - 2 }, 276 end: firstComment.loc.end 277 }, 278 messageId: "endNewline", 279 fix: fixer => fixer.replaceTextRange([firstComment.range[1] - 2, firstComment.range[1]], `\n${expectedLinePrefix}/`) 280 }); 281 } 282 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) 286 ? "alignment" 287 : "missingStar"; 288 289 if (!lineText.startsWith(expectedLinePrefix)) { 290 context.report({ 291 loc: { 292 start: { line: lineNumber, column: 0 }, 293 end: { line: lineNumber, column: lineText.length } 294 }, 295 messageId: errorType, 296 fix(fixer) { 297 const lineStartIndex = sourceCode.getIndexFromLoc({ line: lineNumber, column: 0 }); 298 299 if (errorType === "alignment") { 300 const [, commentTextPrefix = ""] = lineText.match(/^(\s*\*)/u) || []; 301 const commentTextStartIndex = lineStartIndex + commentTextPrefix.length; 302 303 return fixer.replaceTextRange([lineStartIndex, commentTextStartIndex], expectedLinePrefix); 304 } 305 306 const [, commentTextPrefix = ""] = lineText.match(/^(\s*)/u) || []; 307 const commentTextStartIndex = lineStartIndex + commentTextPrefix.length; 308 let offset; 309 310 for (const [idx, line] of lines.entries()) { 311 if (!/\S+/u.test(line)) { 312 continue; 313 } 314 315 const lineTextToAlignWith = sourceCode.lines[firstComment.loc.start.line - 1 + idx]; 316 const [, prefix = "", initialOffset = ""] = lineTextToAlignWith.match(/^(\s*(?:\/?\*)?(\s*))/u) || []; 317 318 offset = `${commentTextPrefix.slice(prefix.length)}${initialOffset}`; 319 320 if (/^\s*\//u.test(lineText) && offset.length === 0) { 321 offset += " "; 322 } 323 break; 324 } 325 326 return fixer.replaceTextRange([lineStartIndex, commentTextStartIndex], `${expectedLinePrefix}${offset}`); 327 } 328 }); 329 } 330 } 331 } 332 }, 333 "separate-lines"(commentGroup) { 334 const [firstComment] = commentGroup; 335 336 if (firstComment.type !== "Block" || isJSDocComment(commentGroup)) { 337 return; 338 } 339 340 const commentLines = getCommentLines(commentGroup); 341 const tokenAfter = sourceCode.getTokenAfter(firstComment, { includeComments: true }); 342 343 if (tokenAfter && firstComment.loc.end.line === tokenAfter.loc.start.line) { 344 return; 345 } 346 347 context.report({ 348 loc: { 349 start: firstComment.loc.start, 350 end: { line: firstComment.loc.start.line, column: firstComment.loc.start.column + 2 } 351 }, 352 messageId: "expectedLines", 353 fix(fixer) { 354 return fixer.replaceText(firstComment, convertToSeparateLines(firstComment, commentLines)); 355 } 356 }); 357 }, 358 "bare-block"(commentGroup) { 359 if (isJSDocComment(commentGroup)) { 360 return; 361 } 362 363 const [firstComment] = commentGroup; 364 const commentLines = getCommentLines(commentGroup); 365 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("*/"))) { 369 context.report({ 370 loc: { 371 start: firstComment.loc.start, 372 end: commentGroup[commentGroup.length - 1].loc.end 373 }, 374 messageId: "expectedBlock", 375 fix(fixer) { 376 return fixer.replaceTextRange( 377 [firstComment.range[0], commentGroup[commentGroup.length - 1].range[1]], 378 convertToBlock(firstComment, commentLines) 379 ); 380 } 381 }); 382 } 383 384 // Prohibits block comments from having a * at the beginning of each line. 385 if (isStarredBlockComment(commentGroup)) { 386 context.report({ 387 loc: { 388 start: firstComment.loc.start, 389 end: { line: firstComment.loc.start.line, column: firstComment.loc.start.column + 2 } 390 }, 391 messageId: "expectedBareBlock", 392 fix(fixer) { 393 return fixer.replaceText(firstComment, convertToBlock(firstComment, commentLines)); 394 } 395 }); 396 } 397 } 398 }; 399 400 //---------------------------------------------------------------------- 401 // Public 402 //---------------------------------------------------------------------- 403 404 return { 405 Program() { 406 return sourceCode.getAllComments() 407 .filter(comment => comment.type !== "Shebang") 408 .filter(comment => !astUtils.COMMENTS_IGNORE_PATTERN.test(comment.value)) 409 .filter(comment => { 410 const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true }); 411 412 return !tokenBefore || tokenBefore.loc.end.line < comment.loc.start.line; 413 }) 414 .reduce((commentGroups, comment, index, commentList) => { 415 const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true }); 416 417 if ( 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] 422 ) { 423 commentGroups[commentGroups.length - 1].push(comment); 424 } else { 425 commentGroups.push([comment]); 426 } 427 428 return commentGroups; 429 }, []) 430 .filter(commentGroup => !(commentGroup.length === 1 && commentGroup[0].loc.start.line === commentGroup[0].loc.end.line)) 431 .forEach(commentGroupCheckers[option]); 432 } 433 }; 434 } 435}; 436