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 * Gets the `else` keyword token of a given `IfStatement` node.
136 * @param {ASTNode} node A `IfStatement` node to get.
137 * @returns {Token} The `else` keyword token.
139 function getElseKeyword(node) {
140 return node.alternate && sourceCode.getFirstTokenBetween(node.consequent, node.alternate, isElseKeywordToken);
144 * Checks a given IfStatement node requires braces of the consequent chunk.
145 * This returns `true` when below:
147 * 1. The given node has the `alternate` node.
148 * 2. There is a `IfStatement` which doesn't have `alternate` node in the
149 * trailing statement chain of the `consequent` node.
150 * @param {ASTNode} node A IfStatement node to check.
151 * @returns {boolean} `true` if the node requires braces of the consequent chunk.
153 function requiresBraceOfConsequent(node) {
154 if (node.alternate && node.consequent.type === "BlockStatement") {
155 if (node.consequent.body.length >= 2) {
160 let currentNode = node.consequent.body[0];
162 currentNode = astUtils.getTrailingStatement(currentNode)
164 if (currentNode.type === "IfStatement" && !currentNode.alternate) {
174 * Determines if a semicolon needs to be inserted after removing a set of curly brackets, in order to avoid a SyntaxError.
175 * @param {Token} closingBracket The } token
176 * @returns {boolean} `true` if a semicolon needs to be inserted after the last statement in the block.
178 function needsSemicolon(closingBracket) {
179 const tokenBefore = sourceCode.getTokenBefore(closingBracket);
180 const tokenAfter = sourceCode.getTokenAfter(closingBracket);
181 const lastBlockNode = sourceCode.getNodeByRangeIndex(tokenBefore.range[0]);
183 if (astUtils.isSemicolonToken(tokenBefore)) {
185 // If the last statement already has a semicolon, don't add another one.
191 // If there are no statements after this block, there is no need to add a semicolon.
195 if (lastBlockNode.type === "BlockStatement" && lastBlockNode.parent.type !== "FunctionExpression" && lastBlockNode.parent.type !== "ArrowFunctionExpression") {
198 * If the last node surrounded by curly brackets is a BlockStatement (other than a FunctionExpression or an ArrowFunctionExpression),
199 * don't insert a semicolon. Otherwise, the semicolon would be parsed as a separate statement, which would cause
200 * a SyntaxError if it was followed by `else`.
205 if (tokenBefore.loc.end.line === tokenAfter.loc.start.line) {
207 // If the next token is on the same line, insert a semicolon.
211 if (/^[([/`+-]/u.test(tokenAfter.value)) {
213 // If the next token starts with a character that would disrupt ASI, insert a semicolon.
217 if (tokenBefore.type === "Punctuator" && (tokenBefore.value === "++" || tokenBefore.value === "--")) {
219 // If the last token is ++ or --, insert a semicolon to avoid disrupting ASI.
223 // Otherwise, do not insert a semicolon.
228 * Prepares to check the body of a node to see if it's a block statement.
229 * @param {ASTNode} node The node to report if there's a problem.
230 * @param {ASTNode} body The body node to check for blocks.
231 * @param {string} name The name to report if there's a problem.
232 * @param {{ condition: boolean }} opts Options to pass to the report functions
233 * @returns {Object} a prepared check object, with "actual", "expected", "check" properties.
234 * "actual" will be `true` or `false` whether the body is already a block statement.
235 * "expected" will be `true` or `false` if the body should be a block statement or not, or
236 * `null` if it doesn't matter, depending on the rule options. It can be modified to change
237 * the final behavior of "check".
238 * "check" will be a function reporting appropriate problems depending on the other
241 function prepareCheck(node, body, name, opts) {
242 const hasBlock = (body.type === "BlockStatement");
245 if (node.type === "IfStatement" && node.consequent === body && requiresBraceOfConsequent(node)) {
247 } else if (multiOnly) {
248 if (hasBlock && body.body.length === 1 && !isLexicalDeclaration(body.body[0])) {
251 } else if (multiLine) {
252 if (!isCollapsedOneLiner(body)) {
255 } else if (multiOrNest) {
256 if (hasBlock && body.body.length === 1 && isOneLiner(body.body[0])) {
257 const leadingComments = sourceCode.getCommentsBefore(body.body[0]);
258 const isLexDef = isLexicalDeclaration(body.body[0]);
263 expected = leadingComments.length > 0;
265 } else if (!isOneLiner(body)) {
276 if (this.expected !== null && this.expected !== this.actual) {
280 loc: (name !== "else" ? node : getElseKeyword(node)).loc.start,
281 messageId: opts && opts.condition ? "missingCurlyAfterCondition" : "missingCurlyAfter",
285 fix: fixer => fixer.replaceText(body, `{${sourceCode.getText(body)}}`)
290 loc: (name !== "else" ? node : getElseKeyword(node)).loc.start,
291 messageId: opts && opts.condition ? "unexpectedCurlyAfterCondition" : "unexpectedCurlyAfter",
298 * `do while` expressions sometimes need a space to be inserted after `do`.
299 * e.g. `do{foo()} while (bar)` should be corrected to `do foo() while (bar)`
301 const needsPrecedingSpace = node.type === "DoWhileStatement" &&
302 sourceCode.getTokenBefore(body).range[1] === body.range[0] &&
303 !astUtils.canTokensBeAdjacent("do", sourceCode.getFirstToken(body, { skip: 1 }));
305 const openingBracket = sourceCode.getFirstToken(body);
306 const closingBracket = sourceCode.getLastToken(body);
307 const lastTokenInBlock = sourceCode.getTokenBefore(closingBracket);
309 if (needsSemicolon(closingBracket)) {
312 * If removing braces would cause a SyntaxError due to multiple statements on the same line (or
313 * change the semantics of the code due to ASI), don't perform a fix.
318 const resultingBodyText = sourceCode.getText().slice(openingBracket.range[1], lastTokenInBlock.range[0]) +
319 sourceCode.getText(lastTokenInBlock) +
320 sourceCode.getText().slice(lastTokenInBlock.range[1], closingBracket.range[0]);
322 return fixer.replaceText(body, (needsPrecedingSpace ? " " : "") + resultingBodyText);
332 * Prepares to check the bodies of a "if", "else if" and "else" chain.
333 * @param {ASTNode} node The first IfStatement node of the chain.
334 * @returns {Object[]} prepared checks for each body of the chain. See `prepareCheck` for more
337 function prepareIfChecks(node) {
338 const preparedChecks = [];
340 for (let currentNode = node; currentNode; currentNode = currentNode.alternate) {
341 preparedChecks.push(prepareCheck(currentNode, currentNode.consequent, "if", { condition: true }));
342 if (currentNode.alternate && currentNode.alternate.type !== "IfStatement") {
343 preparedChecks.push(prepareCheck(currentNode, currentNode.alternate, "else"));
351 * If any node should have or already have braces, make sure they
353 * If all nodes shouldn't have braces, make sure they don't.
355 const expected = preparedChecks.some(preparedCheck => {
356 if (preparedCheck.expected !== null) {
357 return preparedCheck.expected;
359 return preparedCheck.actual;
362 preparedChecks.forEach(preparedCheck => {
363 preparedCheck.expected = expected;
367 return preparedChecks;
370 //--------------------------------------------------------------------------
372 //--------------------------------------------------------------------------
376 if (node.parent.type !== "IfStatement") {
377 prepareIfChecks(node).forEach(preparedCheck => {
378 preparedCheck.check();
383 WhileStatement(node) {
384 prepareCheck(node, node.body, "while", { condition: true }).check();
387 DoWhileStatement(node) {
388 prepareCheck(node, node.body, "do").check();
392 prepareCheck(node, node.body, "for", { condition: true }).check();
395 ForInStatement(node) {
396 prepareCheck(node, node.body, "for-in").check();
399 ForOfStatement(node) {
400 prepareCheck(node, node.body, "for-of").check();