padded-blocks.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. /**
  2. * @fileoverview A rule to ensure blank lines within blocks.
  3. * @author Mathias Schreck <https://github.com/lo1tuma>
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Rule Definition
  12. //------------------------------------------------------------------------------
  13. /** @type {import('../shared/types').Rule} */
  14. module.exports = {
  15. meta: {
  16. type: "layout",
  17. docs: {
  18. description: "Require or disallow padding within blocks",
  19. recommended: false,
  20. url: "https://eslint.org/docs/rules/padded-blocks"
  21. },
  22. fixable: "whitespace",
  23. schema: [
  24. {
  25. oneOf: [
  26. {
  27. enum: ["always", "never"]
  28. },
  29. {
  30. type: "object",
  31. properties: {
  32. blocks: {
  33. enum: ["always", "never"]
  34. },
  35. switches: {
  36. enum: ["always", "never"]
  37. },
  38. classes: {
  39. enum: ["always", "never"]
  40. }
  41. },
  42. additionalProperties: false,
  43. minProperties: 1
  44. }
  45. ]
  46. },
  47. {
  48. type: "object",
  49. properties: {
  50. allowSingleLineBlocks: {
  51. type: "boolean"
  52. }
  53. },
  54. additionalProperties: false
  55. }
  56. ],
  57. messages: {
  58. alwaysPadBlock: "Block must be padded by blank lines.",
  59. neverPadBlock: "Block must not be padded by blank lines."
  60. }
  61. },
  62. create(context) {
  63. const options = {};
  64. const typeOptions = context.options[0] || "always";
  65. const exceptOptions = context.options[1] || {};
  66. if (typeof typeOptions === "string") {
  67. const shouldHavePadding = typeOptions === "always";
  68. options.blocks = shouldHavePadding;
  69. options.switches = shouldHavePadding;
  70. options.classes = shouldHavePadding;
  71. } else {
  72. if (Object.prototype.hasOwnProperty.call(typeOptions, "blocks")) {
  73. options.blocks = typeOptions.blocks === "always";
  74. }
  75. if (Object.prototype.hasOwnProperty.call(typeOptions, "switches")) {
  76. options.switches = typeOptions.switches === "always";
  77. }
  78. if (Object.prototype.hasOwnProperty.call(typeOptions, "classes")) {
  79. options.classes = typeOptions.classes === "always";
  80. }
  81. }
  82. if (Object.prototype.hasOwnProperty.call(exceptOptions, "allowSingleLineBlocks")) {
  83. options.allowSingleLineBlocks = exceptOptions.allowSingleLineBlocks === true;
  84. }
  85. const sourceCode = context.getSourceCode();
  86. /**
  87. * Gets the open brace token from a given node.
  88. * @param {ASTNode} node A BlockStatement or SwitchStatement node from which to get the open brace.
  89. * @returns {Token} The token of the open brace.
  90. */
  91. function getOpenBrace(node) {
  92. if (node.type === "SwitchStatement") {
  93. return sourceCode.getTokenBefore(node.cases[0]);
  94. }
  95. if (node.type === "StaticBlock") {
  96. return sourceCode.getFirstToken(node, { skip: 1 }); // skip the `static` token
  97. }
  98. // `BlockStatement` or `ClassBody`
  99. return sourceCode.getFirstToken(node);
  100. }
  101. /**
  102. * Checks if the given parameter is a comment node
  103. * @param {ASTNode|Token} node An AST node or token
  104. * @returns {boolean} True if node is a comment
  105. */
  106. function isComment(node) {
  107. return node.type === "Line" || node.type === "Block";
  108. }
  109. /**
  110. * Checks if there is padding between two tokens
  111. * @param {Token} first The first token
  112. * @param {Token} second The second token
  113. * @returns {boolean} True if there is at least a line between the tokens
  114. */
  115. function isPaddingBetweenTokens(first, second) {
  116. return second.loc.start.line - first.loc.end.line >= 2;
  117. }
  118. /**
  119. * Checks if the given token has a blank line after it.
  120. * @param {Token} token The token to check.
  121. * @returns {boolean} Whether or not the token is followed by a blank line.
  122. */
  123. function getFirstBlockToken(token) {
  124. let prev,
  125. first = token;
  126. do {
  127. prev = first;
  128. first = sourceCode.getTokenAfter(first, { includeComments: true });
  129. } while (isComment(first) && first.loc.start.line === prev.loc.end.line);
  130. return first;
  131. }
  132. /**
  133. * Checks if the given token is preceded by a blank line.
  134. * @param {Token} token The token to check
  135. * @returns {boolean} Whether or not the token is preceded by a blank line
  136. */
  137. function getLastBlockToken(token) {
  138. let last = token,
  139. next;
  140. do {
  141. next = last;
  142. last = sourceCode.getTokenBefore(last, { includeComments: true });
  143. } while (isComment(last) && last.loc.end.line === next.loc.start.line);
  144. return last;
  145. }
  146. /**
  147. * Checks if a node should be padded, according to the rule config.
  148. * @param {ASTNode} node The AST node to check.
  149. * @throws {Error} (Unreachable)
  150. * @returns {boolean} True if the node should be padded, false otherwise.
  151. */
  152. function requirePaddingFor(node) {
  153. switch (node.type) {
  154. case "BlockStatement":
  155. case "StaticBlock":
  156. return options.blocks;
  157. case "SwitchStatement":
  158. return options.switches;
  159. case "ClassBody":
  160. return options.classes;
  161. /* c8 ignore next */
  162. default:
  163. throw new Error("unreachable");
  164. }
  165. }
  166. /**
  167. * Checks the given BlockStatement node to be padded if the block is not empty.
  168. * @param {ASTNode} node The AST node of a BlockStatement.
  169. * @returns {void} undefined.
  170. */
  171. function checkPadding(node) {
  172. const openBrace = getOpenBrace(node),
  173. firstBlockToken = getFirstBlockToken(openBrace),
  174. tokenBeforeFirst = sourceCode.getTokenBefore(firstBlockToken, { includeComments: true }),
  175. closeBrace = sourceCode.getLastToken(node),
  176. lastBlockToken = getLastBlockToken(closeBrace),
  177. tokenAfterLast = sourceCode.getTokenAfter(lastBlockToken, { includeComments: true }),
  178. blockHasTopPadding = isPaddingBetweenTokens(tokenBeforeFirst, firstBlockToken),
  179. blockHasBottomPadding = isPaddingBetweenTokens(lastBlockToken, tokenAfterLast);
  180. if (options.allowSingleLineBlocks && astUtils.isTokenOnSameLine(tokenBeforeFirst, tokenAfterLast)) {
  181. return;
  182. }
  183. if (requirePaddingFor(node)) {
  184. if (!blockHasTopPadding) {
  185. context.report({
  186. node,
  187. loc: {
  188. start: tokenBeforeFirst.loc.start,
  189. end: firstBlockToken.loc.start
  190. },
  191. fix(fixer) {
  192. return fixer.insertTextAfter(tokenBeforeFirst, "\n");
  193. },
  194. messageId: "alwaysPadBlock"
  195. });
  196. }
  197. if (!blockHasBottomPadding) {
  198. context.report({
  199. node,
  200. loc: {
  201. end: tokenAfterLast.loc.start,
  202. start: lastBlockToken.loc.end
  203. },
  204. fix(fixer) {
  205. return fixer.insertTextBefore(tokenAfterLast, "\n");
  206. },
  207. messageId: "alwaysPadBlock"
  208. });
  209. }
  210. } else {
  211. if (blockHasTopPadding) {
  212. context.report({
  213. node,
  214. loc: {
  215. start: tokenBeforeFirst.loc.start,
  216. end: firstBlockToken.loc.start
  217. },
  218. fix(fixer) {
  219. return fixer.replaceTextRange([tokenBeforeFirst.range[1], firstBlockToken.range[0] - firstBlockToken.loc.start.column], "\n");
  220. },
  221. messageId: "neverPadBlock"
  222. });
  223. }
  224. if (blockHasBottomPadding) {
  225. context.report({
  226. node,
  227. loc: {
  228. end: tokenAfterLast.loc.start,
  229. start: lastBlockToken.loc.end
  230. },
  231. messageId: "neverPadBlock",
  232. fix(fixer) {
  233. return fixer.replaceTextRange([lastBlockToken.range[1], tokenAfterLast.range[0] - tokenAfterLast.loc.start.column], "\n");
  234. }
  235. });
  236. }
  237. }
  238. }
  239. const rule = {};
  240. if (Object.prototype.hasOwnProperty.call(options, "switches")) {
  241. rule.SwitchStatement = function(node) {
  242. if (node.cases.length === 0) {
  243. return;
  244. }
  245. checkPadding(node);
  246. };
  247. }
  248. if (Object.prototype.hasOwnProperty.call(options, "blocks")) {
  249. rule.BlockStatement = function(node) {
  250. if (node.body.length === 0) {
  251. return;
  252. }
  253. checkPadding(node);
  254. };
  255. rule.StaticBlock = rule.BlockStatement;
  256. }
  257. if (Object.prototype.hasOwnProperty.call(options, "classes")) {
  258. rule.ClassBody = function(node) {
  259. if (node.body.length === 0) {
  260. return;
  261. }
  262. checkPadding(node);
  263. };
  264. }
  265. return rule;
  266. }
  267. };