curly.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. /**
  2. * @fileoverview Rule to flag statements without curly braces
  3. * @author Nicholas C. Zakas
  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: "suggestion",
  17. docs: {
  18. description: "Enforce consistent brace style for all control statements",
  19. recommended: false,
  20. url: "https://eslint.org/docs/rules/curly"
  21. },
  22. schema: {
  23. anyOf: [
  24. {
  25. type: "array",
  26. items: [
  27. {
  28. enum: ["all"]
  29. }
  30. ],
  31. minItems: 0,
  32. maxItems: 1
  33. },
  34. {
  35. type: "array",
  36. items: [
  37. {
  38. enum: ["multi", "multi-line", "multi-or-nest"]
  39. },
  40. {
  41. enum: ["consistent"]
  42. }
  43. ],
  44. minItems: 0,
  45. maxItems: 2
  46. }
  47. ]
  48. },
  49. fixable: "code",
  50. messages: {
  51. missingCurlyAfter: "Expected { after '{{name}}'.",
  52. missingCurlyAfterCondition: "Expected { after '{{name}}' condition.",
  53. unexpectedCurlyAfter: "Unnecessary { after '{{name}}'.",
  54. unexpectedCurlyAfterCondition: "Unnecessary { after '{{name}}' condition."
  55. }
  56. },
  57. create(context) {
  58. const multiOnly = (context.options[0] === "multi");
  59. const multiLine = (context.options[0] === "multi-line");
  60. const multiOrNest = (context.options[0] === "multi-or-nest");
  61. const consistent = (context.options[1] === "consistent");
  62. const sourceCode = context.getSourceCode();
  63. //--------------------------------------------------------------------------
  64. // Helpers
  65. //--------------------------------------------------------------------------
  66. /**
  67. * Determines if a given node is a one-liner that's on the same line as it's preceding code.
  68. * @param {ASTNode} node The node to check.
  69. * @returns {boolean} True if the node is a one-liner that's on the same line as it's preceding code.
  70. * @private
  71. */
  72. function isCollapsedOneLiner(node) {
  73. const before = sourceCode.getTokenBefore(node);
  74. const last = sourceCode.getLastToken(node);
  75. const lastExcludingSemicolon = astUtils.isSemicolonToken(last) ? sourceCode.getTokenBefore(last) : last;
  76. return before.loc.start.line === lastExcludingSemicolon.loc.end.line;
  77. }
  78. /**
  79. * Determines if a given node is a one-liner.
  80. * @param {ASTNode} node The node to check.
  81. * @returns {boolean} True if the node is a one-liner.
  82. * @private
  83. */
  84. function isOneLiner(node) {
  85. if (node.type === "EmptyStatement") {
  86. return true;
  87. }
  88. const first = sourceCode.getFirstToken(node);
  89. const last = sourceCode.getLastToken(node);
  90. const lastExcludingSemicolon = astUtils.isSemicolonToken(last) ? sourceCode.getTokenBefore(last) : last;
  91. return first.loc.start.line === lastExcludingSemicolon.loc.end.line;
  92. }
  93. /**
  94. * Determines if the given node is a lexical declaration (let, const, function, or class)
  95. * @param {ASTNode} node The node to check
  96. * @returns {boolean} True if the node is a lexical declaration
  97. * @private
  98. */
  99. function isLexicalDeclaration(node) {
  100. if (node.type === "VariableDeclaration") {
  101. return node.kind === "const" || node.kind === "let";
  102. }
  103. return node.type === "FunctionDeclaration" || node.type === "ClassDeclaration";
  104. }
  105. /**
  106. * Checks if the given token is an `else` token or not.
  107. * @param {Token} token The token to check.
  108. * @returns {boolean} `true` if the token is an `else` token.
  109. */
  110. function isElseKeywordToken(token) {
  111. return token.value === "else" && token.type === "Keyword";
  112. }
  113. /**
  114. * Determines whether the given node has an `else` keyword token as the first token after.
  115. * @param {ASTNode} node The node to check.
  116. * @returns {boolean} `true` if the node is followed by an `else` keyword token.
  117. */
  118. function isFollowedByElseKeyword(node) {
  119. const nextToken = sourceCode.getTokenAfter(node);
  120. return Boolean(nextToken) && isElseKeywordToken(nextToken);
  121. }
  122. /**
  123. * Determines if a semicolon needs to be inserted after removing a set of curly brackets, in order to avoid a SyntaxError.
  124. * @param {Token} closingBracket The } token
  125. * @returns {boolean} `true` if a semicolon needs to be inserted after the last statement in the block.
  126. */
  127. function needsSemicolon(closingBracket) {
  128. const tokenBefore = sourceCode.getTokenBefore(closingBracket);
  129. const tokenAfter = sourceCode.getTokenAfter(closingBracket);
  130. const lastBlockNode = sourceCode.getNodeByRangeIndex(tokenBefore.range[0]);
  131. if (astUtils.isSemicolonToken(tokenBefore)) {
  132. // If the last statement already has a semicolon, don't add another one.
  133. return false;
  134. }
  135. if (!tokenAfter) {
  136. // If there are no statements after this block, there is no need to add a semicolon.
  137. return false;
  138. }
  139. if (lastBlockNode.type === "BlockStatement" && lastBlockNode.parent.type !== "FunctionExpression" && lastBlockNode.parent.type !== "ArrowFunctionExpression") {
  140. /*
  141. * If the last node surrounded by curly brackets is a BlockStatement (other than a FunctionExpression or an ArrowFunctionExpression),
  142. * don't insert a semicolon. Otherwise, the semicolon would be parsed as a separate statement, which would cause
  143. * a SyntaxError if it was followed by `else`.
  144. */
  145. return false;
  146. }
  147. if (tokenBefore.loc.end.line === tokenAfter.loc.start.line) {
  148. // If the next token is on the same line, insert a semicolon.
  149. return true;
  150. }
  151. if (/^[([/`+-]/u.test(tokenAfter.value)) {
  152. // If the next token starts with a character that would disrupt ASI, insert a semicolon.
  153. return true;
  154. }
  155. if (tokenBefore.type === "Punctuator" && (tokenBefore.value === "++" || tokenBefore.value === "--")) {
  156. // If the last token is ++ or --, insert a semicolon to avoid disrupting ASI.
  157. return true;
  158. }
  159. // Otherwise, do not insert a semicolon.
  160. return false;
  161. }
  162. /**
  163. * Determines whether the code represented by the given node contains an `if` statement
  164. * that would become associated with an `else` keyword directly appended to that code.
  165. *
  166. * Examples where it returns `true`:
  167. *
  168. * if (a)
  169. * foo();
  170. *
  171. * if (a) {
  172. * foo();
  173. * }
  174. *
  175. * if (a)
  176. * foo();
  177. * else if (b)
  178. * bar();
  179. *
  180. * while (a)
  181. * if (b)
  182. * if(c)
  183. * foo();
  184. * else
  185. * bar();
  186. *
  187. * Examples where it returns `false`:
  188. *
  189. * if (a)
  190. * foo();
  191. * else
  192. * bar();
  193. *
  194. * while (a) {
  195. * if (b)
  196. * if(c)
  197. * foo();
  198. * else
  199. * bar();
  200. * }
  201. *
  202. * while (a)
  203. * if (b) {
  204. * if(c)
  205. * foo();
  206. * }
  207. * else
  208. * bar();
  209. * @param {ASTNode} node Node representing the code to check.
  210. * @returns {boolean} `true` if an `if` statement within the code would become associated with an `else` appended to that code.
  211. */
  212. function hasUnsafeIf(node) {
  213. switch (node.type) {
  214. case "IfStatement":
  215. if (!node.alternate) {
  216. return true;
  217. }
  218. return hasUnsafeIf(node.alternate);
  219. case "ForStatement":
  220. case "ForInStatement":
  221. case "ForOfStatement":
  222. case "LabeledStatement":
  223. case "WithStatement":
  224. case "WhileStatement":
  225. return hasUnsafeIf(node.body);
  226. default:
  227. return false;
  228. }
  229. }
  230. /**
  231. * Determines whether the existing curly braces around the single statement are necessary to preserve the semantics of the code.
  232. * The braces, which make the given block body, are necessary in either of the following situations:
  233. *
  234. * 1. The statement is a lexical declaration.
  235. * 2. Without the braces, an `if` within the statement would become associated with an `else` after the closing brace:
  236. *
  237. * if (a) {
  238. * if (b)
  239. * foo();
  240. * }
  241. * else
  242. * bar();
  243. *
  244. * if (a)
  245. * while (b)
  246. * while (c) {
  247. * while (d)
  248. * if (e)
  249. * while(f)
  250. * foo();
  251. * }
  252. * else
  253. * bar();
  254. * @param {ASTNode} node `BlockStatement` body with exactly one statement directly inside. The statement can have its own nested statements.
  255. * @returns {boolean} `true` if the braces are necessary - removing them (replacing the given `BlockStatement` body with its single statement content)
  256. * would change the semantics of the code or produce a syntax error.
  257. */
  258. function areBracesNecessary(node) {
  259. const statement = node.body[0];
  260. return isLexicalDeclaration(statement) ||
  261. hasUnsafeIf(statement) && isFollowedByElseKeyword(node);
  262. }
  263. /**
  264. * Prepares to check the body of a node to see if it's a block statement.
  265. * @param {ASTNode} node The node to report if there's a problem.
  266. * @param {ASTNode} body The body node to check for blocks.
  267. * @param {string} name The name to report if there's a problem.
  268. * @param {{ condition: boolean }} opts Options to pass to the report functions
  269. * @returns {Object} a prepared check object, with "actual", "expected", "check" properties.
  270. * "actual" will be `true` or `false` whether the body is already a block statement.
  271. * "expected" will be `true` or `false` if the body should be a block statement or not, or
  272. * `null` if it doesn't matter, depending on the rule options. It can be modified to change
  273. * the final behavior of "check".
  274. * "check" will be a function reporting appropriate problems depending on the other
  275. * properties.
  276. */
  277. function prepareCheck(node, body, name, opts) {
  278. const hasBlock = (body.type === "BlockStatement");
  279. let expected = null;
  280. if (hasBlock && (body.body.length !== 1 || areBracesNecessary(body))) {
  281. expected = true;
  282. } else if (multiOnly) {
  283. expected = false;
  284. } else if (multiLine) {
  285. if (!isCollapsedOneLiner(body)) {
  286. expected = true;
  287. }
  288. // otherwise, the body is allowed to have braces or not to have braces
  289. } else if (multiOrNest) {
  290. if (hasBlock) {
  291. const statement = body.body[0];
  292. const leadingCommentsInBlock = sourceCode.getCommentsBefore(statement);
  293. expected = !isOneLiner(statement) || leadingCommentsInBlock.length > 0;
  294. } else {
  295. expected = !isOneLiner(body);
  296. }
  297. } else {
  298. // default "all"
  299. expected = true;
  300. }
  301. return {
  302. actual: hasBlock,
  303. expected,
  304. check() {
  305. if (this.expected !== null && this.expected !== this.actual) {
  306. if (this.expected) {
  307. context.report({
  308. node,
  309. loc: body.loc,
  310. messageId: opts && opts.condition ? "missingCurlyAfterCondition" : "missingCurlyAfter",
  311. data: {
  312. name
  313. },
  314. fix: fixer => fixer.replaceText(body, `{${sourceCode.getText(body)}}`)
  315. });
  316. } else {
  317. context.report({
  318. node,
  319. loc: body.loc,
  320. messageId: opts && opts.condition ? "unexpectedCurlyAfterCondition" : "unexpectedCurlyAfter",
  321. data: {
  322. name
  323. },
  324. fix(fixer) {
  325. /*
  326. * `do while` expressions sometimes need a space to be inserted after `do`.
  327. * e.g. `do{foo()} while (bar)` should be corrected to `do foo() while (bar)`
  328. */
  329. const needsPrecedingSpace = node.type === "DoWhileStatement" &&
  330. sourceCode.getTokenBefore(body).range[1] === body.range[0] &&
  331. !astUtils.canTokensBeAdjacent("do", sourceCode.getFirstToken(body, { skip: 1 }));
  332. const openingBracket = sourceCode.getFirstToken(body);
  333. const closingBracket = sourceCode.getLastToken(body);
  334. const lastTokenInBlock = sourceCode.getTokenBefore(closingBracket);
  335. if (needsSemicolon(closingBracket)) {
  336. /*
  337. * If removing braces would cause a SyntaxError due to multiple statements on the same line (or
  338. * change the semantics of the code due to ASI), don't perform a fix.
  339. */
  340. return null;
  341. }
  342. const resultingBodyText = sourceCode.getText().slice(openingBracket.range[1], lastTokenInBlock.range[0]) +
  343. sourceCode.getText(lastTokenInBlock) +
  344. sourceCode.getText().slice(lastTokenInBlock.range[1], closingBracket.range[0]);
  345. return fixer.replaceText(body, (needsPrecedingSpace ? " " : "") + resultingBodyText);
  346. }
  347. });
  348. }
  349. }
  350. }
  351. };
  352. }
  353. /**
  354. * Prepares to check the bodies of a "if", "else if" and "else" chain.
  355. * @param {ASTNode} node The first IfStatement node of the chain.
  356. * @returns {Object[]} prepared checks for each body of the chain. See `prepareCheck` for more
  357. * information.
  358. */
  359. function prepareIfChecks(node) {
  360. const preparedChecks = [];
  361. for (let currentNode = node; currentNode; currentNode = currentNode.alternate) {
  362. preparedChecks.push(prepareCheck(currentNode, currentNode.consequent, "if", { condition: true }));
  363. if (currentNode.alternate && currentNode.alternate.type !== "IfStatement") {
  364. preparedChecks.push(prepareCheck(currentNode, currentNode.alternate, "else"));
  365. break;
  366. }
  367. }
  368. if (consistent) {
  369. /*
  370. * If any node should have or already have braces, make sure they
  371. * all have braces.
  372. * If all nodes shouldn't have braces, make sure they don't.
  373. */
  374. const expected = preparedChecks.some(preparedCheck => {
  375. if (preparedCheck.expected !== null) {
  376. return preparedCheck.expected;
  377. }
  378. return preparedCheck.actual;
  379. });
  380. preparedChecks.forEach(preparedCheck => {
  381. preparedCheck.expected = expected;
  382. });
  383. }
  384. return preparedChecks;
  385. }
  386. //--------------------------------------------------------------------------
  387. // Public
  388. //--------------------------------------------------------------------------
  389. return {
  390. IfStatement(node) {
  391. const parent = node.parent;
  392. const isElseIf = parent.type === "IfStatement" && parent.alternate === node;
  393. if (!isElseIf) {
  394. // This is a top `if`, check the whole `if-else-if` chain
  395. prepareIfChecks(node).forEach(preparedCheck => {
  396. preparedCheck.check();
  397. });
  398. }
  399. // Skip `else if`, it's already checked (when the top `if` was visited)
  400. },
  401. WhileStatement(node) {
  402. prepareCheck(node, node.body, "while", { condition: true }).check();
  403. },
  404. DoWhileStatement(node) {
  405. prepareCheck(node, node.body, "do").check();
  406. },
  407. ForStatement(node) {
  408. prepareCheck(node, node.body, "for", { condition: true }).check();
  409. },
  410. ForInStatement(node) {
  411. prepareCheck(node, node.body, "for-in").check();
  412. },
  413. ForOfStatement(node) {
  414. prepareCheck(node, node.body, "for-of").check();
  415. }
  416. };
  417. }
  418. };