UNPKG

3.71 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to disallow if as the only statmenet in an else block
3 * @author Brandon Mills
4 */
5"use strict";
6
7//------------------------------------------------------------------------------
8// Rule Definition
9//------------------------------------------------------------------------------
10
11module.exports = {
12 meta: {
13 type: "suggestion",
14
15 docs: {
16 description: "disallow `if` statements as the only statement in `else` blocks",
17 category: "Stylistic Issues",
18 recommended: false,
19 url: "https://eslint.org/docs/rules/no-lonely-if"
20 },
21
22 schema: [],
23 fixable: "code"
24 },
25
26 create(context) {
27 const sourceCode = context.getSourceCode();
28
29 return {
30 IfStatement(node) {
31 const ancestors = context.getAncestors(),
32 parent = ancestors.pop(),
33 grandparent = ancestors.pop();
34
35 if (parent && parent.type === "BlockStatement" &&
36 parent.body.length === 1 && grandparent &&
37 grandparent.type === "IfStatement" &&
38 parent === grandparent.alternate) {
39 context.report({
40 node,
41 message: "Unexpected if as the only statement in an else block.",
42 fix(fixer) {
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();
49
50 if (sourceText.slice(openingElseCurly.range[1],
51 node.range[0]).trim() || sourceText.slice(node.range[1], closingElseCurly.range[0]).trim()) {
52
53 // Don't fix if there are any non-whitespace characters interfering (e.g. comments)
54 return null;
55 }
56
57 if (
58 node.consequent.type !== "BlockStatement" && lastIfToken.value !== ";" && tokenAfterElseBlock &&
59 (
60 node.consequent.loc.end.line === tokenAfterElseBlock.loc.start.line ||
61 /^[([/+`-]/u.test(tokenAfterElseBlock.value) ||
62 lastIfToken.value === "++" ||
63 lastIfToken.value === "--"
64 )
65 ) {
66
67 /*
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.
70 */
71 return null;
72 }
73
74 return fixer.replaceTextRange(
75 [openingElseCurly.range[0], closingElseCurly.range[1]],
76 (elseKeyword.range[1] === openingElseCurly.range[0] ? " " : "") + sourceCode.getText(node)
77 );
78 }
79 });
80 }
81 }
82 };
83
84 }
85};