Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

spaced-comment.js 12KB

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