1 | /**
|
---|
2 | * @fileoverview enforce a particular style for multiline comments
|
---|
3 | * @author Teddy Katz
|
---|
4 | */
|
---|
5 | "use strict";
|
---|
6 |
|
---|
7 | const astUtils = require("./utils/ast-utils");
|
---|
8 |
|
---|
9 | //------------------------------------------------------------------------------
|
---|
10 | // Rule Definition
|
---|
11 | //------------------------------------------------------------------------------
|
---|
12 |
|
---|
13 | /** @type {import('../shared/types').Rule} */
|
---|
14 | module.exports = {
|
---|
15 | meta: {
|
---|
16 | type: "suggestion",
|
---|
17 |
|
---|
18 | docs: {
|
---|
19 | description: "Enforce a particular style for multiline comments",
|
---|
20 | recommended: false,
|
---|
21 | url: "https://eslint.org/docs/latest/rules/multiline-comment-style"
|
---|
22 | },
|
---|
23 |
|
---|
24 | fixable: "whitespace",
|
---|
25 | schema: {
|
---|
26 | anyOf: [
|
---|
27 | {
|
---|
28 | type: "array",
|
---|
29 | items: [
|
---|
30 | {
|
---|
31 | enum: ["starred-block", "bare-block"]
|
---|
32 | }
|
---|
33 | ],
|
---|
34 | additionalItems: false
|
---|
35 | },
|
---|
36 | {
|
---|
37 | type: "array",
|
---|
38 | items: [
|
---|
39 | {
|
---|
40 | enum: ["separate-lines"]
|
---|
41 | },
|
---|
42 | {
|
---|
43 | type: "object",
|
---|
44 | properties: {
|
---|
45 | checkJSDoc: {
|
---|
46 | type: "boolean"
|
---|
47 | }
|
---|
48 | },
|
---|
49 | additionalProperties: false
|
---|
50 | }
|
---|
51 | ],
|
---|
52 | additionalItems: false
|
---|
53 | }
|
---|
54 | ]
|
---|
55 | },
|
---|
56 | messages: {
|
---|
57 | expectedBlock: "Expected a block comment instead of consecutive line comments.",
|
---|
58 | expectedBareBlock: "Expected a block comment without padding stars.",
|
---|
59 | startNewline: "Expected a linebreak after '/*'.",
|
---|
60 | endNewline: "Expected a linebreak before '*/'.",
|
---|
61 | missingStar: "Expected a '*' at the start of this line.",
|
---|
62 | alignment: "Expected this line to be aligned with the start of the comment.",
|
---|
63 | expectedLines: "Expected multiple line comments instead of a block comment."
|
---|
64 | }
|
---|
65 | },
|
---|
66 |
|
---|
67 | create(context) {
|
---|
68 | const sourceCode = context.sourceCode;
|
---|
69 | const option = context.options[0] || "starred-block";
|
---|
70 | const params = context.options[1] || {};
|
---|
71 | const checkJSDoc = !!params.checkJSDoc;
|
---|
72 |
|
---|
73 | //----------------------------------------------------------------------
|
---|
74 | // Helpers
|
---|
75 | //----------------------------------------------------------------------
|
---|
76 |
|
---|
77 | /**
|
---|
78 | * Checks if a comment line is starred.
|
---|
79 | * @param {string} line A string representing a comment line.
|
---|
80 | * @returns {boolean} Whether or not the comment line is starred.
|
---|
81 | */
|
---|
82 | function isStarredCommentLine(line) {
|
---|
83 | return /^\s*\*/u.test(line);
|
---|
84 | }
|
---|
85 |
|
---|
86 | /**
|
---|
87 | * Checks if a comment group is in starred-block form.
|
---|
88 | * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment.
|
---|
89 | * @returns {boolean} Whether or not the comment group is in starred block form.
|
---|
90 | */
|
---|
91 | function isStarredBlockComment([firstComment]) {
|
---|
92 | if (firstComment.type !== "Block") {
|
---|
93 | return false;
|
---|
94 | }
|
---|
95 |
|
---|
96 | const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER);
|
---|
97 |
|
---|
98 | // The first and last lines can only contain whitespace.
|
---|
99 | return lines.length > 0 && lines.every((line, i) => (i === 0 || i === lines.length - 1 ? /^\s*$/u : /^\s*\*/u).test(line));
|
---|
100 | }
|
---|
101 |
|
---|
102 | /**
|
---|
103 | * Checks if a comment group is in JSDoc form.
|
---|
104 | * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment.
|
---|
105 | * @returns {boolean} Whether or not the comment group is in JSDoc form.
|
---|
106 | */
|
---|
107 | function isJSDocComment([firstComment]) {
|
---|
108 | if (firstComment.type !== "Block") {
|
---|
109 | return false;
|
---|
110 | }
|
---|
111 |
|
---|
112 | const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER);
|
---|
113 |
|
---|
114 | return /^\*\s*$/u.test(lines[0]) &&
|
---|
115 | lines.slice(1, -1).every(line => /^\s* /u.test(line)) &&
|
---|
116 | /^\s*$/u.test(lines[lines.length - 1]);
|
---|
117 | }
|
---|
118 |
|
---|
119 | /**
|
---|
120 | * Processes a comment group that is currently in separate-line form, calculating the offset for each line.
|
---|
121 | * @param {Token[]} commentGroup A group of comments containing multiple line comments.
|
---|
122 | * @returns {string[]} An array of the processed lines.
|
---|
123 | */
|
---|
124 | function processSeparateLineComments(commentGroup) {
|
---|
125 | const allLinesHaveLeadingSpace = commentGroup
|
---|
126 | .map(({ value }) => value)
|
---|
127 | .filter(line => line.trim().length)
|
---|
128 | .every(line => line.startsWith(" "));
|
---|
129 |
|
---|
130 | return commentGroup.map(({ value }) => (allLinesHaveLeadingSpace ? value.replace(/^ /u, "") : value));
|
---|
131 | }
|
---|
132 |
|
---|
133 | /**
|
---|
134 | * Processes a comment group that is currently in starred-block form, calculating the offset for each line.
|
---|
135 | * @param {Token} comment A single block comment token in starred-block form.
|
---|
136 | * @returns {string[]} An array of the processed lines.
|
---|
137 | */
|
---|
138 | function processStarredBlockComment(comment) {
|
---|
139 | const lines = comment.value.split(astUtils.LINEBREAK_MATCHER)
|
---|
140 | .filter((line, i, linesArr) => !(i === 0 || i === linesArr.length - 1))
|
---|
141 | .map(line => line.replace(/^\s*$/u, ""));
|
---|
142 | const allLinesHaveLeadingSpace = lines
|
---|
143 | .map(line => line.replace(/\s*\*/u, ""))
|
---|
144 | .filter(line => line.trim().length)
|
---|
145 | .every(line => line.startsWith(" "));
|
---|
146 |
|
---|
147 | return lines.map(line => line.replace(allLinesHaveLeadingSpace ? /\s*\* ?/u : /\s*\*/u, ""));
|
---|
148 | }
|
---|
149 |
|
---|
150 | /**
|
---|
151 | * Processes a comment group that is currently in bare-block form, calculating the offset for each line.
|
---|
152 | * @param {Token} comment A single block comment token in bare-block form.
|
---|
153 | * @returns {string[]} An array of the processed lines.
|
---|
154 | */
|
---|
155 | function processBareBlockComment(comment) {
|
---|
156 | const lines = comment.value.split(astUtils.LINEBREAK_MATCHER).map(line => line.replace(/^\s*$/u, ""));
|
---|
157 | const leadingWhitespace = `${sourceCode.text.slice(comment.range[0] - comment.loc.start.column, comment.range[0])} `;
|
---|
158 | let offset = "";
|
---|
159 |
|
---|
160 | /*
|
---|
161 | * Calculate the offset of the least indented line and use that as the basis for offsetting all the lines.
|
---|
162 | * The first line should not be checked because it is inline with the opening block comment delimiter.
|
---|
163 | */
|
---|
164 | for (const [i, line] of lines.entries()) {
|
---|
165 | if (!line.trim().length || i === 0) {
|
---|
166 | continue;
|
---|
167 | }
|
---|
168 |
|
---|
169 | const [, lineOffset] = line.match(/^(\s*\*?\s*)/u);
|
---|
170 |
|
---|
171 | if (lineOffset.length < leadingWhitespace.length) {
|
---|
172 | const newOffset = leadingWhitespace.slice(lineOffset.length - leadingWhitespace.length);
|
---|
173 |
|
---|
174 | if (newOffset.length > offset.length) {
|
---|
175 | offset = newOffset;
|
---|
176 | }
|
---|
177 | }
|
---|
178 | }
|
---|
179 |
|
---|
180 | return lines.map(line => {
|
---|
181 | const match = line.match(/^(\s*\*?\s*)(.*)/u);
|
---|
182 | const [, lineOffset, lineContents] = match;
|
---|
183 |
|
---|
184 | if (lineOffset.length > leadingWhitespace.length) {
|
---|
185 | return `${lineOffset.slice(leadingWhitespace.length - (offset.length + lineOffset.length))}${lineContents}`;
|
---|
186 | }
|
---|
187 |
|
---|
188 | if (lineOffset.length < leadingWhitespace.length) {
|
---|
189 | return `${lineOffset.slice(leadingWhitespace.length)}${lineContents}`;
|
---|
190 | }
|
---|
191 |
|
---|
192 | return lineContents;
|
---|
193 | });
|
---|
194 | }
|
---|
195 |
|
---|
196 | /**
|
---|
197 | * Gets a list of comment lines in a group, formatting leading whitespace as necessary.
|
---|
198 | * @param {Token[]} commentGroup A group of comments containing either multiple line comments or a single block comment.
|
---|
199 | * @returns {string[]} A list of comment lines.
|
---|
200 | */
|
---|
201 | function getCommentLines(commentGroup) {
|
---|
202 | const [firstComment] = commentGroup;
|
---|
203 |
|
---|
204 | if (firstComment.type === "Line") {
|
---|
205 | return processSeparateLineComments(commentGroup);
|
---|
206 | }
|
---|
207 |
|
---|
208 | if (isStarredBlockComment(commentGroup)) {
|
---|
209 | return processStarredBlockComment(firstComment);
|
---|
210 | }
|
---|
211 |
|
---|
212 | return processBareBlockComment(firstComment);
|
---|
213 | }
|
---|
214 |
|
---|
215 | /**
|
---|
216 | * Gets the initial offset (whitespace) from the beginning of a line to a given comment token.
|
---|
217 | * @param {Token} comment The token to check.
|
---|
218 | * @returns {string} The offset from the beginning of a line to the token.
|
---|
219 | */
|
---|
220 | function getInitialOffset(comment) {
|
---|
221 | return sourceCode.text.slice(comment.range[0] - comment.loc.start.column, comment.range[0]);
|
---|
222 | }
|
---|
223 |
|
---|
224 | /**
|
---|
225 | * Converts a comment into starred-block form
|
---|
226 | * @param {Token} firstComment The first comment of the group being converted
|
---|
227 | * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
|
---|
228 | * @returns {string} A representation of the comment value in starred-block form, excluding start and end markers
|
---|
229 | */
|
---|
230 | function convertToStarredBlock(firstComment, commentLinesList) {
|
---|
231 | const initialOffset = getInitialOffset(firstComment);
|
---|
232 |
|
---|
233 | return `/*\n${commentLinesList.map(line => `${initialOffset} * ${line}`).join("\n")}\n${initialOffset} */`;
|
---|
234 | }
|
---|
235 |
|
---|
236 | /**
|
---|
237 | * Converts a comment into separate-line form
|
---|
238 | * @param {Token} firstComment The first comment of the group being converted
|
---|
239 | * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
|
---|
240 | * @returns {string} A representation of the comment value in separate-line form
|
---|
241 | */
|
---|
242 | function convertToSeparateLines(firstComment, commentLinesList) {
|
---|
243 | return commentLinesList.map(line => `// ${line}`).join(`\n${getInitialOffset(firstComment)}`);
|
---|
244 | }
|
---|
245 |
|
---|
246 | /**
|
---|
247 | * Converts a comment into bare-block form
|
---|
248 | * @param {Token} firstComment The first comment of the group being converted
|
---|
249 | * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
|
---|
250 | * @returns {string} A representation of the comment value in bare-block form
|
---|
251 | */
|
---|
252 | function convertToBlock(firstComment, commentLinesList) {
|
---|
253 | return `/* ${commentLinesList.join(`\n${getInitialOffset(firstComment)} `)} */`;
|
---|
254 | }
|
---|
255 |
|
---|
256 | /**
|
---|
257 | * Each method checks a group of comments to see if it's valid according to the given option.
|
---|
258 | * @param {Token[]} commentGroup A list of comments that appear together. This will either contain a single
|
---|
259 | * block comment or multiple line comments.
|
---|
260 | * @returns {void}
|
---|
261 | */
|
---|
262 | const commentGroupCheckers = {
|
---|
263 | "starred-block"(commentGroup) {
|
---|
264 | const [firstComment] = commentGroup;
|
---|
265 | const commentLines = getCommentLines(commentGroup);
|
---|
266 |
|
---|
267 | if (commentLines.some(value => value.includes("*/"))) {
|
---|
268 | return;
|
---|
269 | }
|
---|
270 |
|
---|
271 | if (commentGroup.length > 1) {
|
---|
272 | context.report({
|
---|
273 | loc: {
|
---|
274 | start: firstComment.loc.start,
|
---|
275 | end: commentGroup[commentGroup.length - 1].loc.end
|
---|
276 | },
|
---|
277 | messageId: "expectedBlock",
|
---|
278 | fix(fixer) {
|
---|
279 | const range = [firstComment.range[0], commentGroup[commentGroup.length - 1].range[1]];
|
---|
280 |
|
---|
281 | return commentLines.some(value => value.startsWith("/"))
|
---|
282 | ? null
|
---|
283 | : fixer.replaceTextRange(range, convertToStarredBlock(firstComment, commentLines));
|
---|
284 | }
|
---|
285 | });
|
---|
286 | } else {
|
---|
287 | const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER);
|
---|
288 | const expectedLeadingWhitespace = getInitialOffset(firstComment);
|
---|
289 | const expectedLinePrefix = `${expectedLeadingWhitespace} *`;
|
---|
290 |
|
---|
291 | if (!/^\*?\s*$/u.test(lines[0])) {
|
---|
292 | const start = firstComment.value.startsWith("*") ? firstComment.range[0] + 1 : firstComment.range[0];
|
---|
293 |
|
---|
294 | context.report({
|
---|
295 | loc: {
|
---|
296 | start: firstComment.loc.start,
|
---|
297 | end: { line: firstComment.loc.start.line, column: firstComment.loc.start.column + 2 }
|
---|
298 | },
|
---|
299 | messageId: "startNewline",
|
---|
300 | fix: fixer => fixer.insertTextAfterRange([start, start + 2], `\n${expectedLinePrefix}`)
|
---|
301 | });
|
---|
302 | }
|
---|
303 |
|
---|
304 | if (!/^\s*$/u.test(lines[lines.length - 1])) {
|
---|
305 | context.report({
|
---|
306 | loc: {
|
---|
307 | start: { line: firstComment.loc.end.line, column: firstComment.loc.end.column - 2 },
|
---|
308 | end: firstComment.loc.end
|
---|
309 | },
|
---|
310 | messageId: "endNewline",
|
---|
311 | fix: fixer => fixer.replaceTextRange([firstComment.range[1] - 2, firstComment.range[1]], `\n${expectedLinePrefix}/`)
|
---|
312 | });
|
---|
313 | }
|
---|
314 |
|
---|
315 | for (let lineNumber = firstComment.loc.start.line + 1; lineNumber <= firstComment.loc.end.line; lineNumber++) {
|
---|
316 | const lineText = sourceCode.lines[lineNumber - 1];
|
---|
317 | const errorType = isStarredCommentLine(lineText)
|
---|
318 | ? "alignment"
|
---|
319 | : "missingStar";
|
---|
320 |
|
---|
321 | if (!lineText.startsWith(expectedLinePrefix)) {
|
---|
322 | context.report({
|
---|
323 | loc: {
|
---|
324 | start: { line: lineNumber, column: 0 },
|
---|
325 | end: { line: lineNumber, column: lineText.length }
|
---|
326 | },
|
---|
327 | messageId: errorType,
|
---|
328 | fix(fixer) {
|
---|
329 | const lineStartIndex = sourceCode.getIndexFromLoc({ line: lineNumber, column: 0 });
|
---|
330 |
|
---|
331 | if (errorType === "alignment") {
|
---|
332 | const [, commentTextPrefix = ""] = lineText.match(/^(\s*\*)/u) || [];
|
---|
333 | const commentTextStartIndex = lineStartIndex + commentTextPrefix.length;
|
---|
334 |
|
---|
335 | return fixer.replaceTextRange([lineStartIndex, commentTextStartIndex], expectedLinePrefix);
|
---|
336 | }
|
---|
337 |
|
---|
338 | const [, commentTextPrefix = ""] = lineText.match(/^(\s*)/u) || [];
|
---|
339 | const commentTextStartIndex = lineStartIndex + commentTextPrefix.length;
|
---|
340 | let offset;
|
---|
341 |
|
---|
342 | for (const [idx, line] of lines.entries()) {
|
---|
343 | if (!/\S+/u.test(line)) {
|
---|
344 | continue;
|
---|
345 | }
|
---|
346 |
|
---|
347 | const lineTextToAlignWith = sourceCode.lines[firstComment.loc.start.line - 1 + idx];
|
---|
348 | const [, prefix = "", initialOffset = ""] = lineTextToAlignWith.match(/^(\s*(?:\/?\*)?(\s*))/u) || [];
|
---|
349 |
|
---|
350 | offset = `${commentTextPrefix.slice(prefix.length)}${initialOffset}`;
|
---|
351 |
|
---|
352 | if (/^\s*\//u.test(lineText) && offset.length === 0) {
|
---|
353 | offset += " ";
|
---|
354 | }
|
---|
355 | break;
|
---|
356 | }
|
---|
357 |
|
---|
358 | return fixer.replaceTextRange([lineStartIndex, commentTextStartIndex], `${expectedLinePrefix}${offset}`);
|
---|
359 | }
|
---|
360 | });
|
---|
361 | }
|
---|
362 | }
|
---|
363 | }
|
---|
364 | },
|
---|
365 | "separate-lines"(commentGroup) {
|
---|
366 | const [firstComment] = commentGroup;
|
---|
367 |
|
---|
368 | const isJSDoc = isJSDocComment(commentGroup);
|
---|
369 |
|
---|
370 | if (firstComment.type !== "Block" || (!checkJSDoc && isJSDoc)) {
|
---|
371 | return;
|
---|
372 | }
|
---|
373 |
|
---|
374 | let commentLines = getCommentLines(commentGroup);
|
---|
375 |
|
---|
376 | if (isJSDoc) {
|
---|
377 | commentLines = commentLines.slice(1, commentLines.length - 1);
|
---|
378 | }
|
---|
379 |
|
---|
380 | const tokenAfter = sourceCode.getTokenAfter(firstComment, { includeComments: true });
|
---|
381 |
|
---|
382 | if (tokenAfter && firstComment.loc.end.line === tokenAfter.loc.start.line) {
|
---|
383 | return;
|
---|
384 | }
|
---|
385 |
|
---|
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: "expectedLines",
|
---|
392 | fix(fixer) {
|
---|
393 | return fixer.replaceText(firstComment, convertToSeparateLines(firstComment, commentLines));
|
---|
394 | }
|
---|
395 | });
|
---|
396 | },
|
---|
397 | "bare-block"(commentGroup) {
|
---|
398 | if (isJSDocComment(commentGroup)) {
|
---|
399 | return;
|
---|
400 | }
|
---|
401 |
|
---|
402 | const [firstComment] = commentGroup;
|
---|
403 | const commentLines = getCommentLines(commentGroup);
|
---|
404 |
|
---|
405 | // Disallows consecutive line comments in favor of using a block comment.
|
---|
406 | if (firstComment.type === "Line" && commentLines.length > 1 &&
|
---|
407 | !commentLines.some(value => value.includes("*/"))) {
|
---|
408 | context.report({
|
---|
409 | loc: {
|
---|
410 | start: firstComment.loc.start,
|
---|
411 | end: commentGroup[commentGroup.length - 1].loc.end
|
---|
412 | },
|
---|
413 | messageId: "expectedBlock",
|
---|
414 | fix(fixer) {
|
---|
415 | return fixer.replaceTextRange(
|
---|
416 | [firstComment.range[0], commentGroup[commentGroup.length - 1].range[1]],
|
---|
417 | convertToBlock(firstComment, commentLines)
|
---|
418 | );
|
---|
419 | }
|
---|
420 | });
|
---|
421 | }
|
---|
422 |
|
---|
423 | // Prohibits block comments from having a * at the beginning of each line.
|
---|
424 | if (isStarredBlockComment(commentGroup)) {
|
---|
425 | context.report({
|
---|
426 | loc: {
|
---|
427 | start: firstComment.loc.start,
|
---|
428 | end: { line: firstComment.loc.start.line, column: firstComment.loc.start.column + 2 }
|
---|
429 | },
|
---|
430 | messageId: "expectedBareBlock",
|
---|
431 | fix(fixer) {
|
---|
432 | return fixer.replaceText(firstComment, convertToBlock(firstComment, commentLines));
|
---|
433 | }
|
---|
434 | });
|
---|
435 | }
|
---|
436 | }
|
---|
437 | };
|
---|
438 |
|
---|
439 | //----------------------------------------------------------------------
|
---|
440 | // Public
|
---|
441 | //----------------------------------------------------------------------
|
---|
442 |
|
---|
443 | return {
|
---|
444 | Program() {
|
---|
445 | return sourceCode.getAllComments()
|
---|
446 | .filter(comment => comment.type !== "Shebang")
|
---|
447 | .filter(comment => !astUtils.COMMENTS_IGNORE_PATTERN.test(comment.value))
|
---|
448 | .filter(comment => {
|
---|
449 | const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
|
---|
450 |
|
---|
451 | return !tokenBefore || tokenBefore.loc.end.line < comment.loc.start.line;
|
---|
452 | })
|
---|
453 | .reduce((commentGroups, comment, index, commentList) => {
|
---|
454 | const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
|
---|
455 |
|
---|
456 | if (
|
---|
457 | comment.type === "Line" &&
|
---|
458 | index && commentList[index - 1].type === "Line" &&
|
---|
459 | tokenBefore && tokenBefore.loc.end.line === comment.loc.start.line - 1 &&
|
---|
460 | tokenBefore === commentList[index - 1]
|
---|
461 | ) {
|
---|
462 | commentGroups[commentGroups.length - 1].push(comment);
|
---|
463 | } else {
|
---|
464 | commentGroups.push([comment]);
|
---|
465 | }
|
---|
466 |
|
---|
467 | return commentGroups;
|
---|
468 | }, [])
|
---|
469 | .filter(commentGroup => !(commentGroup.length === 1 && commentGroup[0].loc.start.line === commentGroup[0].loc.end.line))
|
---|
470 | .forEach(commentGroupCheckers[option]);
|
---|
471 | }
|
---|
472 | };
|
---|
473 | }
|
---|
474 | };
|
---|