spaced-comment.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. /**
  2. * @fileoverview Source code for spaced-comments rule
  3. * @author Gyandeep Singh
  4. */
  5. "use strict";
  6. const lodash = require("lodash");
  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 `(?:${lodash.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. },
  198. create(context) {
  199. const sourceCode = context.getSourceCode();
  200. // Unless the first option is never, require a space
  201. const requireSpace = context.options[0] !== "never";
  202. /*
  203. * Parse the second options.
  204. * If markers don't include `"*"`, it's added automatically for JSDoc
  205. * comments.
  206. */
  207. const config = context.options[1] || {};
  208. const balanced = config.block && config.block.balanced;
  209. const styleRules = ["block", "line"].reduce((rule, type) => {
  210. const markers = parseMarkersOption(config[type] && config[type].markers || config.markers || []);
  211. const exceptions = config[type] && config[type].exceptions || config.exceptions || [];
  212. const endNeverPattern = "[ \t]+$";
  213. // Create RegExp object for valid patterns.
  214. rule[type] = {
  215. beginRegex: requireSpace ? createAlwaysStylePattern(markers, exceptions) : createNeverStylePattern(markers),
  216. endRegex: balanced && requireSpace ? new RegExp(`${createExceptionsPattern(exceptions)}$`, "u") : new RegExp(endNeverPattern, "u"),
  217. hasExceptions: exceptions.length > 0,
  218. captureMarker: new RegExp(`^(${markers.map(escape).join("|")})`, "u"),
  219. markers: new Set(markers)
  220. };
  221. return rule;
  222. }, {});
  223. /**
  224. * Reports a beginning spacing error with an appropriate message.
  225. * @param {ASTNode} node A comment node to check.
  226. * @param {string} message An error message to report.
  227. * @param {Array} match An array of match results for markers.
  228. * @param {string} refChar Character used for reference in the error message.
  229. * @returns {void}
  230. */
  231. function reportBegin(node, message, match, refChar) {
  232. const type = node.type.toLowerCase(),
  233. commentIdentifier = type === "block" ? "/*" : "//";
  234. context.report({
  235. node,
  236. fix(fixer) {
  237. const start = node.range[0];
  238. let end = start + 2;
  239. if (requireSpace) {
  240. if (match) {
  241. end += match[0].length;
  242. }
  243. return fixer.insertTextAfterRange([start, end], " ");
  244. }
  245. end += match[0].length;
  246. return fixer.replaceTextRange([start, end], commentIdentifier + (match[1] ? match[1] : ""));
  247. },
  248. message,
  249. data: { refChar }
  250. });
  251. }
  252. /**
  253. * Reports an ending spacing error with an appropriate message.
  254. * @param {ASTNode} node A comment node to check.
  255. * @param {string} message An error message to report.
  256. * @param {string} match An array of the matched whitespace characters.
  257. * @returns {void}
  258. */
  259. function reportEnd(node, message, match) {
  260. context.report({
  261. node,
  262. fix(fixer) {
  263. if (requireSpace) {
  264. return fixer.insertTextAfterRange([node.range[0], node.range[1] - 2], " ");
  265. }
  266. const end = node.range[1] - 2,
  267. start = end - match[0].length;
  268. return fixer.replaceTextRange([start, end], "");
  269. },
  270. message
  271. });
  272. }
  273. /**
  274. * Reports a given comment if it's invalid.
  275. * @param {ASTNode} node a comment node to check.
  276. * @returns {void}
  277. */
  278. function checkCommentForSpace(node) {
  279. const type = node.type.toLowerCase(),
  280. rule = styleRules[type],
  281. commentIdentifier = type === "block" ? "/*" : "//";
  282. // Ignores empty comments and comments that consist only of a marker.
  283. if (node.value.length === 0 || rule.markers.has(node.value)) {
  284. return;
  285. }
  286. const beginMatch = rule.beginRegex.exec(node.value);
  287. const endMatch = rule.endRegex.exec(node.value);
  288. // Checks.
  289. if (requireSpace) {
  290. if (!beginMatch) {
  291. const hasMarker = rule.captureMarker.exec(node.value);
  292. const marker = hasMarker ? commentIdentifier + hasMarker[0] : commentIdentifier;
  293. if (rule.hasExceptions) {
  294. reportBegin(node, "Expected exception block, space or tab after '{{refChar}}' in comment.", hasMarker, marker);
  295. } else {
  296. reportBegin(node, "Expected space or tab after '{{refChar}}' in comment.", hasMarker, marker);
  297. }
  298. }
  299. if (balanced && type === "block" && !endMatch) {
  300. reportEnd(node, "Expected space or tab before '*/' in comment.");
  301. }
  302. } else {
  303. if (beginMatch) {
  304. if (!beginMatch[1]) {
  305. reportBegin(node, "Unexpected space or tab after '{{refChar}}' in comment.", beginMatch, commentIdentifier);
  306. } else {
  307. reportBegin(node, "Unexpected space or tab after marker ({{refChar}}) in comment.", beginMatch, beginMatch[1]);
  308. }
  309. }
  310. if (balanced && type === "block" && endMatch) {
  311. reportEnd(node, "Unexpected space or tab before '*/' in comment.", endMatch);
  312. }
  313. }
  314. }
  315. return {
  316. Program() {
  317. const comments = sourceCode.getAllComments();
  318. comments.filter(token => token.type !== "Shebang").forEach(checkCommentForSpace);
  319. }
  320. };
  321. }
  322. };