2 * @fileoverview Rule to disallow if as the only statement 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"
26 unexpectedLonelyIf: "Unexpected if as the only statement in an else block."
31 const sourceCode = context.getSourceCode();
35 const ancestors = context.getAncestors(),
36 parent = ancestors.pop(),
37 grandparent = ancestors.pop();
39 if (parent && parent.type === "BlockStatement" &&
40 parent.body.length === 1 && grandparent &&
41 grandparent.type === "IfStatement" &&
42 parent === grandparent.alternate) {
45 messageId: "unexpectedLonelyIf",
47 const openingElseCurly = sourceCode.getFirstToken(parent);
48 const closingElseCurly = sourceCode.getLastToken(parent);
49 const elseKeyword = sourceCode.getTokenBefore(openingElseCurly);
50 const tokenAfterElseBlock = sourceCode.getTokenAfter(closingElseCurly);
51 const lastIfToken = sourceCode.getLastToken(node.consequent);
52 const sourceText = sourceCode.getText();
54 if (sourceText.slice(openingElseCurly.range[1],
55 node.range[0]).trim() || sourceText.slice(node.range[1], closingElseCurly.range[0]).trim()) {
57 // Don't fix if there are any non-whitespace characters interfering (e.g. comments)
62 node.consequent.type !== "BlockStatement" && lastIfToken.value !== ";" && tokenAfterElseBlock &&
64 node.consequent.loc.end.line === tokenAfterElseBlock.loc.start.line ||
65 /^[([/+`-]/u.test(tokenAfterElseBlock.value) ||
66 lastIfToken.value === "++" ||
67 lastIfToken.value === "--"
72 * If the `if` statement has no block, and is not followed by a semicolon, make sure that fixing
73 * the issue would not change semantics due to ASI. If this would happen, don't do a fix.
78 return fixer.replaceTextRange(
79 [openingElseCurly.range[0], closingElseCurly.range[1]],
80 (elseKeyword.range[1] === openingElseCurly.range[0] ? " " : "") + sourceCode.getText(node)