padded-blocks.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. module.exports = {
  14. meta: {
  15. type: "layout",
  16. docs: {
  17. description: "require or disallow padding within blocks",
  18. category: "Stylistic Issues",
  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. return sourceCode.getFirstToken(node);
  96. }
  97. /**
  98. * Checks if the given parameter is a comment node
  99. * @param {ASTNode|Token} node An AST node or token
  100. * @returns {boolean} True if node is a comment
  101. */
  102. function isComment(node) {
  103. return node.type === "Line" || node.type === "Block";
  104. }
  105. /**
  106. * Checks if there is padding between two tokens
  107. * @param {Token} first The first token
  108. * @param {Token} second The second token
  109. * @returns {boolean} True if there is at least a line between the tokens
  110. */
  111. function isPaddingBetweenTokens(first, second) {
  112. return second.loc.start.line - first.loc.end.line >= 2;
  113. }
  114. /**
  115. * Checks if the given token has a blank line after it.
  116. * @param {Token} token The token to check.
  117. * @returns {boolean} Whether or not the token is followed by a blank line.
  118. */
  119. function getFirstBlockToken(token) {
  120. let prev,
  121. first = token;
  122. do {
  123. prev = first;
  124. first = sourceCode.getTokenAfter(first, { includeComments: true });
  125. } while (isComment(first) && first.loc.start.line === prev.loc.end.line);
  126. return first;
  127. }
  128. /**
  129. * Checks if the given token is preceded by a blank line.
  130. * @param {Token} token The token to check
  131. * @returns {boolean} Whether or not the token is preceded by a blank line
  132. */
  133. function getLastBlockToken(token) {
  134. let last = token,
  135. next;
  136. do {
  137. next = last;
  138. last = sourceCode.getTokenBefore(last, { includeComments: true });
  139. } while (isComment(last) && last.loc.end.line === next.loc.start.line);
  140. return last;
  141. }
  142. /**
  143. * Checks if a node should be padded, according to the rule config.
  144. * @param {ASTNode} node The AST node to check.
  145. * @returns {boolean} True if the node should be padded, false otherwise.
  146. */
  147. function requirePaddingFor(node) {
  148. switch (node.type) {
  149. case "BlockStatement":
  150. return options.blocks;
  151. case "SwitchStatement":
  152. return options.switches;
  153. case "ClassBody":
  154. return options.classes;
  155. /* istanbul ignore next */
  156. default:
  157. throw new Error("unreachable");
  158. }
  159. }
  160. /**
  161. * Checks the given BlockStatement node to be padded if the block is not empty.
  162. * @param {ASTNode} node The AST node of a BlockStatement.
  163. * @returns {void} undefined.
  164. */
  165. function checkPadding(node) {
  166. const openBrace = getOpenBrace(node),
  167. firstBlockToken = getFirstBlockToken(openBrace),
  168. tokenBeforeFirst = sourceCode.getTokenBefore(firstBlockToken, { includeComments: true }),
  169. closeBrace = sourceCode.getLastToken(node),
  170. lastBlockToken = getLastBlockToken(closeBrace),
  171. tokenAfterLast = sourceCode.getTokenAfter(lastBlockToken, { includeComments: true }),
  172. blockHasTopPadding = isPaddingBetweenTokens(tokenBeforeFirst, firstBlockToken),
  173. blockHasBottomPadding = isPaddingBetweenTokens(lastBlockToken, tokenAfterLast);
  174. if (options.allowSingleLineBlocks && astUtils.isTokenOnSameLine(tokenBeforeFirst, tokenAfterLast)) {
  175. return;
  176. }
  177. if (requirePaddingFor(node)) {
  178. if (!blockHasTopPadding) {
  179. context.report({
  180. node,
  181. loc: {
  182. start: tokenBeforeFirst.loc.start,
  183. end: firstBlockToken.loc.start
  184. },
  185. fix(fixer) {
  186. return fixer.insertTextAfter(tokenBeforeFirst, "\n");
  187. },
  188. messageId: "alwaysPadBlock"
  189. });
  190. }
  191. if (!blockHasBottomPadding) {
  192. context.report({
  193. node,
  194. loc: {
  195. end: tokenAfterLast.loc.start,
  196. start: lastBlockToken.loc.end
  197. },
  198. fix(fixer) {
  199. return fixer.insertTextBefore(tokenAfterLast, "\n");
  200. },
  201. messageId: "alwaysPadBlock"
  202. });
  203. }
  204. } else {
  205. if (blockHasTopPadding) {
  206. context.report({
  207. node,
  208. loc: {
  209. start: tokenBeforeFirst.loc.start,
  210. end: firstBlockToken.loc.start
  211. },
  212. fix(fixer) {
  213. return fixer.replaceTextRange([tokenBeforeFirst.range[1], firstBlockToken.range[0] - firstBlockToken.loc.start.column], "\n");
  214. },
  215. messageId: "neverPadBlock"
  216. });
  217. }
  218. if (blockHasBottomPadding) {
  219. context.report({
  220. node,
  221. loc: {
  222. end: tokenAfterLast.loc.start,
  223. start: lastBlockToken.loc.end
  224. },
  225. messageId: "neverPadBlock",
  226. fix(fixer) {
  227. return fixer.replaceTextRange([lastBlockToken.range[1], tokenAfterLast.range[0] - tokenAfterLast.loc.start.column], "\n");
  228. }
  229. });
  230. }
  231. }
  232. }
  233. const rule = {};
  234. if (Object.prototype.hasOwnProperty.call(options, "switches")) {
  235. rule.SwitchStatement = function(node) {
  236. if (node.cases.length === 0) {
  237. return;
  238. }
  239. checkPadding(node);
  240. };
  241. }
  242. if (Object.prototype.hasOwnProperty.call(options, "blocks")) {
  243. rule.BlockStatement = function(node) {
  244. if (node.body.length === 0) {
  245. return;
  246. }
  247. checkPadding(node);
  248. };
  249. }
  250. if (Object.prototype.hasOwnProperty.call(options, "classes")) {
  251. rule.ClassBody = function(node) {
  252. if (node.body.length === 0) {
  253. return;
  254. }
  255. checkPadding(node);
  256. };
  257. }
  258. return rule;
  259. }
  260. };