lines-around-comment.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. /**
  2. * @fileoverview Enforces empty lines around comments.
  3. * @author Jamund Ferguson
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Helpers
  12. //------------------------------------------------------------------------------
  13. /**
  14. * Return an array with any line numbers that are empty.
  15. * @param {Array} lines An array of each line of the file.
  16. * @returns {Array} An array of line numbers.
  17. */
  18. function getEmptyLineNums(lines) {
  19. const emptyLines = lines.map((line, i) => ({
  20. code: line.trim(),
  21. num: i + 1
  22. })).filter(line => !line.code).map(line => line.num);
  23. return emptyLines;
  24. }
  25. /**
  26. * Return an array with any line numbers that contain comments.
  27. * @param {Array} comments An array of comment tokens.
  28. * @returns {Array} An array of line numbers.
  29. */
  30. function getCommentLineNums(comments) {
  31. const lines = [];
  32. comments.forEach(token => {
  33. const start = token.loc.start.line;
  34. const end = token.loc.end.line;
  35. lines.push(start, end);
  36. });
  37. return lines;
  38. }
  39. //------------------------------------------------------------------------------
  40. // Rule Definition
  41. //------------------------------------------------------------------------------
  42. /** @type {import('../shared/types').Rule} */
  43. module.exports = {
  44. meta: {
  45. type: "layout",
  46. docs: {
  47. description: "Require empty lines around comments",
  48. recommended: false,
  49. url: "https://eslint.org/docs/rules/lines-around-comment"
  50. },
  51. fixable: "whitespace",
  52. schema: [
  53. {
  54. type: "object",
  55. properties: {
  56. beforeBlockComment: {
  57. type: "boolean",
  58. default: true
  59. },
  60. afterBlockComment: {
  61. type: "boolean",
  62. default: false
  63. },
  64. beforeLineComment: {
  65. type: "boolean",
  66. default: false
  67. },
  68. afterLineComment: {
  69. type: "boolean",
  70. default: false
  71. },
  72. allowBlockStart: {
  73. type: "boolean",
  74. default: false
  75. },
  76. allowBlockEnd: {
  77. type: "boolean",
  78. default: false
  79. },
  80. allowClassStart: {
  81. type: "boolean"
  82. },
  83. allowClassEnd: {
  84. type: "boolean"
  85. },
  86. allowObjectStart: {
  87. type: "boolean"
  88. },
  89. allowObjectEnd: {
  90. type: "boolean"
  91. },
  92. allowArrayStart: {
  93. type: "boolean"
  94. },
  95. allowArrayEnd: {
  96. type: "boolean"
  97. },
  98. ignorePattern: {
  99. type: "string"
  100. },
  101. applyDefaultIgnorePatterns: {
  102. type: "boolean"
  103. }
  104. },
  105. additionalProperties: false
  106. }
  107. ],
  108. messages: {
  109. after: "Expected line after comment.",
  110. before: "Expected line before comment."
  111. }
  112. },
  113. create(context) {
  114. const options = Object.assign({}, context.options[0]);
  115. const ignorePattern = options.ignorePattern;
  116. const defaultIgnoreRegExp = astUtils.COMMENTS_IGNORE_PATTERN;
  117. const customIgnoreRegExp = new RegExp(ignorePattern, "u");
  118. const applyDefaultIgnorePatterns = options.applyDefaultIgnorePatterns !== false;
  119. options.beforeBlockComment = typeof options.beforeBlockComment !== "undefined" ? options.beforeBlockComment : true;
  120. const sourceCode = context.getSourceCode();
  121. const lines = sourceCode.lines,
  122. numLines = lines.length + 1,
  123. comments = sourceCode.getAllComments(),
  124. commentLines = getCommentLineNums(comments),
  125. emptyLines = getEmptyLineNums(lines),
  126. commentAndEmptyLines = new Set(commentLines.concat(emptyLines));
  127. /**
  128. * Returns whether or not comments are on lines starting with or ending with code
  129. * @param {token} token The comment token to check.
  130. * @returns {boolean} True if the comment is not alone.
  131. */
  132. function codeAroundComment(token) {
  133. let currentToken = token;
  134. do {
  135. currentToken = sourceCode.getTokenBefore(currentToken, { includeComments: true });
  136. } while (currentToken && astUtils.isCommentToken(currentToken));
  137. if (currentToken && astUtils.isTokenOnSameLine(currentToken, token)) {
  138. return true;
  139. }
  140. currentToken = token;
  141. do {
  142. currentToken = sourceCode.getTokenAfter(currentToken, { includeComments: true });
  143. } while (currentToken && astUtils.isCommentToken(currentToken));
  144. if (currentToken && astUtils.isTokenOnSameLine(token, currentToken)) {
  145. return true;
  146. }
  147. return false;
  148. }
  149. /**
  150. * Returns whether or not comments are inside a node type or not.
  151. * @param {ASTNode} parent The Comment parent node.
  152. * @param {string} nodeType The parent type to check against.
  153. * @returns {boolean} True if the comment is inside nodeType.
  154. */
  155. function isParentNodeType(parent, nodeType) {
  156. return parent.type === nodeType ||
  157. (parent.body && parent.body.type === nodeType) ||
  158. (parent.consequent && parent.consequent.type === nodeType);
  159. }
  160. /**
  161. * Returns the parent node that contains the given token.
  162. * @param {token} token The token to check.
  163. * @returns {ASTNode|null} The parent node that contains the given token.
  164. */
  165. function getParentNodeOfToken(token) {
  166. const node = sourceCode.getNodeByRangeIndex(token.range[0]);
  167. /*
  168. * For the purpose of this rule, the comment token is in a `StaticBlock` node only
  169. * if it's inside the braces of that `StaticBlock` node.
  170. *
  171. * Example where this function returns `null`:
  172. *
  173. * static
  174. * // comment
  175. * {
  176. * }
  177. *
  178. * Example where this function returns `StaticBlock` node:
  179. *
  180. * static
  181. * {
  182. * // comment
  183. * }
  184. *
  185. */
  186. if (node && node.type === "StaticBlock") {
  187. const openingBrace = sourceCode.getFirstToken(node, { skip: 1 }); // skip the `static` token
  188. return token.range[0] >= openingBrace.range[0]
  189. ? node
  190. : null;
  191. }
  192. return node;
  193. }
  194. /**
  195. * Returns whether or not comments are at the parent start or not.
  196. * @param {token} token The Comment token.
  197. * @param {string} nodeType The parent type to check against.
  198. * @returns {boolean} True if the comment is at parent start.
  199. */
  200. function isCommentAtParentStart(token, nodeType) {
  201. const parent = getParentNodeOfToken(token);
  202. if (parent && isParentNodeType(parent, nodeType)) {
  203. let parentStartNodeOrToken = parent;
  204. if (parent.type === "StaticBlock") {
  205. parentStartNodeOrToken = sourceCode.getFirstToken(parent, { skip: 1 }); // opening brace of the static block
  206. } else if (parent.type === "SwitchStatement") {
  207. parentStartNodeOrToken = sourceCode.getTokenAfter(parent.discriminant, {
  208. filter: astUtils.isOpeningBraceToken
  209. }); // opening brace of the switch statement
  210. }
  211. return token.loc.start.line - parentStartNodeOrToken.loc.start.line === 1;
  212. }
  213. return false;
  214. }
  215. /**
  216. * Returns whether or not comments are at the parent end or not.
  217. * @param {token} token The Comment token.
  218. * @param {string} nodeType The parent type to check against.
  219. * @returns {boolean} True if the comment is at parent end.
  220. */
  221. function isCommentAtParentEnd(token, nodeType) {
  222. const parent = getParentNodeOfToken(token);
  223. return !!parent && isParentNodeType(parent, nodeType) &&
  224. parent.loc.end.line - token.loc.end.line === 1;
  225. }
  226. /**
  227. * Returns whether or not comments are at the block start or not.
  228. * @param {token} token The Comment token.
  229. * @returns {boolean} True if the comment is at block start.
  230. */
  231. function isCommentAtBlockStart(token) {
  232. return (
  233. isCommentAtParentStart(token, "ClassBody") ||
  234. isCommentAtParentStart(token, "BlockStatement") ||
  235. isCommentAtParentStart(token, "StaticBlock") ||
  236. isCommentAtParentStart(token, "SwitchCase") ||
  237. isCommentAtParentStart(token, "SwitchStatement")
  238. );
  239. }
  240. /**
  241. * Returns whether or not comments are at the block end or not.
  242. * @param {token} token The Comment token.
  243. * @returns {boolean} True if the comment is at block end.
  244. */
  245. function isCommentAtBlockEnd(token) {
  246. return (
  247. isCommentAtParentEnd(token, "ClassBody") ||
  248. isCommentAtParentEnd(token, "BlockStatement") ||
  249. isCommentAtParentEnd(token, "StaticBlock") ||
  250. isCommentAtParentEnd(token, "SwitchCase") ||
  251. isCommentAtParentEnd(token, "SwitchStatement")
  252. );
  253. }
  254. /**
  255. * Returns whether or not comments are at the class start or not.
  256. * @param {token} token The Comment token.
  257. * @returns {boolean} True if the comment is at class start.
  258. */
  259. function isCommentAtClassStart(token) {
  260. return isCommentAtParentStart(token, "ClassBody");
  261. }
  262. /**
  263. * Returns whether or not comments are at the class end or not.
  264. * @param {token} token The Comment token.
  265. * @returns {boolean} True if the comment is at class end.
  266. */
  267. function isCommentAtClassEnd(token) {
  268. return isCommentAtParentEnd(token, "ClassBody");
  269. }
  270. /**
  271. * Returns whether or not comments are at the object start or not.
  272. * @param {token} token The Comment token.
  273. * @returns {boolean} True if the comment is at object start.
  274. */
  275. function isCommentAtObjectStart(token) {
  276. return isCommentAtParentStart(token, "ObjectExpression") || isCommentAtParentStart(token, "ObjectPattern");
  277. }
  278. /**
  279. * Returns whether or not comments are at the object end or not.
  280. * @param {token} token The Comment token.
  281. * @returns {boolean} True if the comment is at object end.
  282. */
  283. function isCommentAtObjectEnd(token) {
  284. return isCommentAtParentEnd(token, "ObjectExpression") || isCommentAtParentEnd(token, "ObjectPattern");
  285. }
  286. /**
  287. * Returns whether or not comments are at the array start or not.
  288. * @param {token} token The Comment token.
  289. * @returns {boolean} True if the comment is at array start.
  290. */
  291. function isCommentAtArrayStart(token) {
  292. return isCommentAtParentStart(token, "ArrayExpression") || isCommentAtParentStart(token, "ArrayPattern");
  293. }
  294. /**
  295. * Returns whether or not comments are at the array end or not.
  296. * @param {token} token The Comment token.
  297. * @returns {boolean} True if the comment is at array end.
  298. */
  299. function isCommentAtArrayEnd(token) {
  300. return isCommentAtParentEnd(token, "ArrayExpression") || isCommentAtParentEnd(token, "ArrayPattern");
  301. }
  302. /**
  303. * Checks if a comment token has lines around it (ignores inline comments)
  304. * @param {token} token The Comment token.
  305. * @param {Object} opts Options to determine the newline.
  306. * @param {boolean} opts.after Should have a newline after this line.
  307. * @param {boolean} opts.before Should have a newline before this line.
  308. * @returns {void}
  309. */
  310. function checkForEmptyLine(token, opts) {
  311. if (applyDefaultIgnorePatterns && defaultIgnoreRegExp.test(token.value)) {
  312. return;
  313. }
  314. if (ignorePattern && customIgnoreRegExp.test(token.value)) {
  315. return;
  316. }
  317. let after = opts.after,
  318. before = opts.before;
  319. const prevLineNum = token.loc.start.line - 1,
  320. nextLineNum = token.loc.end.line + 1,
  321. commentIsNotAlone = codeAroundComment(token);
  322. const blockStartAllowed = options.allowBlockStart &&
  323. isCommentAtBlockStart(token) &&
  324. !(options.allowClassStart === false &&
  325. isCommentAtClassStart(token)),
  326. blockEndAllowed = options.allowBlockEnd && isCommentAtBlockEnd(token) && !(options.allowClassEnd === false && isCommentAtClassEnd(token)),
  327. classStartAllowed = options.allowClassStart && isCommentAtClassStart(token),
  328. classEndAllowed = options.allowClassEnd && isCommentAtClassEnd(token),
  329. objectStartAllowed = options.allowObjectStart && isCommentAtObjectStart(token),
  330. objectEndAllowed = options.allowObjectEnd && isCommentAtObjectEnd(token),
  331. arrayStartAllowed = options.allowArrayStart && isCommentAtArrayStart(token),
  332. arrayEndAllowed = options.allowArrayEnd && isCommentAtArrayEnd(token);
  333. const exceptionStartAllowed = blockStartAllowed || classStartAllowed || objectStartAllowed || arrayStartAllowed;
  334. const exceptionEndAllowed = blockEndAllowed || classEndAllowed || objectEndAllowed || arrayEndAllowed;
  335. // ignore top of the file and bottom of the file
  336. if (prevLineNum < 1) {
  337. before = false;
  338. }
  339. if (nextLineNum >= numLines) {
  340. after = false;
  341. }
  342. // we ignore all inline comments
  343. if (commentIsNotAlone) {
  344. return;
  345. }
  346. const previousTokenOrComment = sourceCode.getTokenBefore(token, { includeComments: true });
  347. const nextTokenOrComment = sourceCode.getTokenAfter(token, { includeComments: true });
  348. // check for newline before
  349. if (!exceptionStartAllowed && before && !commentAndEmptyLines.has(prevLineNum) &&
  350. !(astUtils.isCommentToken(previousTokenOrComment) && astUtils.isTokenOnSameLine(previousTokenOrComment, token))) {
  351. const lineStart = token.range[0] - token.loc.start.column;
  352. const range = [lineStart, lineStart];
  353. context.report({
  354. node: token,
  355. messageId: "before",
  356. fix(fixer) {
  357. return fixer.insertTextBeforeRange(range, "\n");
  358. }
  359. });
  360. }
  361. // check for newline after
  362. if (!exceptionEndAllowed && after && !commentAndEmptyLines.has(nextLineNum) &&
  363. !(astUtils.isCommentToken(nextTokenOrComment) && astUtils.isTokenOnSameLine(token, nextTokenOrComment))) {
  364. context.report({
  365. node: token,
  366. messageId: "after",
  367. fix(fixer) {
  368. return fixer.insertTextAfter(token, "\n");
  369. }
  370. });
  371. }
  372. }
  373. //--------------------------------------------------------------------------
  374. // Public
  375. //--------------------------------------------------------------------------
  376. return {
  377. Program() {
  378. comments.forEach(token => {
  379. if (token.type === "Line") {
  380. if (options.beforeLineComment || options.afterLineComment) {
  381. checkForEmptyLine(token, {
  382. after: options.afterLineComment,
  383. before: options.beforeLineComment
  384. });
  385. }
  386. } else if (token.type === "Block") {
  387. if (options.beforeBlockComment || options.afterBlockComment) {
  388. checkForEmptyLine(token, {
  389. after: options.afterBlockComment,
  390. before: options.beforeBlockComment
  391. });
  392. }
  393. }
  394. });
  395. }
  396. };
  397. }
  398. };