UNPKG

14.8 kBJavaScriptView Raw
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 * Gets a list of comment lines in a group
47 * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment
48 * @returns {string[]} A list of comment lines
49 */
50 function getCommentLines(commentGroup) {
51 if (commentGroup[0].type === "Line") {
52 return commentGroup.map(comment => comment.value);
53 }
54 return commentGroup[0].value
55 .split(astUtils.LINEBREAK_MATCHER)
56 .map(line => line.replace(/^\s*\*?/u, ""));
57 }
58
59 /**
60 * Converts a comment into starred-block form
61 * @param {Token} firstComment The first comment of the group being converted
62 * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
63 * @returns {string} A representation of the comment value in starred-block form, excluding start and end markers
64 */
65 function convertToStarredBlock(firstComment, commentLinesList) {
66 const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
67 const starredLines = commentLinesList.map(line => `${initialOffset} *${line}`);
68
69 return `\n${starredLines.join("\n")}\n${initialOffset} `;
70 }
71
72 /**
73 * Converts a comment into separate-line form
74 * @param {Token} firstComment The first comment of the group being converted
75 * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
76 * @returns {string} A representation of the comment value in separate-line form
77 */
78 function convertToSeparateLines(firstComment, commentLinesList) {
79 const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
80 const separateLines = commentLinesList.map(line => `// ${line.trim()}`);
81
82 return separateLines.join(`\n${initialOffset}`);
83 }
84
85 /**
86 * Converts a comment into bare-block form
87 * @param {Token} firstComment The first comment of the group being converted
88 * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
89 * @returns {string} A representation of the comment value in bare-block form
90 */
91 function convertToBlock(firstComment, commentLinesList) {
92 const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
93 const blockLines = commentLinesList.map(line => line.trim());
94
95 return `/* ${blockLines.join(`\n${initialOffset} `)} */`;
96 }
97
98 /**
99 * Check a comment is JSDoc form
100 * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment
101 * @returns {boolean} if commentGroup is JSDoc form, return true
102 */
103 function isJSDoc(commentGroup) {
104 const lines = commentGroup[0].value.split(astUtils.LINEBREAK_MATCHER);
105
106 return commentGroup[0].type === "Block" &&
107 /^\*\s*$/u.test(lines[0]) &&
108 lines.slice(1, -1).every(line => /^\s* /u.test(line)) &&
109 /^\s*$/u.test(lines[lines.length - 1]);
110 }
111
112 /**
113 * Each method checks a group of comments to see if it's valid according to the given option.
114 * @param {Token[]} commentGroup A list of comments that appear together. This will either contain a single
115 * block comment or multiple line comments.
116 * @returns {void}
117 */
118 const commentGroupCheckers = {
119 "starred-block"(commentGroup) {
120 const commentLines = getCommentLines(commentGroup);
121
122 if (commentLines.some(value => value.includes("*/"))) {
123 return;
124 }
125
126 if (commentGroup.length > 1) {
127 context.report({
128 loc: {
129 start: commentGroup[0].loc.start,
130 end: commentGroup[commentGroup.length - 1].loc.end
131 },
132 messageId: "expectedBlock",
133 fix(fixer) {
134 const range = [commentGroup[0].range[0], commentGroup[commentGroup.length - 1].range[1]];
135 const starredBlock = `/*${convertToStarredBlock(commentGroup[0], commentLines)}*/`;
136
137 return commentLines.some(value => value.startsWith("/"))
138 ? null
139 : fixer.replaceTextRange(range, starredBlock);
140 }
141 });
142 } else {
143 const block = commentGroup[0];
144 const lines = block.value.split(astUtils.LINEBREAK_MATCHER);
145 const expectedLinePrefix = `${sourceCode.text.slice(block.range[0] - block.loc.start.column, block.range[0])} *`;
146
147 if (!/^\*?\s*$/u.test(lines[0])) {
148 const start = block.value.startsWith("*") ? block.range[0] + 1 : block.range[0];
149
150 context.report({
151 loc: {
152 start: block.loc.start,
153 end: { line: block.loc.start.line, column: block.loc.start.column + 2 }
154 },
155 messageId: "startNewline",
156 fix: fixer => fixer.insertTextAfterRange([start, start + 2], `\n${expectedLinePrefix}`)
157 });
158 }
159
160 if (!/^\s*$/u.test(lines[lines.length - 1])) {
161 context.report({
162 loc: {
163 start: { line: block.loc.end.line, column: block.loc.end.column - 2 },
164 end: block.loc.end
165 },
166 messageId: "endNewline",
167 fix: fixer => fixer.replaceTextRange([block.range[1] - 2, block.range[1]], `\n${expectedLinePrefix}/`)
168 });
169 }
170
171 for (let lineNumber = block.loc.start.line + 1; lineNumber <= block.loc.end.line; lineNumber++) {
172 const lineText = sourceCode.lines[lineNumber - 1];
173
174 if (!lineText.startsWith(expectedLinePrefix)) {
175 context.report({
176 loc: {
177 start: { line: lineNumber, column: 0 },
178 end: { line: lineNumber, column: sourceCode.lines[lineNumber - 1].length }
179 },
180 messageId: /^\s*\*/u.test(lineText)
181 ? "alignment"
182 : "missingStar",
183 fix(fixer) {
184 const lineStartIndex = sourceCode.getIndexFromLoc({ line: lineNumber, column: 0 });
185 const linePrefixLength = lineText.match(/^\s*\*? ?/u)[0].length;
186 const commentStartIndex = lineStartIndex + linePrefixLength;
187
188 const replacementText = lineNumber === block.loc.end.line || lineText.length === linePrefixLength
189 ? expectedLinePrefix
190 : `${expectedLinePrefix} `;
191
192 return fixer.replaceTextRange([lineStartIndex, commentStartIndex], replacementText);
193 }
194 });
195 }
196 }
197 }
198 },
199 "separate-lines"(commentGroup) {
200 if (!isJSDoc(commentGroup) && commentGroup[0].type === "Block") {
201 const commentLines = getCommentLines(commentGroup);
202 const block = commentGroup[0];
203 const tokenAfter = sourceCode.getTokenAfter(block, { includeComments: true });
204
205 if (tokenAfter && block.loc.end.line === tokenAfter.loc.start.line) {
206 return;
207 }
208
209 context.report({
210 loc: {
211 start: block.loc.start,
212 end: { line: block.loc.start.line, column: block.loc.start.column + 2 }
213 },
214 messageId: "expectedLines",
215 fix(fixer) {
216 return fixer.replaceText(block, convertToSeparateLines(block, commentLines.filter(line => line)));
217 }
218 });
219 }
220 },
221 "bare-block"(commentGroup) {
222 if (!isJSDoc(commentGroup)) {
223 const commentLines = getCommentLines(commentGroup);
224
225 // disallows consecutive line comments in favor of using a block comment.
226 if (commentGroup[0].type === "Line" && commentLines.length > 1 &&
227 !commentLines.some(value => value.includes("*/"))) {
228 context.report({
229 loc: {
230 start: commentGroup[0].loc.start,
231 end: commentGroup[commentGroup.length - 1].loc.end
232 },
233 messageId: "expectedBlock",
234 fix(fixer) {
235 const range = [commentGroup[0].range[0], commentGroup[commentGroup.length - 1].range[1]];
236 const block = convertToBlock(commentGroup[0], commentLines.filter(line => line));
237
238 return fixer.replaceTextRange(range, block);
239 }
240 });
241 }
242
243 // prohibits block comments from having a * at the beginning of each line.
244 if (commentGroup[0].type === "Block") {
245 const block = commentGroup[0];
246 const lines = block.value.split(astUtils.LINEBREAK_MATCHER).filter(line => line.trim());
247
248 if (lines.length > 0 && lines.every(line => /^\s*\*/u.test(line))) {
249 context.report({
250 loc: {
251 start: block.loc.start,
252 end: { line: block.loc.start.line, column: block.loc.start.column + 2 }
253 },
254 messageId: "expectedBareBlock",
255 fix(fixer) {
256 return fixer.replaceText(block, convertToBlock(block, commentLines.filter(line => line)));
257 }
258 });
259 }
260 }
261 }
262 }
263 };
264
265 //----------------------------------------------------------------------
266 // Public
267 //----------------------------------------------------------------------
268
269 return {
270 Program() {
271 return sourceCode.getAllComments()
272 .filter(comment => comment.type !== "Shebang")
273 .filter(comment => !astUtils.COMMENTS_IGNORE_PATTERN.test(comment.value))
274 .filter(comment => {
275 const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
276
277 return !tokenBefore || tokenBefore.loc.end.line < comment.loc.start.line;
278 })
279 .reduce((commentGroups, comment, index, commentList) => {
280 const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
281
282 if (
283 comment.type === "Line" &&
284 index && commentList[index - 1].type === "Line" &&
285 tokenBefore && tokenBefore.loc.end.line === comment.loc.start.line - 1 &&
286 tokenBefore === commentList[index - 1]
287 ) {
288 commentGroups[commentGroups.length - 1].push(comment);
289 } else {
290 commentGroups.push([comment]);
291 }
292
293 return commentGroups;
294 }, [])
295 .filter(commentGroup => !(commentGroup.length === 1 && commentGroup[0].loc.start.line === commentGroup[0].loc.end.line))
296 .forEach(commentGroupCheckers[option]);
297 }
298 };
299 }
300};