2 * @fileoverview Rule to disallow if as the only statmenet in an else block
3 * @author Brandon Mills
7 //------------------------------------------------------------------------------
9 //------------------------------------------------------------------------------
16 description: "disallow `if` statements as the only statement in `else` blocks",
17 category: "Stylistic Issues",
19 url: "https://eslint.org/docs/rules/no-lonely-if"
27 const sourceCode = context.getSourceCode();
31 const ancestors = context.getAncestors(),
32 parent = ancestors.pop(),
33 grandparent = ancestors.pop();
35 if (parent && parent.type === "BlockStatement" &&
36 parent.body.length === 1 && grandparent &&
37 grandparent.type === "IfStatement" &&
38 parent === grandparent.alternate) {
41 message: "Unexpected if as the only statement in an else block.",
43 const openingElseCurly = sourceCode.getFirstToken(parent);
44 const closingElseCurly = sourceCode.getLastToken(parent);
45 const elseKeyword = sourceCode.getTokenBefore(openingElseCurly);
46 const tokenAfterElseBlock = sourceCode.getTokenAfter(closingElseCurly);
47 const lastIfToken = sourceCode.getLastToken(node.consequent);
48 const sourceText = sourceCode.getText();
50 if (sourceText.slice(openingElseCurly.range[1],
51 node.range[0]).trim() || sourceText.slice(node.range[1], closingElseCurly.range[0]).trim()) {
53 // Don't fix if there are any non-whitespace characters interfering (e.g. comments)
58 node.consequent.type !== "BlockStatement" && lastIfToken.value !== ";" && tokenAfterElseBlock &&
60 node.consequent.loc.end.line === tokenAfterElseBlock.loc.start.line ||
61 /^[([/+`-]/u.test(tokenAfterElseBlock.value) ||
62 lastIfToken.value === "++" ||
63 lastIfToken.value === "--"
68 * If the `if` statement has no block, and is not followed by a semicolon, make sure that fixing
69 * the issue would not change semantics due to ASI. If this would happen, don't do a fix.
74 return fixer.replaceTextRange(
75 [openingElseCurly.range[0], closingElseCurly.range[1]],
76 (elseKeyword.range[1] === openingElseCurly.range[0] ? " " : "") + sourceCode.getText(node)