brace-style.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. /**
  2. * @fileoverview Rule to flag block statements that do not use the one true brace style
  3. * @author Ian Christian Myers
  4. * @deprecated in ESLint v8.53.0
  5. */
  6. "use strict";
  7. const astUtils = require("./utils/ast-utils");
  8. //------------------------------------------------------------------------------
  9. // Rule Definition
  10. //------------------------------------------------------------------------------
  11. /** @type {import('../types').Rule.RuleModule} */
  12. module.exports = {
  13. meta: {
  14. deprecated: {
  15. message: "Formatting rules are being moved out of ESLint core.",
  16. url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
  17. deprecatedSince: "8.53.0",
  18. availableUntil: "11.0.0",
  19. replacedBy: [
  20. {
  21. message:
  22. "ESLint Stylistic now maintains deprecated stylistic core rules.",
  23. url: "https://eslint.style/guide/migration",
  24. plugin: {
  25. name: "@stylistic/eslint-plugin",
  26. url: "https://eslint.style",
  27. },
  28. rule: {
  29. name: "brace-style",
  30. url: "https://eslint.style/rules/brace-style",
  31. },
  32. },
  33. ],
  34. },
  35. type: "layout",
  36. docs: {
  37. description: "Enforce consistent brace style for blocks",
  38. recommended: false,
  39. url: "https://eslint.org/docs/latest/rules/brace-style",
  40. },
  41. schema: [
  42. {
  43. enum: ["1tbs", "stroustrup", "allman"],
  44. },
  45. {
  46. type: "object",
  47. properties: {
  48. allowSingleLine: {
  49. type: "boolean",
  50. default: false,
  51. },
  52. },
  53. additionalProperties: false,
  54. },
  55. ],
  56. fixable: "whitespace",
  57. messages: {
  58. nextLineOpen:
  59. "Opening curly brace does not appear on the same line as controlling statement.",
  60. sameLineOpen:
  61. "Opening curly brace appears on the same line as controlling statement.",
  62. blockSameLine:
  63. "Statement inside of curly braces should be on next line.",
  64. nextLineClose:
  65. "Closing curly brace does not appear on the same line as the subsequent block.",
  66. singleLineClose:
  67. "Closing curly brace should be on the same line as opening curly brace or on the line after the previous block.",
  68. sameLineClose:
  69. "Closing curly brace appears on the same line as the subsequent block.",
  70. },
  71. },
  72. create(context) {
  73. const style = context.options[0] || "1tbs",
  74. params = context.options[1] || {},
  75. sourceCode = context.sourceCode;
  76. //--------------------------------------------------------------------------
  77. // Helpers
  78. //--------------------------------------------------------------------------
  79. /**
  80. * Fixes a place where a newline unexpectedly appears
  81. * @param {Token} firstToken The token before the unexpected newline
  82. * @param {Token} secondToken The token after the unexpected newline
  83. * @returns {Function} A fixer function to remove the newlines between the tokens
  84. */
  85. function removeNewlineBetween(firstToken, secondToken) {
  86. const textRange = [firstToken.range[1], secondToken.range[0]];
  87. const textBetween = sourceCode.text.slice(
  88. textRange[0],
  89. textRange[1],
  90. );
  91. // Don't do a fix if there is a comment between the tokens
  92. if (textBetween.trim()) {
  93. return null;
  94. }
  95. return fixer => fixer.replaceTextRange(textRange, " ");
  96. }
  97. /**
  98. * Validates a pair of curly brackets based on the user's config
  99. * @param {Token} openingCurly The opening curly bracket
  100. * @param {Token} closingCurly The closing curly bracket
  101. * @returns {void}
  102. */
  103. function validateCurlyPair(openingCurly, closingCurly) {
  104. const tokenBeforeOpeningCurly =
  105. sourceCode.getTokenBefore(openingCurly);
  106. const tokenAfterOpeningCurly =
  107. sourceCode.getTokenAfter(openingCurly);
  108. const tokenBeforeClosingCurly =
  109. sourceCode.getTokenBefore(closingCurly);
  110. const singleLineException =
  111. params.allowSingleLine &&
  112. astUtils.isTokenOnSameLine(openingCurly, closingCurly);
  113. if (
  114. style !== "allman" &&
  115. !astUtils.isTokenOnSameLine(
  116. tokenBeforeOpeningCurly,
  117. openingCurly,
  118. )
  119. ) {
  120. context.report({
  121. node: openingCurly,
  122. messageId: "nextLineOpen",
  123. fix: removeNewlineBetween(
  124. tokenBeforeOpeningCurly,
  125. openingCurly,
  126. ),
  127. });
  128. }
  129. if (
  130. style === "allman" &&
  131. astUtils.isTokenOnSameLine(
  132. tokenBeforeOpeningCurly,
  133. openingCurly,
  134. ) &&
  135. !singleLineException
  136. ) {
  137. context.report({
  138. node: openingCurly,
  139. messageId: "sameLineOpen",
  140. fix: fixer => fixer.insertTextBefore(openingCurly, "\n"),
  141. });
  142. }
  143. if (
  144. astUtils.isTokenOnSameLine(
  145. openingCurly,
  146. tokenAfterOpeningCurly,
  147. ) &&
  148. tokenAfterOpeningCurly !== closingCurly &&
  149. !singleLineException
  150. ) {
  151. context.report({
  152. node: openingCurly,
  153. messageId: "blockSameLine",
  154. fix: fixer => fixer.insertTextAfter(openingCurly, "\n"),
  155. });
  156. }
  157. if (
  158. tokenBeforeClosingCurly !== openingCurly &&
  159. !singleLineException &&
  160. astUtils.isTokenOnSameLine(
  161. tokenBeforeClosingCurly,
  162. closingCurly,
  163. )
  164. ) {
  165. context.report({
  166. node: closingCurly,
  167. messageId: "singleLineClose",
  168. fix: fixer => fixer.insertTextBefore(closingCurly, "\n"),
  169. });
  170. }
  171. }
  172. /**
  173. * Validates the location of a token that appears before a keyword (e.g. a newline before `else`)
  174. * @param {Token} curlyToken The closing curly token. This is assumed to precede a keyword token (such as `else` or `finally`).
  175. * @returns {void}
  176. */
  177. function validateCurlyBeforeKeyword(curlyToken) {
  178. const keywordToken = sourceCode.getTokenAfter(curlyToken);
  179. if (
  180. style === "1tbs" &&
  181. !astUtils.isTokenOnSameLine(curlyToken, keywordToken)
  182. ) {
  183. context.report({
  184. node: curlyToken,
  185. messageId: "nextLineClose",
  186. fix: removeNewlineBetween(curlyToken, keywordToken),
  187. });
  188. }
  189. if (
  190. style !== "1tbs" &&
  191. astUtils.isTokenOnSameLine(curlyToken, keywordToken)
  192. ) {
  193. context.report({
  194. node: curlyToken,
  195. messageId: "sameLineClose",
  196. fix: fixer => fixer.insertTextAfter(curlyToken, "\n"),
  197. });
  198. }
  199. }
  200. //--------------------------------------------------------------------------
  201. // Public API
  202. //--------------------------------------------------------------------------
  203. return {
  204. BlockStatement(node) {
  205. if (!astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)) {
  206. validateCurlyPair(
  207. sourceCode.getFirstToken(node),
  208. sourceCode.getLastToken(node),
  209. );
  210. }
  211. },
  212. StaticBlock(node) {
  213. validateCurlyPair(
  214. sourceCode.getFirstToken(node, { skip: 1 }), // skip the `static` token
  215. sourceCode.getLastToken(node),
  216. );
  217. },
  218. ClassBody(node) {
  219. validateCurlyPair(
  220. sourceCode.getFirstToken(node),
  221. sourceCode.getLastToken(node),
  222. );
  223. },
  224. SwitchStatement(node) {
  225. const closingCurly = sourceCode.getLastToken(node);
  226. const openingCurly = sourceCode.getTokenBefore(
  227. node.cases.length ? node.cases[0] : closingCurly,
  228. );
  229. validateCurlyPair(openingCurly, closingCurly);
  230. },
  231. IfStatement(node) {
  232. if (
  233. node.consequent.type === "BlockStatement" &&
  234. node.alternate
  235. ) {
  236. // Handle the keyword after the `if` block (before `else`)
  237. validateCurlyBeforeKeyword(
  238. sourceCode.getLastToken(node.consequent),
  239. );
  240. }
  241. },
  242. TryStatement(node) {
  243. // Handle the keyword after the `try` block (before `catch` or `finally`)
  244. validateCurlyBeforeKeyword(sourceCode.getLastToken(node.block));
  245. if (node.handler && node.finalizer) {
  246. // Handle the keyword after the `catch` block (before `finally`)
  247. validateCurlyBeforeKeyword(
  248. sourceCode.getLastToken(node.handler.body),
  249. );
  250. }
  251. },
  252. };
  253. },
  254. };