spaced-comment.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. /**
  2. * @fileoverview Source code for spaced-comments rule
  3. * @author Gyandeep Singh
  4. * @deprecated in ESLint v8.53.0
  5. */
  6. "use strict";
  7. const escapeRegExp = require("escape-string-regexp");
  8. const astUtils = require("./utils/ast-utils");
  9. //------------------------------------------------------------------------------
  10. // Helpers
  11. //------------------------------------------------------------------------------
  12. /**
  13. * Escapes the control characters of a given string.
  14. * @param {string} s A string to escape.
  15. * @returns {string} An escaped string.
  16. */
  17. function escape(s) {
  18. return `(?:${escapeRegExp(s)})`;
  19. }
  20. /**
  21. * Escapes the control characters of a given string.
  22. * And adds a repeat flag.
  23. * @param {string} s A string to escape.
  24. * @returns {string} An escaped string.
  25. */
  26. function escapeAndRepeat(s) {
  27. return `${escape(s)}+`;
  28. }
  29. /**
  30. * Parses `markers` option.
  31. * If markers don't include `"*"`, this adds `"*"` to allow JSDoc comments.
  32. * @param {string[]} [markers] A marker list.
  33. * @returns {string[]} A marker list.
  34. */
  35. function parseMarkersOption(markers) {
  36. // `*` is a marker for JSDoc comments.
  37. if (!markers.includes("*")) {
  38. return markers.concat("*");
  39. }
  40. return markers;
  41. }
  42. /**
  43. * Creates string pattern for exceptions.
  44. * Generated pattern:
  45. *
  46. * 1. A space or an exception pattern sequence.
  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. * @param {string[]} markers A marker list.
  85. * @param {string[]} exceptions An exception pattern list.
  86. * @returns {RegExp} A RegExp object for the beginning of a comment in `always` mode.
  87. */
  88. function createAlwaysStylePattern(markers, exceptions) {
  89. let pattern = "^";
  90. /*
  91. * A marker or nothing.
  92. * ["*"] ==> "\*?"
  93. * ["*", "!"] ==> "(?:\*|!)?"
  94. * ["*", "/", "!<"] ==> "(?:\*|\/|(?:!<))?" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5C*%7C%5C%2F%7C(%3F%3A!%3C))%3F
  95. */
  96. if (markers.length === 1) {
  97. // the marker.
  98. pattern += escape(markers[0]);
  99. } else {
  100. // one of markers.
  101. pattern += "(?:";
  102. pattern += markers.map(escape).join("|");
  103. pattern += ")";
  104. }
  105. pattern += "?"; // or nothing.
  106. pattern += createExceptionsPattern(exceptions);
  107. return new RegExp(pattern, "u");
  108. }
  109. /**
  110. * Creates RegExp object for `never` mode.
  111. * Generated pattern for beginning of comment:
  112. *
  113. * 1. First, a marker or nothing (captured).
  114. * 2. Next, a space or a tab.
  115. * @param {string[]} markers A marker list.
  116. * @returns {RegExp} A RegExp object for `never` mode.
  117. */
  118. function createNeverStylePattern(markers) {
  119. const pattern = `^(${markers.map(escape).join("|")})?[ \t]+`;
  120. return new RegExp(pattern, "u");
  121. }
  122. //------------------------------------------------------------------------------
  123. // Rule Definition
  124. //------------------------------------------------------------------------------
  125. /** @type {import('../types').Rule.RuleModule} */
  126. module.exports = {
  127. meta: {
  128. deprecated: {
  129. message: "Formatting rules are being moved out of ESLint core.",
  130. url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
  131. deprecatedSince: "8.53.0",
  132. availableUntil: "11.0.0",
  133. replacedBy: [
  134. {
  135. message:
  136. "ESLint Stylistic now maintains deprecated stylistic core rules.",
  137. url: "https://eslint.style/guide/migration",
  138. plugin: {
  139. name: "@stylistic/eslint-plugin",
  140. url: "https://eslint.style",
  141. },
  142. rule: {
  143. name: "spaced-comment",
  144. url: "https://eslint.style/rules/spaced-comment",
  145. },
  146. },
  147. ],
  148. },
  149. type: "suggestion",
  150. docs: {
  151. description:
  152. "Enforce consistent spacing after the `//` or `/*` in a comment",
  153. recommended: false,
  154. url: "https://eslint.org/docs/latest/rules/spaced-comment",
  155. },
  156. fixable: "whitespace",
  157. schema: [
  158. {
  159. enum: ["always", "never"],
  160. },
  161. {
  162. type: "object",
  163. properties: {
  164. exceptions: {
  165. type: "array",
  166. items: {
  167. type: "string",
  168. },
  169. },
  170. markers: {
  171. type: "array",
  172. items: {
  173. type: "string",
  174. },
  175. },
  176. line: {
  177. type: "object",
  178. properties: {
  179. exceptions: {
  180. type: "array",
  181. items: {
  182. type: "string",
  183. },
  184. },
  185. markers: {
  186. type: "array",
  187. items: {
  188. type: "string",
  189. },
  190. },
  191. },
  192. additionalProperties: false,
  193. },
  194. block: {
  195. type: "object",
  196. properties: {
  197. exceptions: {
  198. type: "array",
  199. items: {
  200. type: "string",
  201. },
  202. },
  203. markers: {
  204. type: "array",
  205. items: {
  206. type: "string",
  207. },
  208. },
  209. balanced: {
  210. type: "boolean",
  211. default: false,
  212. },
  213. },
  214. additionalProperties: false,
  215. },
  216. },
  217. additionalProperties: false,
  218. },
  219. ],
  220. messages: {
  221. unexpectedSpaceAfterMarker:
  222. "Unexpected space or tab after marker ({{refChar}}) in comment.",
  223. expectedExceptionAfter:
  224. "Expected exception block, space or tab after '{{refChar}}' in comment.",
  225. unexpectedSpaceBefore:
  226. "Unexpected space or tab before '*/' in comment.",
  227. unexpectedSpaceAfter:
  228. "Unexpected space or tab after '{{refChar}}' in comment.",
  229. expectedSpaceBefore:
  230. "Expected space or tab before '*/' in comment.",
  231. expectedSpaceAfter:
  232. "Expected space or tab after '{{refChar}}' in comment.",
  233. },
  234. },
  235. create(context) {
  236. const sourceCode = context.sourceCode;
  237. // Unless the first option is never, require a space
  238. const requireSpace = context.options[0] !== "never";
  239. /*
  240. * Parse the second options.
  241. * If markers don't include `"*"`, it's added automatically for JSDoc
  242. * comments.
  243. */
  244. const config = context.options[1] || {};
  245. const balanced = config.block && config.block.balanced;
  246. const styleRules = ["block", "line"].reduce((rule, type) => {
  247. const markers = parseMarkersOption(
  248. (config[type] && config[type].markers) || config.markers || [],
  249. );
  250. const exceptions =
  251. (config[type] && config[type].exceptions) ||
  252. config.exceptions ||
  253. [];
  254. const endNeverPattern = "[ \t]+$";
  255. // Create RegExp object for valid patterns.
  256. rule[type] = {
  257. beginRegex: requireSpace
  258. ? createAlwaysStylePattern(markers, exceptions)
  259. : createNeverStylePattern(markers),
  260. endRegex:
  261. balanced && requireSpace
  262. ? new RegExp(
  263. `${createExceptionsPattern(exceptions)}$`,
  264. "u",
  265. )
  266. : new RegExp(endNeverPattern, "u"),
  267. hasExceptions: exceptions.length > 0,
  268. captureMarker: new RegExp(
  269. `^(${markers.map(escape).join("|")})`,
  270. "u",
  271. ),
  272. markers: new Set(markers),
  273. };
  274. return rule;
  275. }, {});
  276. /**
  277. * Reports a beginning spacing error with an appropriate message.
  278. * @param {ASTNode} node A comment node to check.
  279. * @param {string} messageId An error message to report.
  280. * @param {Array} match An array of match results for markers.
  281. * @param {string} refChar Character used for reference in the error message.
  282. * @returns {void}
  283. */
  284. function reportBegin(node, messageId, match, refChar) {
  285. const type = node.type.toLowerCase(),
  286. commentIdentifier = type === "block" ? "/*" : "//";
  287. context.report({
  288. node,
  289. fix(fixer) {
  290. const start = node.range[0];
  291. let end = start + 2;
  292. if (requireSpace) {
  293. if (match) {
  294. end += match[0].length;
  295. }
  296. return fixer.insertTextAfterRange([start, end], " ");
  297. }
  298. end += match[0].length;
  299. return fixer.replaceTextRange(
  300. [start, end],
  301. commentIdentifier + (match[1] ? match[1] : ""),
  302. );
  303. },
  304. messageId,
  305. data: { refChar },
  306. });
  307. }
  308. /**
  309. * Reports an ending spacing error with an appropriate message.
  310. * @param {ASTNode} node A comment node to check.
  311. * @param {string} messageId An error message to report.
  312. * @param {string} match An array of the matched whitespace characters.
  313. * @returns {void}
  314. */
  315. function reportEnd(node, messageId, match) {
  316. context.report({
  317. node,
  318. fix(fixer) {
  319. if (requireSpace) {
  320. return fixer.insertTextAfterRange(
  321. [node.range[0], node.range[1] - 2],
  322. " ",
  323. );
  324. }
  325. const end = node.range[1] - 2,
  326. start = end - match[0].length;
  327. return fixer.replaceTextRange([start, end], "");
  328. },
  329. messageId,
  330. });
  331. }
  332. /**
  333. * Reports a given comment if it's invalid.
  334. * @param {ASTNode} node a comment node to check.
  335. * @returns {void}
  336. */
  337. function checkCommentForSpace(node) {
  338. const type = node.type.toLowerCase(),
  339. rule = styleRules[type],
  340. commentIdentifier = type === "block" ? "/*" : "//";
  341. // Ignores empty comments and comments that consist only of a marker.
  342. if (node.value.length === 0 || rule.markers.has(node.value)) {
  343. return;
  344. }
  345. const beginMatch = rule.beginRegex.exec(node.value);
  346. const endMatch = rule.endRegex.exec(node.value);
  347. // Checks.
  348. if (requireSpace) {
  349. if (!beginMatch) {
  350. const hasMarker = rule.captureMarker.exec(node.value);
  351. const marker = hasMarker
  352. ? commentIdentifier + hasMarker[0]
  353. : commentIdentifier;
  354. if (rule.hasExceptions) {
  355. reportBegin(
  356. node,
  357. "expectedExceptionAfter",
  358. hasMarker,
  359. marker,
  360. );
  361. } else {
  362. reportBegin(
  363. node,
  364. "expectedSpaceAfter",
  365. hasMarker,
  366. marker,
  367. );
  368. }
  369. }
  370. if (balanced && type === "block" && !endMatch) {
  371. reportEnd(node, "expectedSpaceBefore");
  372. }
  373. } else {
  374. if (beginMatch) {
  375. if (!beginMatch[1]) {
  376. reportBegin(
  377. node,
  378. "unexpectedSpaceAfter",
  379. beginMatch,
  380. commentIdentifier,
  381. );
  382. } else {
  383. reportBegin(
  384. node,
  385. "unexpectedSpaceAfterMarker",
  386. beginMatch,
  387. beginMatch[1],
  388. );
  389. }
  390. }
  391. if (balanced && type === "block" && endMatch) {
  392. reportEnd(node, "unexpectedSpaceBefore", endMatch);
  393. }
  394. }
  395. }
  396. return {
  397. Program() {
  398. const comments = sourceCode.getAllComments();
  399. comments
  400. .filter(token => token.type !== "Shebang")
  401. .forEach(checkCommentForSpace);
  402. },
  403. };
  404. },
  405. };