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.

multiline-comment-style.js 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. /**
  2. * @fileoverview enforce a particular style for multiline comments
  3. * @author Teddy Katz
  4. */
  5. "use strict";
  6. const astUtils = require("../util/ast-utils");
  7. //------------------------------------------------------------------------------
  8. // Rule Definition
  9. //------------------------------------------------------------------------------
  10. module.exports = {
  11. meta: {
  12. type: "suggestion",
  13. docs: {
  14. description: "enforce a particular style for multiline comments",
  15. category: "Stylistic Issues",
  16. recommended: false,
  17. url: "https://eslint.org/docs/rules/multiline-comment-style"
  18. },
  19. fixable: "whitespace",
  20. schema: [{ enum: ["starred-block", "separate-lines", "bare-block"] }]
  21. },
  22. create(context) {
  23. const sourceCode = context.getSourceCode();
  24. const option = context.options[0] || "starred-block";
  25. const EXPECTED_BLOCK_ERROR = "Expected a block comment instead of consecutive line comments.";
  26. const START_NEWLINE_ERROR = "Expected a linebreak after '/*'.";
  27. const END_NEWLINE_ERROR = "Expected a linebreak before '*/'.";
  28. const MISSING_STAR_ERROR = "Expected a '*' at the start of this line.";
  29. const ALIGNMENT_ERROR = "Expected this line to be aligned with the start of the comment.";
  30. const EXPECTED_LINES_ERROR = "Expected multiple line comments instead of a block comment.";
  31. //----------------------------------------------------------------------
  32. // Helpers
  33. //----------------------------------------------------------------------
  34. /**
  35. * Gets a list of comment lines in a group
  36. * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment
  37. * @returns {string[]} A list of comment lines
  38. */
  39. function getCommentLines(commentGroup) {
  40. if (commentGroup[0].type === "Line") {
  41. return commentGroup.map(comment => comment.value);
  42. }
  43. return commentGroup[0].value
  44. .split(astUtils.LINEBREAK_MATCHER)
  45. .map(line => line.replace(/^\s*\*?/, ""));
  46. }
  47. /**
  48. * Converts a comment into starred-block form
  49. * @param {Token} firstComment The first comment of the group being converted
  50. * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
  51. * @returns {string} A representation of the comment value in starred-block form, excluding start and end markers
  52. */
  53. function convertToStarredBlock(firstComment, commentLinesList) {
  54. const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
  55. const starredLines = commentLinesList.map(line => `${initialOffset} *${line}`);
  56. return `\n${starredLines.join("\n")}\n${initialOffset} `;
  57. }
  58. /**
  59. * Converts a comment into separate-line form
  60. * @param {Token} firstComment The first comment of the group being converted
  61. * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
  62. * @returns {string} A representation of the comment value in separate-line form
  63. */
  64. function convertToSeparateLines(firstComment, commentLinesList) {
  65. const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
  66. const separateLines = commentLinesList.map(line => `// ${line.trim()}`);
  67. return separateLines.join(`\n${initialOffset}`);
  68. }
  69. /**
  70. * Converts a comment into bare-block form
  71. * @param {Token} firstComment The first comment of the group being converted
  72. * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
  73. * @returns {string} A representation of the comment value in bare-block form
  74. */
  75. function convertToBlock(firstComment, commentLinesList) {
  76. const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
  77. const blockLines = commentLinesList.map(line => line.trim());
  78. return `/* ${blockLines.join(`\n${initialOffset} `)} */`;
  79. }
  80. /**
  81. * Check a comment is JSDoc form
  82. * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment
  83. * @returns {boolean} if commentGroup is JSDoc form, return true
  84. */
  85. function isJSDoc(commentGroup) {
  86. const lines = commentGroup[0].value.split(astUtils.LINEBREAK_MATCHER);
  87. return commentGroup[0].type === "Block" &&
  88. /^\*\s*$/.test(lines[0]) &&
  89. lines.slice(1, -1).every(line => /^\s* /.test(line)) &&
  90. /^\s*$/.test(lines[lines.length - 1]);
  91. }
  92. /**
  93. * Each method checks a group of comments to see if it's valid according to the given option.
  94. * @param {Token[]} commentGroup A list of comments that appear together. This will either contain a single
  95. * block comment or multiple line comments.
  96. * @returns {void}
  97. */
  98. const commentGroupCheckers = {
  99. "starred-block"(commentGroup) {
  100. const commentLines = getCommentLines(commentGroup);
  101. if (commentLines.some(value => value.includes("*/"))) {
  102. return;
  103. }
  104. if (commentGroup.length > 1) {
  105. context.report({
  106. loc: {
  107. start: commentGroup[0].loc.start,
  108. end: commentGroup[commentGroup.length - 1].loc.end
  109. },
  110. message: EXPECTED_BLOCK_ERROR,
  111. fix(fixer) {
  112. const range = [commentGroup[0].range[0], commentGroup[commentGroup.length - 1].range[1]];
  113. const starredBlock = `/*${convertToStarredBlock(commentGroup[0], commentLines)}*/`;
  114. return commentLines.some(value => value.startsWith("/"))
  115. ? null
  116. : fixer.replaceTextRange(range, starredBlock);
  117. }
  118. });
  119. } else {
  120. const block = commentGroup[0];
  121. const lines = block.value.split(astUtils.LINEBREAK_MATCHER);
  122. const expectedLinePrefix = `${sourceCode.text.slice(block.range[0] - block.loc.start.column, block.range[0])} *`;
  123. if (!/^\*?\s*$/.test(lines[0])) {
  124. const start = block.value.startsWith("*") ? block.range[0] + 1 : block.range[0];
  125. context.report({
  126. loc: {
  127. start: block.loc.start,
  128. end: { line: block.loc.start.line, column: block.loc.start.column + 2 }
  129. },
  130. message: START_NEWLINE_ERROR,
  131. fix: fixer => fixer.insertTextAfterRange([start, start + 2], `\n${expectedLinePrefix}`)
  132. });
  133. }
  134. if (!/^\s*$/.test(lines[lines.length - 1])) {
  135. context.report({
  136. loc: {
  137. start: { line: block.loc.end.line, column: block.loc.end.column - 2 },
  138. end: block.loc.end
  139. },
  140. message: END_NEWLINE_ERROR,
  141. fix: fixer => fixer.replaceTextRange([block.range[1] - 2, block.range[1]], `\n${expectedLinePrefix}/`)
  142. });
  143. }
  144. for (let lineNumber = block.loc.start.line + 1; lineNumber <= block.loc.end.line; lineNumber++) {
  145. const lineText = sourceCode.lines[lineNumber - 1];
  146. if (!lineText.startsWith(expectedLinePrefix)) {
  147. context.report({
  148. loc: {
  149. start: { line: lineNumber, column: 0 },
  150. end: { line: lineNumber, column: sourceCode.lines[lineNumber - 1].length }
  151. },
  152. message: /^\s*\*/.test(lineText)
  153. ? ALIGNMENT_ERROR
  154. : MISSING_STAR_ERROR,
  155. fix(fixer) {
  156. const lineStartIndex = sourceCode.getIndexFromLoc({ line: lineNumber, column: 0 });
  157. const linePrefixLength = lineText.match(/^\s*\*? ?/)[0].length;
  158. const commentStartIndex = lineStartIndex + linePrefixLength;
  159. const replacementText = lineNumber === block.loc.end.line || lineText.length === linePrefixLength
  160. ? expectedLinePrefix
  161. : `${expectedLinePrefix} `;
  162. return fixer.replaceTextRange([lineStartIndex, commentStartIndex], replacementText);
  163. }
  164. });
  165. }
  166. }
  167. }
  168. },
  169. "separate-lines"(commentGroup) {
  170. if (!isJSDoc(commentGroup) && commentGroup[0].type === "Block") {
  171. const commentLines = getCommentLines(commentGroup);
  172. const block = commentGroup[0];
  173. const tokenAfter = sourceCode.getTokenAfter(block, { includeComments: true });
  174. if (tokenAfter && block.loc.end.line === tokenAfter.loc.start.line) {
  175. return;
  176. }
  177. context.report({
  178. loc: {
  179. start: block.loc.start,
  180. end: { line: block.loc.start.line, column: block.loc.start.column + 2 }
  181. },
  182. message: EXPECTED_LINES_ERROR,
  183. fix(fixer) {
  184. return fixer.replaceText(block, convertToSeparateLines(block, commentLines.filter(line => line)));
  185. }
  186. });
  187. }
  188. },
  189. "bare-block"(commentGroup) {
  190. if (!isJSDoc(commentGroup)) {
  191. const commentLines = getCommentLines(commentGroup);
  192. // disallows consecutive line comments in favor of using a block comment.
  193. if (commentGroup[0].type === "Line" && commentLines.length > 1 &&
  194. !commentLines.some(value => value.includes("*/"))) {
  195. context.report({
  196. loc: {
  197. start: commentGroup[0].loc.start,
  198. end: commentGroup[commentGroup.length - 1].loc.end
  199. },
  200. message: EXPECTED_BLOCK_ERROR,
  201. fix(fixer) {
  202. const range = [commentGroup[0].range[0], commentGroup[commentGroup.length - 1].range[1]];
  203. const block = convertToBlock(commentGroup[0], commentLines.filter(line => line));
  204. return fixer.replaceTextRange(range, block);
  205. }
  206. });
  207. }
  208. // prohibits block comments from having a * at the beginning of each line.
  209. if (commentGroup[0].type === "Block") {
  210. const block = commentGroup[0];
  211. const lines = block.value.split(astUtils.LINEBREAK_MATCHER).filter(line => line.trim());
  212. if (lines.length > 0 && lines.every(line => /^\s*\*/.test(line))) {
  213. context.report({
  214. loc: {
  215. start: block.loc.start,
  216. end: { line: block.loc.start.line, column: block.loc.start.column + 2 }
  217. },
  218. message: EXPECTED_BLOCK_ERROR,
  219. fix(fixer) {
  220. return fixer.replaceText(block, convertToBlock(block, commentLines.filter(line => line)));
  221. }
  222. });
  223. }
  224. }
  225. }
  226. }
  227. };
  228. //----------------------------------------------------------------------
  229. // Public
  230. //----------------------------------------------------------------------
  231. return {
  232. Program() {
  233. return sourceCode.getAllComments()
  234. .filter(comment => comment.type !== "Shebang")
  235. .filter(comment => !astUtils.COMMENTS_IGNORE_PATTERN.test(comment.value))
  236. .filter(comment => {
  237. const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
  238. return !tokenBefore || tokenBefore.loc.end.line < comment.loc.start.line;
  239. })
  240. .reduce((commentGroups, comment, index, commentList) => {
  241. const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
  242. if (
  243. comment.type === "Line" &&
  244. index && commentList[index - 1].type === "Line" &&
  245. tokenBefore && tokenBefore.loc.end.line === comment.loc.start.line - 1 &&
  246. tokenBefore === commentList[index - 1]
  247. ) {
  248. commentGroups[commentGroups.length - 1].push(comment);
  249. } else {
  250. commentGroups.push([comment]);
  251. }
  252. return commentGroups;
  253. }, [])
  254. .filter(commentGroup => !(commentGroup.length === 1 && commentGroup[0].loc.start.line === commentGroup[0].loc.end.line))
  255. .forEach(commentGroupCheckers[option]);
  256. }
  257. };
  258. }
  259. };