spaced-comment.js 12 KB

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