spaced-comment.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. /**
  2. * @fileoverview Source code for spaced-comments rule
  3. * @author Gyandeep Singh
  4. */
  5. "use strict";
  6. const escapeRegExp = require("escape-string-regexp");
  7. const astUtils = require("./utils/ast-utils");
  8. //------------------------------------------------------------------------------
  9. // Helpers
  10. //------------------------------------------------------------------------------
  11. /**
  12. * Escapes the control characters of a given string.
  13. * @param {string} s A string to escape.
  14. * @returns {string} An escaped string.
  15. */
  16. function escape(s) {
  17. return `(?:${escapeRegExp(s)})`;
  18. }
  19. /**
  20. * Escapes the control characters of a given string.
  21. * And adds a repeat flag.
  22. * @param {string} s A string to escape.
  23. * @returns {string} An escaped string.
  24. */
  25. function escapeAndRepeat(s) {
  26. return `${escape(s)}+`;
  27. }
  28. /**
  29. * Parses `markers` option.
  30. * If markers don't include `"*"`, this adds `"*"` to allow JSDoc comments.
  31. * @param {string[]} [markers] A marker list.
  32. * @returns {string[]} A marker list.
  33. */
  34. function parseMarkersOption(markers) {
  35. // `*` is a marker for JSDoc comments.
  36. if (markers.indexOf("*") === -1) {
  37. return markers.concat("*");
  38. }
  39. return markers;
  40. }
  41. /**
  42. * Creates string pattern for exceptions.
  43. * Generated pattern:
  44. *
  45. * 1. A space or an exception pattern sequence.
  46. * @param {string[]} exceptions An exception pattern list.
  47. * @returns {string} A regular expression string for exceptions.
  48. */
  49. function createExceptionsPattern(exceptions) {
  50. let pattern = "";
  51. /*
  52. * A space or an exception pattern sequence.
  53. * [] ==> "\s"
  54. * ["-"] ==> "(?:\s|\-+$)"
  55. * ["-", "="] ==> "(?:\s|(?:\-+|=+)$)"
  56. * ["-", "=", "--=="] ==> "(?:\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)
  57. */
  58. if (exceptions.length === 0) {
  59. // a space.
  60. pattern += "\\s";
  61. } else {
  62. // a space or...
  63. pattern += "(?:\\s|";
  64. if (exceptions.length === 1) {
  65. // a sequence of the exception pattern.
  66. pattern += escapeAndRepeat(exceptions[0]);
  67. } else {
  68. // a sequence of one of the exception patterns.
  69. pattern += "(?:";
  70. pattern += exceptions.map(escapeAndRepeat).join("|");
  71. pattern += ")";
  72. }
  73. pattern += `(?:$|[${Array.from(astUtils.LINEBREAKS).join("")}]))`;
  74. }
  75. return pattern;
  76. }
  77. /**
  78. * Creates RegExp object for `always` mode.
  79. * Generated pattern for beginning of comment:
  80. *
  81. * 1. First, a marker or nothing.
  82. * 2. Next, a space or an exception pattern sequence.
  83. * @param {string[]} markers A marker list.
  84. * @param {string[]} exceptions An exception pattern list.
  85. * @returns {RegExp} A RegExp object for the beginning of a comment in `always` mode.
  86. */
  87. function createAlwaysStylePattern(markers, exceptions) {
  88. let pattern = "^";
  89. /*
  90. * A marker or nothing.
  91. * ["*"] ==> "\*?"
  92. * ["*", "!"] ==> "(?:\*|!)?"
  93. * ["*", "/", "!<"] ==> "(?:\*|\/|(?:!<))?" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5C*%7C%5C%2F%7C(%3F%3A!%3C))%3F
  94. */
  95. if (markers.length === 1) {
  96. // the marker.
  97. pattern += escape(markers[0]);
  98. } else {
  99. // one of markers.
  100. pattern += "(?:";
  101. pattern += markers.map(escape).join("|");
  102. pattern += ")";
  103. }
  104. pattern += "?"; // or nothing.
  105. pattern += createExceptionsPattern(exceptions);
  106. return new RegExp(pattern, "u");
  107. }
  108. /**
  109. * Creates RegExp object for `never` mode.
  110. * Generated pattern for beginning of comment:
  111. *
  112. * 1. First, a marker or nothing (captured).
  113. * 2. Next, a space or a tab.
  114. * @param {string[]} markers A marker list.
  115. * @returns {RegExp} A RegExp object for `never` mode.
  116. */
  117. function createNeverStylePattern(markers) {
  118. const pattern = `^(${markers.map(escape).join("|")})?[ \t]+`;
  119. return new RegExp(pattern, "u");
  120. }
  121. //------------------------------------------------------------------------------
  122. // Rule Definition
  123. //------------------------------------------------------------------------------
  124. module.exports = {
  125. meta: {
  126. type: "suggestion",
  127. docs: {
  128. description: "enforce consistent spacing after the `//` or `/*` in a comment",
  129. category: "Stylistic Issues",
  130. recommended: false,
  131. url: "https://eslint.org/docs/rules/spaced-comment"
  132. },
  133. fixable: "whitespace",
  134. schema: [
  135. {
  136. enum: ["always", "never"]
  137. },
  138. {
  139. type: "object",
  140. properties: {
  141. exceptions: {
  142. type: "array",
  143. items: {
  144. type: "string"
  145. }
  146. },
  147. markers: {
  148. type: "array",
  149. items: {
  150. type: "string"
  151. }
  152. },
  153. line: {
  154. type: "object",
  155. properties: {
  156. exceptions: {
  157. type: "array",
  158. items: {
  159. type: "string"
  160. }
  161. },
  162. markers: {
  163. type: "array",
  164. items: {
  165. type: "string"
  166. }
  167. }
  168. },
  169. additionalProperties: false
  170. },
  171. block: {
  172. type: "object",
  173. properties: {
  174. exceptions: {
  175. type: "array",
  176. items: {
  177. type: "string"
  178. }
  179. },
  180. markers: {
  181. type: "array",
  182. items: {
  183. type: "string"
  184. }
  185. },
  186. balanced: {
  187. type: "boolean",
  188. default: false
  189. }
  190. },
  191. additionalProperties: false
  192. }
  193. },
  194. additionalProperties: false
  195. }
  196. ],
  197. messages: {
  198. unexpectedSpaceAfterMarker: "Unexpected space or tab after marker ({{refChar}}) in comment.",
  199. expectedExceptionAfter: "Expected exception block, space or tab after '{{refChar}}' in comment.",
  200. unexpectedSpaceBefore: "Unexpected space or tab before '*/' in comment.",
  201. unexpectedSpaceAfter: "Unexpected space or tab after '{{refChar}}' in comment.",
  202. expectedSpaceBefore: "Expected space or tab before '*/' in comment.",
  203. expectedSpaceAfter: "Expected space or tab after '{{refChar}}' in comment."
  204. }
  205. },
  206. create(context) {
  207. const sourceCode = context.getSourceCode();
  208. // Unless the first option is never, require a space
  209. const requireSpace = context.options[0] !== "never";
  210. /*
  211. * Parse the second options.
  212. * If markers don't include `"*"`, it's added automatically for JSDoc
  213. * comments.
  214. */
  215. const config = context.options[1] || {};
  216. const balanced = config.block && config.block.balanced;
  217. const styleRules = ["block", "line"].reduce((rule, type) => {
  218. const markers = parseMarkersOption(config[type] && config[type].markers || config.markers || []);
  219. const exceptions = config[type] && config[type].exceptions || config.exceptions || [];
  220. const endNeverPattern = "[ \t]+$";
  221. // Create RegExp object for valid patterns.
  222. rule[type] = {
  223. beginRegex: requireSpace ? createAlwaysStylePattern(markers, exceptions) : createNeverStylePattern(markers),
  224. endRegex: balanced && requireSpace ? new RegExp(`${createExceptionsPattern(exceptions)}$`, "u") : new RegExp(endNeverPattern, "u"),
  225. hasExceptions: exceptions.length > 0,
  226. captureMarker: new RegExp(`^(${markers.map(escape).join("|")})`, "u"),
  227. markers: new Set(markers)
  228. };
  229. return rule;
  230. }, {});
  231. /**
  232. * Reports a beginning spacing error with an appropriate message.
  233. * @param {ASTNode} node A comment node to check.
  234. * @param {string} messageId An error message to report.
  235. * @param {Array} match An array of match results for markers.
  236. * @param {string} refChar Character used for reference in the error message.
  237. * @returns {void}
  238. */
  239. function reportBegin(node, messageId, match, refChar) {
  240. const type = node.type.toLowerCase(),
  241. commentIdentifier = type === "block" ? "/*" : "//";
  242. context.report({
  243. node,
  244. fix(fixer) {
  245. const start = node.range[0];
  246. let end = start + 2;
  247. if (requireSpace) {
  248. if (match) {
  249. end += match[0].length;
  250. }
  251. return fixer.insertTextAfterRange([start, end], " ");
  252. }
  253. end += match[0].length;
  254. return fixer.replaceTextRange([start, end], commentIdentifier + (match[1] ? match[1] : ""));
  255. },
  256. messageId,
  257. data: { refChar }
  258. });
  259. }
  260. /**
  261. * Reports an ending spacing error with an appropriate message.
  262. * @param {ASTNode} node A comment node to check.
  263. * @param {string} messageId An error message to report.
  264. * @param {string} match An array of the matched whitespace characters.
  265. * @returns {void}
  266. */
  267. function reportEnd(node, messageId, match) {
  268. context.report({
  269. node,
  270. fix(fixer) {
  271. if (requireSpace) {
  272. return fixer.insertTextAfterRange([node.range[0], node.range[1] - 2], " ");
  273. }
  274. const end = node.range[1] - 2,
  275. start = end - match[0].length;
  276. return fixer.replaceTextRange([start, end], "");
  277. },
  278. messageId
  279. });
  280. }
  281. /**
  282. * Reports a given comment if it's invalid.
  283. * @param {ASTNode} node a comment node to check.
  284. * @returns {void}
  285. */
  286. function checkCommentForSpace(node) {
  287. const type = node.type.toLowerCase(),
  288. rule = styleRules[type],
  289. commentIdentifier = type === "block" ? "/*" : "//";
  290. // Ignores empty comments and comments that consist only of a marker.
  291. if (node.value.length === 0 || rule.markers.has(node.value)) {
  292. return;
  293. }
  294. const beginMatch = rule.beginRegex.exec(node.value);
  295. const endMatch = rule.endRegex.exec(node.value);
  296. // Checks.
  297. if (requireSpace) {
  298. if (!beginMatch) {
  299. const hasMarker = rule.captureMarker.exec(node.value);
  300. const marker = hasMarker ? commentIdentifier + hasMarker[0] : commentIdentifier;
  301. if (rule.hasExceptions) {
  302. reportBegin(node, "expectedExceptionAfter", hasMarker, marker);
  303. } else {
  304. reportBegin(node, "expectedSpaceAfter", hasMarker, marker);
  305. }
  306. }
  307. if (balanced && type === "block" && !endMatch) {
  308. reportEnd(node, "expectedSpaceBefore");
  309. }
  310. } else {
  311. if (beginMatch) {
  312. if (!beginMatch[1]) {
  313. reportBegin(node, "unexpectedSpaceAfter", beginMatch, commentIdentifier);
  314. } else {
  315. reportBegin(node, "unexpectedSpaceAfterMarker", beginMatch, beginMatch[1]);
  316. }
  317. }
  318. if (balanced && type === "block" && endMatch) {
  319. reportEnd(node, "unexpectedSpaceBefore", endMatch);
  320. }
  321. }
  322. }
  323. return {
  324. Program() {
  325. const comments = sourceCode.getAllComments();
  326. comments.filter(token => token.type !== "Shebang").forEach(checkCommentForSpace);
  327. }
  328. };
  329. }
  330. };