2 * @fileoverview Source code for spaced-comments rule
3 * @author Gyandeep Singh
7 const lodash = require("lodash");
8 const astUtils = require("./utils/ast-utils");
10 //------------------------------------------------------------------------------
12 //------------------------------------------------------------------------------
15 * Escapes the control characters of a given string.
16 * @param {string} s A string to escape.
17 * @returns {string} An escaped string.
20 return `(?:${lodash.escapeRegExp(s)})`;
24 * Escapes the control characters of a given string.
25 * And adds a repeat flag.
26 * @param {string} s A string to escape.
27 * @returns {string} An escaped string.
29 function escapeAndRepeat(s) {
30 return `${escape(s)}+`;
34 * Parses `markers` option.
35 * If markers don't include `"*"`, this adds `"*"` to allow JSDoc comments.
36 * @param {string[]} [markers] A marker list.
37 * @returns {string[]} A marker list.
39 function parseMarkersOption(markers) {
41 // `*` is a marker for JSDoc comments.
42 if (markers.indexOf("*") === -1) {
43 return markers.concat("*");
50 * Creates string pattern for exceptions.
53 * 1. A space or an exception pattern sequence.
54 * @param {string[]} exceptions An exception pattern list.
55 * @returns {string} A regular expression string for exceptions.
57 function createExceptionsPattern(exceptions) {
61 * A space or an exception pattern sequence.
63 * ["-"] ==> "(?:\s|\-+$)"
64 * ["-", "="] ==> "(?:\s|(?:\-+|=+)$)"
65 * ["-", "=", "--=="] ==> "(?:\s|(?:\-+|=+|(?:\-\-==)+)$)" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5Cs%7C(%3F%3A%5C-%2B%7C%3D%2B%7C(%3F%3A%5C-%5C-%3D%3D)%2B)%24)
67 if (exceptions.length === 0) {
76 if (exceptions.length === 1) {
78 // a sequence of the exception pattern.
79 pattern += escapeAndRepeat(exceptions[0]);
82 // a sequence of one of the exception patterns.
84 pattern += exceptions.map(escapeAndRepeat).join("|");
87 pattern += `(?:$|[${Array.from(astUtils.LINEBREAKS).join("")}]))`;
94 * Creates RegExp object for `always` mode.
95 * Generated pattern for beginning of comment:
97 * 1. First, a marker or nothing.
98 * 2. Next, a space or an exception pattern sequence.
99 * @param {string[]} markers A marker list.
100 * @param {string[]} exceptions An exception pattern list.
101 * @returns {RegExp} A RegExp object for the beginning of a comment in `always` mode.
103 function createAlwaysStylePattern(markers, exceptions) {
107 * A marker or nothing.
109 * ["*", "!"] ==> "(?:\*|!)?"
110 * ["*", "/", "!<"] ==> "(?:\*|\/|(?:!<))?" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5C*%7C%5C%2F%7C(%3F%3A!%3C))%3F
112 if (markers.length === 1) {
115 pattern += escape(markers[0]);
120 pattern += markers.map(escape).join("|");
124 pattern += "?"; // or nothing.
125 pattern += createExceptionsPattern(exceptions);
127 return new RegExp(pattern, "u");
131 * Creates RegExp object for `never` mode.
132 * Generated pattern for beginning of comment:
134 * 1. First, a marker or nothing (captured).
135 * 2. Next, a space or a tab.
136 * @param {string[]} markers A marker list.
137 * @returns {RegExp} A RegExp object for `never` mode.
139 function createNeverStylePattern(markers) {
140 const pattern = `^(${markers.map(escape).join("|")})?[ \t]+`;
142 return new RegExp(pattern, "u");
145 //------------------------------------------------------------------------------
147 //------------------------------------------------------------------------------
154 description: "enforce consistent spacing after the `//` or `/*` in a comment",
155 category: "Stylistic Issues",
157 url: "https://eslint.org/docs/rules/spaced-comment"
160 fixable: "whitespace",
164 enum: ["always", "never"]
197 additionalProperties: false
219 additionalProperties: false
222 additionalProperties: false
229 const sourceCode = context.getSourceCode();
231 // Unless the first option is never, require a space
232 const requireSpace = context.options[0] !== "never";
235 * Parse the second options.
236 * If markers don't include `"*"`, it's added automatically for JSDoc
239 const config = context.options[1] || {};
240 const balanced = config.block && config.block.balanced;
242 const styleRules = ["block", "line"].reduce((rule, type) => {
243 const markers = parseMarkersOption(config[type] && config[type].markers || config.markers || []);
244 const exceptions = config[type] && config[type].exceptions || config.exceptions || [];
245 const endNeverPattern = "[ \t]+$";
247 // Create RegExp object for valid patterns.
249 beginRegex: requireSpace ? createAlwaysStylePattern(markers, exceptions) : createNeverStylePattern(markers),
250 endRegex: balanced && requireSpace ? new RegExp(`${createExceptionsPattern(exceptions)}$`, "u") : new RegExp(endNeverPattern, "u"),
251 hasExceptions: exceptions.length > 0,
252 captureMarker: new RegExp(`^(${markers.map(escape).join("|")})`, "u"),
253 markers: new Set(markers)
260 * Reports a beginning spacing error with an appropriate message.
261 * @param {ASTNode} node A comment node to check.
262 * @param {string} message An error message to report.
263 * @param {Array} match An array of match results for markers.
264 * @param {string} refChar Character used for reference in the error message.
267 function reportBegin(node, message, match, refChar) {
268 const type = node.type.toLowerCase(),
269 commentIdentifier = type === "block" ? "/*" : "//";
274 const start = node.range[0];
279 end += match[0].length;
281 return fixer.insertTextAfterRange([start, end], " ");
283 end += match[0].length;
284 return fixer.replaceTextRange([start, end], commentIdentifier + (match[1] ? match[1] : ""));
293 * Reports an ending spacing error with an appropriate message.
294 * @param {ASTNode} node A comment node to check.
295 * @param {string} message An error message to report.
296 * @param {string} match An array of the matched whitespace characters.
299 function reportEnd(node, message, match) {
304 return fixer.insertTextAfterRange([node.range[0], node.range[1] - 2], " ");
306 const end = node.range[1] - 2,
307 start = end - match[0].length;
309 return fixer.replaceTextRange([start, end], "");
317 * Reports a given comment if it's invalid.
318 * @param {ASTNode} node a comment node to check.
321 function checkCommentForSpace(node) {
322 const type = node.type.toLowerCase(),
323 rule = styleRules[type],
324 commentIdentifier = type === "block" ? "/*" : "//";
326 // Ignores empty comments and comments that consist only of a marker.
327 if (node.value.length === 0 || rule.markers.has(node.value)) {
331 const beginMatch = rule.beginRegex.exec(node.value);
332 const endMatch = rule.endRegex.exec(node.value);
337 const hasMarker = rule.captureMarker.exec(node.value);
338 const marker = hasMarker ? commentIdentifier + hasMarker[0] : commentIdentifier;
340 if (rule.hasExceptions) {
341 reportBegin(node, "Expected exception block, space or tab after '{{refChar}}' in comment.", hasMarker, marker);
343 reportBegin(node, "Expected space or tab after '{{refChar}}' in comment.", hasMarker, marker);
347 if (balanced && type === "block" && !endMatch) {
348 reportEnd(node, "Expected space or tab before '*/' in comment.");
352 if (!beginMatch[1]) {
353 reportBegin(node, "Unexpected space or tab after '{{refChar}}' in comment.", beginMatch, commentIdentifier);
355 reportBegin(node, "Unexpected space or tab after marker ({{refChar}}) in comment.", beginMatch, beginMatch[1]);
359 if (balanced && type === "block" && endMatch) {
360 reportEnd(node, "Unexpected space or tab before '*/' in comment.", endMatch);
367 const comments = sourceCode.getAllComments();
369 comments.filter(token => token.type !== "Shebang").forEach(checkCommentForSpace);