UNPKG

14.7 kBJavaScriptView Raw
1/**
2 * @fileoverview enforce a particular style for multiline comments
3 * @author Teddy Katz
4 */
5"use strict";
6
7const astUtils = require("../ast-utils");
8
9//------------------------------------------------------------------------------
10// Rule Definition
11//------------------------------------------------------------------------------
12
13module.exports = {
14 meta: {
15 docs: {
16 description: "enforce a particular style for multiline comments",
17 category: "Stylistic Issues",
18 recommended: false,
19 url: "https://eslint.org/docs/rules/multiline-comment-style"
20 },
21 fixable: "whitespace",
22 schema: [{ enum: ["starred-block", "separate-lines", "bare-block"] }]
23 },
24
25 create(context) {
26 const sourceCode = context.getSourceCode();
27 const option = context.options[0] || "starred-block";
28
29 const EXPECTED_BLOCK_ERROR = "Expected a block comment instead of consecutive line comments.";
30 const START_NEWLINE_ERROR = "Expected a linebreak after '/*'.";
31 const END_NEWLINE_ERROR = "Expected a linebreak before '*/'.";
32 const MISSING_STAR_ERROR = "Expected a '*' at the start of this line.";
33 const ALIGNMENT_ERROR = "Expected this line to be aligned with the start of the comment.";
34 const EXPECTED_LINES_ERROR = "Expected multiple line comments instead of a block comment.";
35
36 //----------------------------------------------------------------------
37 // Helpers
38 //----------------------------------------------------------------------
39
40 /**
41 * Gets a list of comment lines in a group
42 * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment
43 * @returns {string[]} A list of comment lines
44 */
45 function getCommentLines(commentGroup) {
46 if (commentGroup[0].type === "Line") {
47 return commentGroup.map(comment => comment.value);
48 }
49 return commentGroup[0].value
50 .split(astUtils.LINEBREAK_MATCHER)
51 .map(line => line.replace(/^\s*\*?/, ""));
52 }
53
54 /**
55 * Converts a comment into starred-block form
56 * @param {Token} firstComment The first comment of the group being converted
57 * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
58 * @returns {string} A representation of the comment value in starred-block form, excluding start and end markers
59 */
60 function convertToStarredBlock(firstComment, commentLinesList) {
61 const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
62 const starredLines = commentLinesList.map(line => `${initialOffset} *${line}`);
63
64 return `\n${starredLines.join("\n")}\n${initialOffset} `;
65 }
66
67 /**
68 * Converts a comment into separate-line form
69 * @param {Token} firstComment The first comment of the group being converted
70 * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
71 * @returns {string} A representation of the comment value in separate-line form
72 */
73 function convertToSeparateLines(firstComment, commentLinesList) {
74 const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
75 const separateLines = commentLinesList.map(line => `// ${line.trim()}`);
76
77 return separateLines.join(`\n${initialOffset}`);
78 }
79
80 /**
81 * Converts a comment into bare-block form
82 * @param {Token} firstComment The first comment of the group being converted
83 * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
84 * @returns {string} A representation of the comment value in bare-block form
85 */
86 function convertToBlock(firstComment, commentLinesList) {
87 const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
88 const blockLines = commentLinesList.map(line => line.trim());
89
90 return `/* ${blockLines.join(`\n${initialOffset} `)} */`;
91 }
92
93 /**
94 * Check a comment is JSDoc form
95 * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment
96 * @returns {boolean} if commentGroup is JSDoc form, return true
97 */
98 function isJSDoc(commentGroup) {
99 const lines = commentGroup[0].value.split(astUtils.LINEBREAK_MATCHER);
100
101 return commentGroup[0].type === "Block" &&
102 /^\*\s*$/.test(lines[0]) &&
103 lines.slice(1, -1).every(line => /^\s* /.test(line)) &&
104 /^\s*$/.test(lines[lines.length - 1]);
105 }
106
107 /**
108 * Each method checks a group of comments to see if it's valid according to the given option.
109 * @param {Token[]} commentGroup A list of comments that appear together. This will either contain a single
110 * block comment or multiple line comments.
111 * @returns {void}
112 */
113 const commentGroupCheckers = {
114 "starred-block"(commentGroup) {
115 const commentLines = getCommentLines(commentGroup);
116
117 if (commentLines.some(value => value.includes("*/"))) {
118 return;
119 }
120
121 if (commentGroup.length > 1) {
122 context.report({
123 loc: {
124 start: commentGroup[0].loc.start,
125 end: commentGroup[commentGroup.length - 1].loc.end
126 },
127 message: EXPECTED_BLOCK_ERROR,
128 fix(fixer) {
129 const range = [commentGroup[0].range[0], commentGroup[commentGroup.length - 1].range[1]];
130 const starredBlock = `/*${convertToStarredBlock(commentGroup[0], commentLines)}*/`;
131
132 return commentLines.some(value => value.startsWith("/"))
133 ? null
134 : fixer.replaceTextRange(range, starredBlock);
135 }
136 });
137 } else {
138 const block = commentGroup[0];
139 const lines = block.value.split(astUtils.LINEBREAK_MATCHER);
140 const expectedLinePrefix = `${sourceCode.text.slice(block.range[0] - block.loc.start.column, block.range[0])} *`;
141
142 if (!/^\*?\s*$/.test(lines[0])) {
143 const start = block.value.startsWith("*") ? block.range[0] + 1 : block.range[0];
144
145 context.report({
146 loc: {
147 start: block.loc.start,
148 end: { line: block.loc.start.line, column: block.loc.start.column + 2 }
149 },
150 message: START_NEWLINE_ERROR,
151 fix: fixer => fixer.insertTextAfterRange([start, start + 2], `\n${expectedLinePrefix}`)
152 });
153 }
154
155 if (!/^\s*$/.test(lines[lines.length - 1])) {
156 context.report({
157 loc: {
158 start: { line: block.loc.end.line, column: block.loc.end.column - 2 },
159 end: block.loc.end
160 },
161 message: END_NEWLINE_ERROR,
162 fix: fixer => fixer.replaceTextRange([block.range[1] - 2, block.range[1]], `\n${expectedLinePrefix}/`)
163 });
164 }
165
166 for (let lineNumber = block.loc.start.line + 1; lineNumber <= block.loc.end.line; lineNumber++) {
167 const lineText = sourceCode.lines[lineNumber - 1];
168
169 if (!lineText.startsWith(expectedLinePrefix)) {
170 context.report({
171 loc: {
172 start: { line: lineNumber, column: 0 },
173 end: { line: lineNumber, column: sourceCode.lines[lineNumber - 1].length }
174 },
175 message: /^\s*\*/.test(lineText)
176 ? ALIGNMENT_ERROR
177 : MISSING_STAR_ERROR,
178 fix(fixer) {
179 const lineStartIndex = sourceCode.getIndexFromLoc({ line: lineNumber, column: 0 });
180 const linePrefixLength = lineText.match(/^\s*\*? ?/)[0].length;
181 const commentStartIndex = lineStartIndex + linePrefixLength;
182
183 const replacementText = lineNumber === block.loc.end.line || lineText.length === linePrefixLength
184 ? expectedLinePrefix
185 : `${expectedLinePrefix} `;
186
187 return fixer.replaceTextRange([lineStartIndex, commentStartIndex], replacementText);
188 }
189 });
190 }
191 }
192 }
193 },
194 "separate-lines"(commentGroup) {
195 if (!isJSDoc(commentGroup) && commentGroup[0].type === "Block") {
196 const commentLines = getCommentLines(commentGroup);
197 const block = commentGroup[0];
198 const tokenAfter = sourceCode.getTokenAfter(block, { includeComments: true });
199
200 if (tokenAfter && block.loc.end.line === tokenAfter.loc.start.line) {
201 return;
202 }
203
204 context.report({
205 loc: {
206 start: block.loc.start,
207 end: { line: block.loc.start.line, column: block.loc.start.column + 2 }
208 },
209 message: EXPECTED_LINES_ERROR,
210 fix(fixer) {
211 return fixer.replaceText(block, convertToSeparateLines(block, commentLines.filter(line => line)));
212 }
213 });
214 }
215 },
216 "bare-block"(commentGroup) {
217 if (!isJSDoc(commentGroup)) {
218 const commentLines = getCommentLines(commentGroup);
219
220 // disallows consecutive line comments in favor of using a block comment.
221 if (commentGroup[0].type === "Line" && commentLines.length > 1 &&
222 !commentLines.some(value => value.includes("*/"))) {
223 context.report({
224 loc: {
225 start: commentGroup[0].loc.start,
226 end: commentGroup[commentGroup.length - 1].loc.end
227 },
228 message: EXPECTED_BLOCK_ERROR,
229 fix(fixer) {
230 const range = [commentGroup[0].range[0], commentGroup[commentGroup.length - 1].range[1]];
231 const block = convertToBlock(commentGroup[0], commentLines.filter(line => line));
232
233 return fixer.replaceTextRange(range, block);
234 }
235 });
236 }
237
238 // prohibits block comments from having a * at the beginning of each line.
239 if (commentGroup[0].type === "Block") {
240 const block = commentGroup[0];
241 const lines = block.value.split(astUtils.LINEBREAK_MATCHER).filter(line => line.trim());
242
243 if (lines.length > 0 && lines.every(line => /^\s*\*/.test(line))) {
244 context.report({
245 loc: {
246 start: block.loc.start,
247 end: { line: block.loc.start.line, column: block.loc.start.column + 2 }
248 },
249 message: EXPECTED_BLOCK_ERROR,
250 fix(fixer) {
251 return fixer.replaceText(block, convertToBlock(block, commentLines.filter(line => line)));
252 }
253 });
254 }
255 }
256 }
257 }
258 };
259
260 //----------------------------------------------------------------------
261 // Public
262 //----------------------------------------------------------------------
263
264 return {
265 Program() {
266 return sourceCode.getAllComments()
267 .filter(comment => comment.type !== "Shebang")
268 .filter(comment => !astUtils.COMMENTS_IGNORE_PATTERN.test(comment.value))
269 .filter(comment => {
270 const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
271
272 return !tokenBefore || tokenBefore.loc.end.line < comment.loc.start.line;
273 })
274 .reduce((commentGroups, comment, index, commentList) => {
275 const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
276
277 if (
278 comment.type === "Line" &&
279 index && commentList[index - 1].type === "Line" &&
280 tokenBefore && tokenBefore.loc.end.line === comment.loc.start.line - 1 &&
281 tokenBefore === commentList[index - 1]
282 ) {
283 commentGroups[commentGroups.length - 1].push(comment);
284 } else {
285 commentGroups.push([comment]);
286 }
287
288 return commentGroups;
289 }, [])
290 .filter(commentGroup => !(commentGroup.length === 1 && commentGroup[0].loc.start.line === commentGroup[0].loc.end.line))
291 .forEach(commentGroupCheckers[option]);
292 }
293 };
294 }
295};