curly.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. module.exports = {
  14. meta: {
  15. type: "suggestion",
  16. docs: {
  17. description: "enforce consistent brace style for all control statements",
  18. category: "Best Practices",
  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. * Gets the `else` keyword token of a given `IfStatement` node.
  115. * @param {ASTNode} node A `IfStatement` node to get.
  116. * @returns {Token} The `else` keyword token.
  117. */
  118. function getElseKeyword(node) {
  119. return node.alternate && sourceCode.getFirstTokenBetween(node.consequent, node.alternate, isElseKeywordToken);
  120. }
  121. /**
  122. * Determines whether the given node has an `else` keyword token as the first token after.
  123. * @param {ASTNode} node The node to check.
  124. * @returns {boolean} `true` if the node is followed by an `else` keyword token.
  125. */
  126. function isFollowedByElseKeyword(node) {
  127. const nextToken = sourceCode.getTokenAfter(node);
  128. return Boolean(nextToken) && isElseKeywordToken(nextToken);
  129. }
  130. /**
  131. * Determines if a semicolon needs to be inserted after removing a set of curly brackets, in order to avoid a SyntaxError.
  132. * @param {Token} closingBracket The } token
  133. * @returns {boolean} `true` if a semicolon needs to be inserted after the last statement in the block.
  134. */
  135. function needsSemicolon(closingBracket) {
  136. const tokenBefore = sourceCode.getTokenBefore(closingBracket);
  137. const tokenAfter = sourceCode.getTokenAfter(closingBracket);
  138. const lastBlockNode = sourceCode.getNodeByRangeIndex(tokenBefore.range[0]);
  139. if (astUtils.isSemicolonToken(tokenBefore)) {
  140. // If the last statement already has a semicolon, don't add another one.
  141. return false;
  142. }
  143. if (!tokenAfter) {
  144. // If there are no statements after this block, there is no need to add a semicolon.
  145. return false;
  146. }
  147. if (lastBlockNode.type === "BlockStatement" && lastBlockNode.parent.type !== "FunctionExpression" && lastBlockNode.parent.type !== "ArrowFunctionExpression") {
  148. /*
  149. * If the last node surrounded by curly brackets is a BlockStatement (other than a FunctionExpression or an ArrowFunctionExpression),
  150. * don't insert a semicolon. Otherwise, the semicolon would be parsed as a separate statement, which would cause
  151. * a SyntaxError if it was followed by `else`.
  152. */
  153. return false;
  154. }
  155. if (tokenBefore.loc.end.line === tokenAfter.loc.start.line) {
  156. // If the next token is on the same line, insert a semicolon.
  157. return true;
  158. }
  159. if (/^[([/`+-]/u.test(tokenAfter.value)) {
  160. // If the next token starts with a character that would disrupt ASI, insert a semicolon.
  161. return true;
  162. }
  163. if (tokenBefore.type === "Punctuator" && (tokenBefore.value === "++" || tokenBefore.value === "--")) {
  164. // If the last token is ++ or --, insert a semicolon to avoid disrupting ASI.
  165. return true;
  166. }
  167. // Otherwise, do not insert a semicolon.
  168. return false;
  169. }
  170. /**
  171. * Determines whether the code represented by the given node contains an `if` statement
  172. * that would become associated with an `else` keyword directly appended to that code.
  173. *
  174. * Examples where it returns `true`:
  175. *
  176. * if (a)
  177. * foo();
  178. *
  179. * if (a) {
  180. * foo();
  181. * }
  182. *
  183. * if (a)
  184. * foo();
  185. * else if (b)
  186. * bar();
  187. *
  188. * while (a)
  189. * if (b)
  190. * if(c)
  191. * foo();
  192. * else
  193. * bar();
  194. *
  195. * Examples where it returns `false`:
  196. *
  197. * if (a)
  198. * foo();
  199. * else
  200. * bar();
  201. *
  202. * while (a) {
  203. * if (b)
  204. * if(c)
  205. * foo();
  206. * else
  207. * bar();
  208. * }
  209. *
  210. * while (a)
  211. * if (b) {
  212. * if(c)
  213. * foo();
  214. * }
  215. * else
  216. * bar();
  217. * @param {ASTNode} node Node representing the code to check.
  218. * @returns {boolean} `true` if an `if` statement within the code would become associated with an `else` appended to that code.
  219. */
  220. function hasUnsafeIf(node) {
  221. switch (node.type) {
  222. case "IfStatement":
  223. if (!node.alternate) {
  224. return true;
  225. }
  226. return hasUnsafeIf(node.alternate);
  227. case "ForStatement":
  228. case "ForInStatement":
  229. case "ForOfStatement":
  230. case "LabeledStatement":
  231. case "WithStatement":
  232. case "WhileStatement":
  233. return hasUnsafeIf(node.body);
  234. default:
  235. return false;
  236. }
  237. }
  238. /**
  239. * Determines whether the existing curly braces around the single statement are necessary to preserve the semantics of the code.
  240. * The braces, which make the given block body, are necessary in either of the following situations:
  241. *
  242. * 1. The statement is a lexical declaration.
  243. * 2. Without the braces, an `if` within the statement would become associated with an `else` after the closing brace:
  244. *
  245. * if (a) {
  246. * if (b)
  247. * foo();
  248. * }
  249. * else
  250. * bar();
  251. *
  252. * if (a)
  253. * while (b)
  254. * while (c) {
  255. * while (d)
  256. * if (e)
  257. * while(f)
  258. * foo();
  259. * }
  260. * else
  261. * bar();
  262. * @param {ASTNode} node `BlockStatement` body with exactly one statement directly inside. The statement can have its own nested statements.
  263. * @returns {boolean} `true` if the braces are necessary - removing them (replacing the given `BlockStatement` body with its single statement content)
  264. * would change the semantics of the code or produce a syntax error.
  265. */
  266. function areBracesNecessary(node) {
  267. const statement = node.body[0];
  268. return isLexicalDeclaration(statement) ||
  269. hasUnsafeIf(statement) && isFollowedByElseKeyword(node);
  270. }
  271. /**
  272. * Prepares to check the body of a node to see if it's a block statement.
  273. * @param {ASTNode} node The node to report if there's a problem.
  274. * @param {ASTNode} body The body node to check for blocks.
  275. * @param {string} name The name to report if there's a problem.
  276. * @param {{ condition: boolean }} opts Options to pass to the report functions
  277. * @returns {Object} a prepared check object, with "actual", "expected", "check" properties.
  278. * "actual" will be `true` or `false` whether the body is already a block statement.
  279. * "expected" will be `true` or `false` if the body should be a block statement or not, or
  280. * `null` if it doesn't matter, depending on the rule options. It can be modified to change
  281. * the final behavior of "check".
  282. * "check" will be a function reporting appropriate problems depending on the other
  283. * properties.
  284. */
  285. function prepareCheck(node, body, name, opts) {
  286. const hasBlock = (body.type === "BlockStatement");
  287. let expected = null;
  288. if (hasBlock && (body.body.length !== 1 || areBracesNecessary(body))) {
  289. expected = true;
  290. } else if (multiOnly) {
  291. expected = false;
  292. } else if (multiLine) {
  293. if (!isCollapsedOneLiner(body)) {
  294. expected = true;
  295. }
  296. // otherwise, the body is allowed to have braces or not to have braces
  297. } else if (multiOrNest) {
  298. if (hasBlock) {
  299. const statement = body.body[0];
  300. const leadingCommentsInBlock = sourceCode.getCommentsBefore(statement);
  301. expected = !isOneLiner(statement) || leadingCommentsInBlock.length > 0;
  302. } else {
  303. expected = !isOneLiner(body);
  304. }
  305. } else {
  306. // default "all"
  307. expected = true;
  308. }
  309. return {
  310. actual: hasBlock,
  311. expected,
  312. check() {
  313. if (this.expected !== null && this.expected !== this.actual) {
  314. if (this.expected) {
  315. context.report({
  316. node,
  317. loc: (name !== "else" ? node : getElseKeyword(node)).loc.start,
  318. messageId: opts && opts.condition ? "missingCurlyAfterCondition" : "missingCurlyAfter",
  319. data: {
  320. name
  321. },
  322. fix: fixer => fixer.replaceText(body, `{${sourceCode.getText(body)}}`)
  323. });
  324. } else {
  325. context.report({
  326. node,
  327. loc: (name !== "else" ? node : getElseKeyword(node)).loc.start,
  328. messageId: opts && opts.condition ? "unexpectedCurlyAfterCondition" : "unexpectedCurlyAfter",
  329. data: {
  330. name
  331. },
  332. fix(fixer) {
  333. /*
  334. * `do while` expressions sometimes need a space to be inserted after `do`.
  335. * e.g. `do{foo()} while (bar)` should be corrected to `do foo() while (bar)`
  336. */
  337. const needsPrecedingSpace = node.type === "DoWhileStatement" &&
  338. sourceCode.getTokenBefore(body).range[1] === body.range[0] &&
  339. !astUtils.canTokensBeAdjacent("do", sourceCode.getFirstToken(body, { skip: 1 }));
  340. const openingBracket = sourceCode.getFirstToken(body);
  341. const closingBracket = sourceCode.getLastToken(body);
  342. const lastTokenInBlock = sourceCode.getTokenBefore(closingBracket);
  343. if (needsSemicolon(closingBracket)) {
  344. /*
  345. * If removing braces would cause a SyntaxError due to multiple statements on the same line (or
  346. * change the semantics of the code due to ASI), don't perform a fix.
  347. */
  348. return null;
  349. }
  350. const resultingBodyText = sourceCode.getText().slice(openingBracket.range[1], lastTokenInBlock.range[0]) +
  351. sourceCode.getText(lastTokenInBlock) +
  352. sourceCode.getText().slice(lastTokenInBlock.range[1], closingBracket.range[0]);
  353. return fixer.replaceText(body, (needsPrecedingSpace ? " " : "") + resultingBodyText);
  354. }
  355. });
  356. }
  357. }
  358. }
  359. };
  360. }
  361. /**
  362. * Prepares to check the bodies of a "if", "else if" and "else" chain.
  363. * @param {ASTNode} node The first IfStatement node of the chain.
  364. * @returns {Object[]} prepared checks for each body of the chain. See `prepareCheck` for more
  365. * information.
  366. */
  367. function prepareIfChecks(node) {
  368. const preparedChecks = [];
  369. for (let currentNode = node; currentNode; currentNode = currentNode.alternate) {
  370. preparedChecks.push(prepareCheck(currentNode, currentNode.consequent, "if", { condition: true }));
  371. if (currentNode.alternate && currentNode.alternate.type !== "IfStatement") {
  372. preparedChecks.push(prepareCheck(currentNode, currentNode.alternate, "else"));
  373. break;
  374. }
  375. }
  376. if (consistent) {
  377. /*
  378. * If any node should have or already have braces, make sure they
  379. * all have braces.
  380. * If all nodes shouldn't have braces, make sure they don't.
  381. */
  382. const expected = preparedChecks.some(preparedCheck => {
  383. if (preparedCheck.expected !== null) {
  384. return preparedCheck.expected;
  385. }
  386. return preparedCheck.actual;
  387. });
  388. preparedChecks.forEach(preparedCheck => {
  389. preparedCheck.expected = expected;
  390. });
  391. }
  392. return preparedChecks;
  393. }
  394. //--------------------------------------------------------------------------
  395. // Public
  396. //--------------------------------------------------------------------------
  397. return {
  398. IfStatement(node) {
  399. const parent = node.parent;
  400. const isElseIf = parent.type === "IfStatement" && parent.alternate === node;
  401. if (!isElseIf) {
  402. // This is a top `if`, check the whole `if-else-if` chain
  403. prepareIfChecks(node).forEach(preparedCheck => {
  404. preparedCheck.check();
  405. });
  406. }
  407. // Skip `else if`, it's already checked (when the top `if` was visited)
  408. },
  409. WhileStatement(node) {
  410. prepareCheck(node, node.body, "while", { condition: true }).check();
  411. },
  412. DoWhileStatement(node) {
  413. prepareCheck(node, node.body, "do").check();
  414. },
  415. ForStatement(node) {
  416. prepareCheck(node, node.body, "for", { condition: true }).check();
  417. },
  418. ForInStatement(node) {
  419. prepareCheck(node, node.body, "for-in").check();
  420. },
  421. ForOfStatement(node) {
  422. prepareCheck(node, node.body, "for-of").check();
  423. }
  424. };
  425. }
  426. };