2 * @fileoverview Rule to flag statements without curly braces
3 * @author Nicholas C. Zakas
7 //------------------------------------------------------------------------------
9 //------------------------------------------------------------------------------
11 const astUtils = require("./utils/ast-utils");
13 //------------------------------------------------------------------------------
15 //------------------------------------------------------------------------------
22 description: "enforce consistent brace style for all control statements",
23 category: "Best Practices",
25 url: "https://eslint.org/docs/rules/curly"
44 enum: ["multi", "multi-line", "multi-or-nest"]
59 missingCurlyAfter: "Expected { after '{{name}}'.",
60 missingCurlyAfterCondition: "Expected { after '{{name}}' condition.",
61 unexpectedCurlyAfter: "Unnecessary { after '{{name}}'.",
62 unexpectedCurlyAfterCondition: "Unnecessary { after '{{name}}' condition."
68 const multiOnly = (context.options[0] === "multi");
69 const multiLine = (context.options[0] === "multi-line");
70 const multiOrNest = (context.options[0] === "multi-or-nest");
71 const consistent = (context.options[1] === "consistent");
73 const sourceCode = context.getSourceCode();
75 //--------------------------------------------------------------------------
77 //--------------------------------------------------------------------------
80 * Determines if a given node is a one-liner that's on the same line as it's preceding code.
81 * @param {ASTNode} node The node to check.
82 * @returns {boolean} True if the node is a one-liner that's on the same line as it's preceding code.
85 function isCollapsedOneLiner(node) {
86 const before = sourceCode.getTokenBefore(node);
87 const last = sourceCode.getLastToken(node);
88 const lastExcludingSemicolon = astUtils.isSemicolonToken(last) ? sourceCode.getTokenBefore(last) : last;
90 return before.loc.start.line === lastExcludingSemicolon.loc.end.line;
94 * Determines if a given node is a one-liner.
95 * @param {ASTNode} node The node to check.
96 * @returns {boolean} True if the node is a one-liner.
99 function isOneLiner(node) {
100 if (node.type === "EmptyStatement") {
104 const first = sourceCode.getFirstToken(node);
105 const last = sourceCode.getLastToken(node);
106 const lastExcludingSemicolon = astUtils.isSemicolonToken(last) ? sourceCode.getTokenBefore(last) : last;
108 return first.loc.start.line === lastExcludingSemicolon.loc.end.line;
112 * Determines if the given node is a lexical declaration (let, const, function, or class)
113 * @param {ASTNode} node The node to check
114 * @returns {boolean} True if the node is a lexical declaration
117 function isLexicalDeclaration(node) {
118 if (node.type === "VariableDeclaration") {
119 return node.kind === "const" || node.kind === "let";
122 return node.type === "FunctionDeclaration" || node.type === "ClassDeclaration";
126 * Checks if the given token is an `else` token or not.
127 * @param {Token} token The token to check.
128 * @returns {boolean} `true` if the token is an `else` token.
130 function isElseKeywordToken(token) {
131 return token.value === "else" && token.type === "Keyword";
135 * Determines whether the given node has an `else` keyword token as the first token after.
136 * @param {ASTNode} node The node to check.
137 * @returns {boolean} `true` if the node is followed by an `else` keyword token.
139 function isFollowedByElseKeyword(node) {
140 const nextToken = sourceCode.getTokenAfter(node);
142 return Boolean(nextToken) && isElseKeywordToken(nextToken);
146 * Determines if a semicolon needs to be inserted after removing a set of curly brackets, in order to avoid a SyntaxError.
147 * @param {Token} closingBracket The } token
148 * @returns {boolean} `true` if a semicolon needs to be inserted after the last statement in the block.
150 function needsSemicolon(closingBracket) {
151 const tokenBefore = sourceCode.getTokenBefore(closingBracket);
152 const tokenAfter = sourceCode.getTokenAfter(closingBracket);
153 const lastBlockNode = sourceCode.getNodeByRangeIndex(tokenBefore.range[0]);
155 if (astUtils.isSemicolonToken(tokenBefore)) {
157 // If the last statement already has a semicolon, don't add another one.
163 // If there are no statements after this block, there is no need to add a semicolon.
167 if (lastBlockNode.type === "BlockStatement" && lastBlockNode.parent.type !== "FunctionExpression" && lastBlockNode.parent.type !== "ArrowFunctionExpression") {
170 * If the last node surrounded by curly brackets is a BlockStatement (other than a FunctionExpression or an ArrowFunctionExpression),
171 * don't insert a semicolon. Otherwise, the semicolon would be parsed as a separate statement, which would cause
172 * a SyntaxError if it was followed by `else`.
177 if (tokenBefore.loc.end.line === tokenAfter.loc.start.line) {
179 // If the next token is on the same line, insert a semicolon.
183 if (/^[([/`+-]/u.test(tokenAfter.value)) {
185 // If the next token starts with a character that would disrupt ASI, insert a semicolon.
189 if (tokenBefore.type === "Punctuator" && (tokenBefore.value === "++" || tokenBefore.value === "--")) {
191 // If the last token is ++ or --, insert a semicolon to avoid disrupting ASI.
195 // Otherwise, do not insert a semicolon.
200 * Determines whether the code represented by the given node contains an `if` statement
201 * that would become associated with an `else` keyword directly appended to that code.
203 * Examples where it returns `true`:
224 * Examples where it returns `false`:
246 * @param {ASTNode} node Node representing the code to check.
247 * @returns {boolean} `true` if an `if` statement within the code would become associated with an `else` appended to that code.
249 function hasUnsafeIf(node) {
252 if (!node.alternate) {
255 return hasUnsafeIf(node.alternate);
257 case "ForInStatement":
258 case "ForOfStatement":
259 case "LabeledStatement":
260 case "WithStatement":
261 case "WhileStatement":
262 return hasUnsafeIf(node.body);
269 * Determines whether the existing curly braces around the single statement are necessary to preserve the semantics of the code.
270 * The braces, which make the given block body, are necessary in either of the following situations:
272 * 1. The statement is a lexical declaration.
273 * 2. Without the braces, an `if` within the statement would become associated with an `else` after the closing brace:
292 * @param {ASTNode} node `BlockStatement` body with exactly one statement directly inside. The statement can have its own nested statements.
293 * @returns {boolean} `true` if the braces are necessary - removing them (replacing the given `BlockStatement` body with its single statement content)
294 * would change the semantics of the code or produce a syntax error.
296 function areBracesNecessary(node) {
297 const statement = node.body[0];
299 return isLexicalDeclaration(statement) ||
300 hasUnsafeIf(statement) && isFollowedByElseKeyword(node);
304 * Prepares to check the body of a node to see if it's a block statement.
305 * @param {ASTNode} node The node to report if there's a problem.
306 * @param {ASTNode} body The body node to check for blocks.
307 * @param {string} name The name to report if there's a problem.
308 * @param {{ condition: boolean }} opts Options to pass to the report functions
309 * @returns {Object} a prepared check object, with "actual", "expected", "check" properties.
310 * "actual" will be `true` or `false` whether the body is already a block statement.
311 * "expected" will be `true` or `false` if the body should be a block statement or not, or
312 * `null` if it doesn't matter, depending on the rule options. It can be modified to change
313 * the final behavior of "check".
314 * "check" will be a function reporting appropriate problems depending on the other
317 function prepareCheck(node, body, name, opts) {
318 const hasBlock = (body.type === "BlockStatement");
321 if (hasBlock && (body.body.length !== 1 || areBracesNecessary(body))) {
323 } else if (multiOnly) {
325 } else if (multiLine) {
326 if (!isCollapsedOneLiner(body)) {
330 // otherwise, the body is allowed to have braces or not to have braces
332 } else if (multiOrNest) {
334 const statement = body.body[0];
335 const leadingCommentsInBlock = sourceCode.getCommentsBefore(statement);
337 expected = !isOneLiner(statement) || leadingCommentsInBlock.length > 0;
339 expected = !isOneLiner(body);
351 if (this.expected !== null && this.expected !== this.actual) {
356 messageId: opts && opts.condition ? "missingCurlyAfterCondition" : "missingCurlyAfter",
360 fix: fixer => fixer.replaceText(body, `{${sourceCode.getText(body)}}`)
366 messageId: opts && opts.condition ? "unexpectedCurlyAfterCondition" : "unexpectedCurlyAfter",
373 * `do while` expressions sometimes need a space to be inserted after `do`.
374 * e.g. `do{foo()} while (bar)` should be corrected to `do foo() while (bar)`
376 const needsPrecedingSpace = node.type === "DoWhileStatement" &&
377 sourceCode.getTokenBefore(body).range[1] === body.range[0] &&
378 !astUtils.canTokensBeAdjacent("do", sourceCode.getFirstToken(body, { skip: 1 }));
380 const openingBracket = sourceCode.getFirstToken(body);
381 const closingBracket = sourceCode.getLastToken(body);
382 const lastTokenInBlock = sourceCode.getTokenBefore(closingBracket);
384 if (needsSemicolon(closingBracket)) {
387 * If removing braces would cause a SyntaxError due to multiple statements on the same line (or
388 * change the semantics of the code due to ASI), don't perform a fix.
393 const resultingBodyText = sourceCode.getText().slice(openingBracket.range[1], lastTokenInBlock.range[0]) +
394 sourceCode.getText(lastTokenInBlock) +
395 sourceCode.getText().slice(lastTokenInBlock.range[1], closingBracket.range[0]);
397 return fixer.replaceText(body, (needsPrecedingSpace ? " " : "") + resultingBodyText);
407 * Prepares to check the bodies of a "if", "else if" and "else" chain.
408 * @param {ASTNode} node The first IfStatement node of the chain.
409 * @returns {Object[]} prepared checks for each body of the chain. See `prepareCheck` for more
412 function prepareIfChecks(node) {
413 const preparedChecks = [];
415 for (let currentNode = node; currentNode; currentNode = currentNode.alternate) {
416 preparedChecks.push(prepareCheck(currentNode, currentNode.consequent, "if", { condition: true }));
417 if (currentNode.alternate && currentNode.alternate.type !== "IfStatement") {
418 preparedChecks.push(prepareCheck(currentNode, currentNode.alternate, "else"));
426 * If any node should have or already have braces, make sure they
428 * If all nodes shouldn't have braces, make sure they don't.
430 const expected = preparedChecks.some(preparedCheck => {
431 if (preparedCheck.expected !== null) {
432 return preparedCheck.expected;
434 return preparedCheck.actual;
437 preparedChecks.forEach(preparedCheck => {
438 preparedCheck.expected = expected;
442 return preparedChecks;
445 //--------------------------------------------------------------------------
447 //--------------------------------------------------------------------------
451 const parent = node.parent;
452 const isElseIf = parent.type === "IfStatement" && parent.alternate === node;
456 // This is a top `if`, check the whole `if-else-if` chain
457 prepareIfChecks(node).forEach(preparedCheck => {
458 preparedCheck.check();
462 // Skip `else if`, it's already checked (when the top `if` was visited)
465 WhileStatement(node) {
466 prepareCheck(node, node.body, "while", { condition: true }).check();
469 DoWhileStatement(node) {
470 prepareCheck(node, node.body, "do").check();
474 prepareCheck(node, node.body, "for", { condition: true }).check();
477 ForInStatement(node) {
478 prepareCheck(node, node.body, "for-in").check();
481 ForOfStatement(node) {
482 prepareCheck(node, node.body, "for-of").check();