multiline-comment-style.js 20.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
/**
 * @fileoverview enforce a particular style for multiline comments
 * @author Teddy Katz
 */
"use strict";

const astUtils = require("./utils/ast-utils");

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = {
    meta: {
        type: "suggestion",

        docs: {
            description: "enforce a particular style for multiline comments",
            category: "Stylistic Issues",
            recommended: false,
            url: "https://eslint.org/docs/rules/multiline-comment-style"
        },

        fixable: "whitespace",
        schema: [{ enum: ["starred-block", "separate-lines", "bare-block"] }],
        messages: {
            expectedBlock: "Expected a block comment instead of consecutive line comments.",
            expectedBareBlock: "Expected a block comment without padding stars.",
            startNewline: "Expected a linebreak after '/*'.",
            endNewline: "Expected a linebreak before '*/'.",
            missingStar: "Expected a '*' at the start of this line.",
            alignment: "Expected this line to be aligned with the start of the comment.",
            expectedLines: "Expected multiple line comments instead of a block comment."
        }
    },

    create(context) {
        const sourceCode = context.getSourceCode();
        const option = context.options[0] || "starred-block";

        //----------------------------------------------------------------------
        // Helpers
        //----------------------------------------------------------------------

        /**
         * Checks if a comment line is starred.
         * @param {string} line A string representing a comment line.
         * @returns {boolean} Whether or not the comment line is starred.
         */
        function isStarredCommentLine(line) {
            return /^\s*\*/u.test(line);
        }

        /**
         * Checks if a comment group is in starred-block form.
         * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment.
         * @returns {boolean} Whether or not the comment group is in starred block form.
         */
        function isStarredBlockComment([firstComment]) {
            if (firstComment.type !== "Block") {
                return false;
            }

            const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER);

            // The first and last lines can only contain whitespace.
            return lines.length > 0 && lines.every((line, i) => (i === 0 || i === lines.length - 1 ? /^\s*$/u : /^\s*\*/u).test(line));
        }

        /**
         * Checks if a comment group is in JSDoc form.
         * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment.
         * @returns {boolean} Whether or not the comment group is in JSDoc form.
         */
        function isJSDocComment([firstComment]) {
            if (firstComment.type !== "Block") {
                return false;
            }

            const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER);

            return /^\*\s*$/u.test(lines[0]) &&
                lines.slice(1, -1).every(line => /^\s* /u.test(line)) &&
                /^\s*$/u.test(lines[lines.length - 1]);
        }

        /**
         * Processes a comment group that is currently in separate-line form, calculating the offset for each line.
         * @param {Token[]} commentGroup A group of comments containing multiple line comments.
         * @returns {string[]} An array of the processed lines.
         */
        function processSeparateLineComments(commentGroup) {
            const allLinesHaveLeadingSpace = commentGroup
                .map(({ value }) => value)
                .filter(line => line.trim().length)
                .every(line => line.startsWith(" "));

            return commentGroup.map(({ value }) => (allLinesHaveLeadingSpace ? value.replace(/^ /u, "") : value));
        }

        /**
         * Processes a comment group that is currently in starred-block form, calculating the offset for each line.
         * @param {Token} comment A single block comment token in starred-block form.
         * @returns {string[]} An array of the processed lines.
         */
        function processStarredBlockComment(comment) {
            const lines = comment.value.split(astUtils.LINEBREAK_MATCHER)
                .filter((line, i, linesArr) => !(i === 0 || i === linesArr.length - 1))
                .map(line => line.replace(/^\s*$/u, ""));
            const allLinesHaveLeadingSpace = lines
                .map(line => line.replace(/\s*\*/u, ""))
                .filter(line => line.trim().length)
                .every(line => line.startsWith(" "));

            return lines.map(line => line.replace(allLinesHaveLeadingSpace ? /\s*\* ?/u : /\s*\*/u, ""));
        }

        /**
         * Processes a comment group that is currently in bare-block form, calculating the offset for each line.
         * @param {Token} comment A single block comment token in bare-block form.
         * @returns {string[]} An array of the processed lines.
         */
        function processBareBlockComment(comment) {
            const lines = comment.value.split(astUtils.LINEBREAK_MATCHER).map(line => line.replace(/^\s*$/u, ""));
            const leadingWhitespace = `${sourceCode.text.slice(comment.range[0] - comment.loc.start.column, comment.range[0])}   `;
            let offset = "";

            /*
             * Calculate the offset of the least indented line and use that as the basis for offsetting all the lines.
             * The first line should not be checked because it is inline with the opening block comment delimiter.
             */
            for (const [i, line] of lines.entries()) {
                if (!line.trim().length || i === 0) {
                    continue;
                }

                const [, lineOffset] = line.match(/^(\s*\*?\s*)/u);

                if (lineOffset.length < leadingWhitespace.length) {
                    const newOffset = leadingWhitespace.slice(lineOffset.length - leadingWhitespace.length);

                    if (newOffset.length > offset.length) {
                        offset = newOffset;
                    }
                }
            }

            return lines.map(line => {
                const match = line.match(/^(\s*\*?\s*)(.*)/u);
                const [, lineOffset, lineContents] = match;

                if (lineOffset.length > leadingWhitespace.length) {
                    return `${lineOffset.slice(leadingWhitespace.length - (offset.length + lineOffset.length))}${lineContents}`;
                }

                if (lineOffset.length < leadingWhitespace.length) {
                    return `${lineOffset.slice(leadingWhitespace.length)}${lineContents}`;
                }

                return lineContents;
            });
        }

        /**
         * Gets a list of comment lines in a group, formatting leading whitespace as necessary.
         * @param {Token[]} commentGroup A group of comments containing either multiple line comments or a single block comment.
         * @returns {string[]} A list of comment lines.
         */
        function getCommentLines(commentGroup) {
            const [firstComment] = commentGroup;

            if (firstComment.type === "Line") {
                return processSeparateLineComments(commentGroup);
            }

            if (isStarredBlockComment(commentGroup)) {
                return processStarredBlockComment(firstComment);
            }

            return processBareBlockComment(firstComment);
        }

        /**
         * Gets the initial offset (whitespace) from the beginning of a line to a given comment token.
         * @param {Token} comment The token to check.
         * @returns {string} The offset from the beginning of a line to the token.
         */
        function getInitialOffset(comment) {
            return sourceCode.text.slice(comment.range[0] - comment.loc.start.column, comment.range[0]);
        }

        /**
         * Converts a comment into starred-block form
         * @param {Token} firstComment The first comment of the group being converted
         * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
         * @returns {string} A representation of the comment value in starred-block form, excluding start and end markers
         */
        function convertToStarredBlock(firstComment, commentLinesList) {
            const initialOffset = getInitialOffset(firstComment);

            return `/*\n${commentLinesList.map(line => `${initialOffset} * ${line}`).join("\n")}\n${initialOffset} */`;
        }

        /**
         * Converts a comment into separate-line form
         * @param {Token} firstComment The first comment of the group being converted
         * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
         * @returns {string} A representation of the comment value in separate-line form
         */
        function convertToSeparateLines(firstComment, commentLinesList) {
            return commentLinesList.map(line => `// ${line}`).join(`\n${getInitialOffset(firstComment)}`);
        }

        /**
         * Converts a comment into bare-block form
         * @param {Token} firstComment The first comment of the group being converted
         * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
         * @returns {string} A representation of the comment value in bare-block form
         */
        function convertToBlock(firstComment, commentLinesList) {
            return `/* ${commentLinesList.join(`\n${getInitialOffset(firstComment)}   `)} */`;
        }

        /**
         * Each method checks a group of comments to see if it's valid according to the given option.
         * @param {Token[]} commentGroup A list of comments that appear together. This will either contain a single
         * block comment or multiple line comments.
         * @returns {void}
         */
        const commentGroupCheckers = {
            "starred-block"(commentGroup) {
                const [firstComment] = commentGroup;
                const commentLines = getCommentLines(commentGroup);

                if (commentLines.some(value => value.includes("*/"))) {
                    return;
                }

                if (commentGroup.length > 1) {
                    context.report({
                        loc: {
                            start: firstComment.loc.start,
                            end: commentGroup[commentGroup.length - 1].loc.end
                        },
                        messageId: "expectedBlock",
                        fix(fixer) {
                            const range = [firstComment.range[0], commentGroup[commentGroup.length - 1].range[1]];

                            return commentLines.some(value => value.startsWith("/"))
                                ? null
                                : fixer.replaceTextRange(range, convertToStarredBlock(firstComment, commentLines));
                        }
                    });
                } else {
                    const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER);
                    const expectedLeadingWhitespace = getInitialOffset(firstComment);
                    const expectedLinePrefix = `${expectedLeadingWhitespace} *`;

                    if (!/^\*?\s*$/u.test(lines[0])) {
                        const start = firstComment.value.startsWith("*") ? firstComment.range[0] + 1 : firstComment.range[0];

                        context.report({
                            loc: {
                                start: firstComment.loc.start,
                                end: { line: firstComment.loc.start.line, column: firstComment.loc.start.column + 2 }
                            },
                            messageId: "startNewline",
                            fix: fixer => fixer.insertTextAfterRange([start, start + 2], `\n${expectedLinePrefix}`)
                        });
                    }

                    if (!/^\s*$/u.test(lines[lines.length - 1])) {
                        context.report({
                            loc: {
                                start: { line: firstComment.loc.end.line, column: firstComment.loc.end.column - 2 },
                                end: firstComment.loc.end
                            },
                            messageId: "endNewline",
                            fix: fixer => fixer.replaceTextRange([firstComment.range[1] - 2, firstComment.range[1]], `\n${expectedLinePrefix}/`)
                        });
                    }

                    for (let lineNumber = firstComment.loc.start.line + 1; lineNumber <= firstComment.loc.end.line; lineNumber++) {
                        const lineText = sourceCode.lines[lineNumber - 1];
                        const errorType = isStarredCommentLine(lineText)
                            ? "alignment"
                            : "missingStar";

                        if (!lineText.startsWith(expectedLinePrefix)) {
                            context.report({
                                loc: {
                                    start: { line: lineNumber, column: 0 },
                                    end: { line: lineNumber, column: lineText.length }
                                },
                                messageId: errorType,
                                fix(fixer) {
                                    const lineStartIndex = sourceCode.getIndexFromLoc({ line: lineNumber, column: 0 });

                                    if (errorType === "alignment") {
                                        const [, commentTextPrefix = ""] = lineText.match(/^(\s*\*)/u) || [];
                                        const commentTextStartIndex = lineStartIndex + commentTextPrefix.length;

                                        return fixer.replaceTextRange([lineStartIndex, commentTextStartIndex], expectedLinePrefix);
                                    }

                                    const [, commentTextPrefix = ""] = lineText.match(/^(\s*)/u) || [];
                                    const commentTextStartIndex = lineStartIndex + commentTextPrefix.length;
                                    let offset;

                                    for (const [idx, line] of lines.entries()) {
                                        if (!/\S+/u.test(line)) {
                                            continue;
                                        }

                                        const lineTextToAlignWith = sourceCode.lines[firstComment.loc.start.line - 1 + idx];
                                        const [, prefix = "", initialOffset = ""] = lineTextToAlignWith.match(/^(\s*(?:\/?\*)?(\s*))/u) || [];

                                        offset = `${commentTextPrefix.slice(prefix.length)}${initialOffset}`;

                                        if (/^\s*\//u.test(lineText) && offset.length === 0) {
                                            offset += " ";
                                        }
                                        break;
                                    }

                                    return fixer.replaceTextRange([lineStartIndex, commentTextStartIndex], `${expectedLinePrefix}${offset}`);
                                }
                            });
                        }
                    }
                }
            },
            "separate-lines"(commentGroup) {
                const [firstComment] = commentGroup;

                if (firstComment.type !== "Block" || isJSDocComment(commentGroup)) {
                    return;
                }

                const commentLines = getCommentLines(commentGroup);
                const tokenAfter = sourceCode.getTokenAfter(firstComment, { includeComments: true });

                if (tokenAfter && firstComment.loc.end.line === tokenAfter.loc.start.line) {
                    return;
                }

                context.report({
                    loc: {
                        start: firstComment.loc.start,
                        end: { line: firstComment.loc.start.line, column: firstComment.loc.start.column + 2 }
                    },
                    messageId: "expectedLines",
                    fix(fixer) {
                        return fixer.replaceText(firstComment, convertToSeparateLines(firstComment, commentLines));
                    }
                });
            },
            "bare-block"(commentGroup) {
                if (isJSDocComment(commentGroup)) {
                    return;
                }

                const [firstComment] = commentGroup;
                const commentLines = getCommentLines(commentGroup);

                // Disallows consecutive line comments in favor of using a block comment.
                if (firstComment.type === "Line" && commentLines.length > 1 &&
                    !commentLines.some(value => value.includes("*/"))) {
                    context.report({
                        loc: {
                            start: firstComment.loc.start,
                            end: commentGroup[commentGroup.length - 1].loc.end
                        },
                        messageId: "expectedBlock",
                        fix(fixer) {
                            return fixer.replaceTextRange(
                                [firstComment.range[0], commentGroup[commentGroup.length - 1].range[1]],
                                convertToBlock(firstComment, commentLines)
                            );
                        }
                    });
                }

                // Prohibits block comments from having a * at the beginning of each line.
                if (isStarredBlockComment(commentGroup)) {
                    context.report({
                        loc: {
                            start: firstComment.loc.start,
                            end: { line: firstComment.loc.start.line, column: firstComment.loc.start.column + 2 }
                        },
                        messageId: "expectedBareBlock",
                        fix(fixer) {
                            return fixer.replaceText(firstComment, convertToBlock(firstComment, commentLines));
                        }
                    });
                }
            }
        };

        //----------------------------------------------------------------------
        // Public
        //----------------------------------------------------------------------

        return {
            Program() {
                return sourceCode.getAllComments()
                    .filter(comment => comment.type !== "Shebang")
                    .filter(comment => !astUtils.COMMENTS_IGNORE_PATTERN.test(comment.value))
                    .filter(comment => {
                        const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true });

                        return !tokenBefore || tokenBefore.loc.end.line < comment.loc.start.line;
                    })
                    .reduce((commentGroups, comment, index, commentList) => {
                        const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true });

                        if (
                            comment.type === "Line" &&
                            index && commentList[index - 1].type === "Line" &&
                            tokenBefore && tokenBefore.loc.end.line === comment.loc.start.line - 1 &&
                            tokenBefore === commentList[index - 1]
                        ) {
                            commentGroups[commentGroups.length - 1].push(comment);
                        } else {
                            commentGroups.push([comment]);
                        }

                        return commentGroups;
                    }, [])
                    .filter(commentGroup => !(commentGroup.length === 1 && commentGroup[0].loc.start.line === commentGroup[0].loc.end.line))
                    .forEach(commentGroupCheckers[option]);
            }
        };
    }
};