padded-blocks.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. }
  55. ]
  56. },
  57. create(context) {
  58. const options = {};
  59. const typeOptions = context.options[0] || "always";
  60. const exceptOptions = context.options[1] || {};
  61. if (typeof typeOptions === "string") {
  62. const shouldHavePadding = typeOptions === "always";
  63. options.blocks = shouldHavePadding;
  64. options.switches = shouldHavePadding;
  65. options.classes = shouldHavePadding;
  66. } else {
  67. if (Object.prototype.hasOwnProperty.call(typeOptions, "blocks")) {
  68. options.blocks = typeOptions.blocks === "always";
  69. }
  70. if (Object.prototype.hasOwnProperty.call(typeOptions, "switches")) {
  71. options.switches = typeOptions.switches === "always";
  72. }
  73. if (Object.prototype.hasOwnProperty.call(typeOptions, "classes")) {
  74. options.classes = typeOptions.classes === "always";
  75. }
  76. }
  77. if (Object.prototype.hasOwnProperty.call(exceptOptions, "allowSingleLineBlocks")) {
  78. options.allowSingleLineBlocks = exceptOptions.allowSingleLineBlocks === true;
  79. }
  80. const ALWAYS_MESSAGE = "Block must be padded by blank lines.",
  81. NEVER_MESSAGE = "Block must not be padded by blank lines.";
  82. const sourceCode = context.getSourceCode();
  83. /**
  84. * Gets the open brace token from a given node.
  85. * @param {ASTNode} node A BlockStatement or SwitchStatement node from which to get the open brace.
  86. * @returns {Token} The token of the open brace.
  87. */
  88. function getOpenBrace(node) {
  89. if (node.type === "SwitchStatement") {
  90. return sourceCode.getTokenBefore(node.cases[0]);
  91. }
  92. return sourceCode.getFirstToken(node);
  93. }
  94. /**
  95. * Checks if the given parameter is a comment node
  96. * @param {ASTNode|Token} node An AST node or token
  97. * @returns {boolean} True if node is a comment
  98. */
  99. function isComment(node) {
  100. return node.type === "Line" || node.type === "Block";
  101. }
  102. /**
  103. * Checks if there is padding between two tokens
  104. * @param {Token} first The first token
  105. * @param {Token} second The second token
  106. * @returns {boolean} True if there is at least a line between the tokens
  107. */
  108. function isPaddingBetweenTokens(first, second) {
  109. return second.loc.start.line - first.loc.end.line >= 2;
  110. }
  111. /**
  112. * Checks if the given token has a blank line after it.
  113. * @param {Token} token The token to check.
  114. * @returns {boolean} Whether or not the token is followed by a blank line.
  115. */
  116. function getFirstBlockToken(token) {
  117. let prev,
  118. first = token;
  119. do {
  120. prev = first;
  121. first = sourceCode.getTokenAfter(first, { includeComments: true });
  122. } while (isComment(first) && first.loc.start.line === prev.loc.end.line);
  123. return first;
  124. }
  125. /**
  126. * Checks if the given token is preceeded by a blank line.
  127. * @param {Token} token The token to check
  128. * @returns {boolean} Whether or not the token is preceeded by a blank line
  129. */
  130. function getLastBlockToken(token) {
  131. let last = token,
  132. next;
  133. do {
  134. next = last;
  135. last = sourceCode.getTokenBefore(last, { includeComments: true });
  136. } while (isComment(last) && last.loc.end.line === next.loc.start.line);
  137. return last;
  138. }
  139. /**
  140. * Checks if a node should be padded, according to the rule config.
  141. * @param {ASTNode} node The AST node to check.
  142. * @returns {boolean} True if the node should be padded, false otherwise.
  143. */
  144. function requirePaddingFor(node) {
  145. switch (node.type) {
  146. case "BlockStatement":
  147. return options.blocks;
  148. case "SwitchStatement":
  149. return options.switches;
  150. case "ClassBody":
  151. return options.classes;
  152. /* istanbul ignore next */
  153. default:
  154. throw new Error("unreachable");
  155. }
  156. }
  157. /**
  158. * Checks the given BlockStatement node to be padded if the block is not empty.
  159. * @param {ASTNode} node The AST node of a BlockStatement.
  160. * @returns {void} undefined.
  161. */
  162. function checkPadding(node) {
  163. const openBrace = getOpenBrace(node),
  164. firstBlockToken = getFirstBlockToken(openBrace),
  165. tokenBeforeFirst = sourceCode.getTokenBefore(firstBlockToken, { includeComments: true }),
  166. closeBrace = sourceCode.getLastToken(node),
  167. lastBlockToken = getLastBlockToken(closeBrace),
  168. tokenAfterLast = sourceCode.getTokenAfter(lastBlockToken, { includeComments: true }),
  169. blockHasTopPadding = isPaddingBetweenTokens(tokenBeforeFirst, firstBlockToken),
  170. blockHasBottomPadding = isPaddingBetweenTokens(lastBlockToken, tokenAfterLast);
  171. if (options.allowSingleLineBlocks && astUtils.isTokenOnSameLine(tokenBeforeFirst, tokenAfterLast)) {
  172. return;
  173. }
  174. if (requirePaddingFor(node)) {
  175. if (!blockHasTopPadding) {
  176. context.report({
  177. node,
  178. loc: { line: tokenBeforeFirst.loc.start.line, column: tokenBeforeFirst.loc.start.column },
  179. fix(fixer) {
  180. return fixer.insertTextAfter(tokenBeforeFirst, "\n");
  181. },
  182. message: ALWAYS_MESSAGE
  183. });
  184. }
  185. if (!blockHasBottomPadding) {
  186. context.report({
  187. node,
  188. loc: { line: tokenAfterLast.loc.end.line, column: tokenAfterLast.loc.end.column - 1 },
  189. fix(fixer) {
  190. return fixer.insertTextBefore(tokenAfterLast, "\n");
  191. },
  192. message: ALWAYS_MESSAGE
  193. });
  194. }
  195. } else {
  196. if (blockHasTopPadding) {
  197. context.report({
  198. node,
  199. loc: { line: tokenBeforeFirst.loc.start.line, column: tokenBeforeFirst.loc.start.column },
  200. fix(fixer) {
  201. return fixer.replaceTextRange([tokenBeforeFirst.range[1], firstBlockToken.range[0] - firstBlockToken.loc.start.column], "\n");
  202. },
  203. message: NEVER_MESSAGE
  204. });
  205. }
  206. if (blockHasBottomPadding) {
  207. context.report({
  208. node,
  209. loc: { line: tokenAfterLast.loc.end.line, column: tokenAfterLast.loc.end.column - 1 },
  210. message: NEVER_MESSAGE,
  211. fix(fixer) {
  212. return fixer.replaceTextRange([lastBlockToken.range[1], tokenAfterLast.range[0] - tokenAfterLast.loc.start.column], "\n");
  213. }
  214. });
  215. }
  216. }
  217. }
  218. const rule = {};
  219. if (Object.prototype.hasOwnProperty.call(options, "switches")) {
  220. rule.SwitchStatement = function(node) {
  221. if (node.cases.length === 0) {
  222. return;
  223. }
  224. checkPadding(node);
  225. };
  226. }
  227. if (Object.prototype.hasOwnProperty.call(options, "blocks")) {
  228. rule.BlockStatement = function(node) {
  229. if (node.body.length === 0) {
  230. return;
  231. }
  232. checkPadding(node);
  233. };
  234. }
  235. if (Object.prototype.hasOwnProperty.call(options, "classes")) {
  236. rule.ClassBody = function(node) {
  237. if (node.body.length === 0) {
  238. return;
  239. }
  240. checkPadding(node);
  241. };
  242. }
  243. return rule;
  244. }
  245. };