]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/collapsible_if.rs
Merge pull request #1080 from sourcefrog/patch-2
[rust.git] / clippy_lints / src / collapsible_if.rs
1 //! Checks for if expressions that contain only an if expression.
2 //!
3 //! For example, the lint would catch:
4 //!
5 //! ```
6 //! if x {
7 //!     if y {
8 //!         println!("Hello world");
9 //!     }
10 //! }
11 //! ```
12 //!
13 //! This lint is **warn** by default
14
15 use rustc::lint::*;
16 use std::borrow::Cow;
17 use syntax::codemap::Spanned;
18 use syntax::ast;
19
20 use utils::{in_macro, snippet, snippet_block, span_lint_and_then};
21
22 /// **What it does:** This lint checks for nested `if`-statements which can be collapsed by
23 /// `&&`-combining their conditions and for `else { if .. }` expressions that can be collapsed to
24 /// `else if ..`.
25 ///
26 /// **Why is this bad?** Each `if`-statement adds one level of nesting, which makes code look more complex than it really is.
27 ///
28 /// **Known problems:** None
29 ///
30 /// **Example:** `if x { if y { .. } }`
31 declare_lint! {
32     pub COLLAPSIBLE_IF,
33     Warn,
34     "two nested `if`-expressions can be collapsed into one, e.g. `if x { if y { foo() } }` \
35      can be written as `if x && y { foo() }` \
36      and an `else { if .. }` expression can be collapsed to \
37      `else if`"
38 }
39
40 #[derive(Copy,Clone)]
41 pub struct CollapsibleIf;
42
43 impl LintPass for CollapsibleIf {
44     fn get_lints(&self) -> LintArray {
45         lint_array!(COLLAPSIBLE_IF)
46     }
47 }
48
49 impl EarlyLintPass for CollapsibleIf {
50     fn check_expr(&mut self, cx: &EarlyContext, expr: &ast::Expr) {
51         if !in_macro(cx, expr.span) {
52             check_if(cx, expr)
53         }
54     }
55 }
56
57 fn check_if(cx: &EarlyContext, expr: &ast::Expr) {
58     match expr.node {
59         ast::ExprKind::If(ref check, ref then, ref else_) => {
60             if let Some(ref else_) = *else_ {
61                 check_collapsible_maybe_if_let(cx, else_);
62             } else {
63                 check_collapsible_no_if_let(cx, expr, check, then);
64             }
65         }
66         ast::ExprKind::IfLet(_, _, _, Some(ref else_)) => {
67             check_collapsible_maybe_if_let(cx, else_);
68         }
69         _ => (),
70     }
71 }
72
73 fn check_collapsible_maybe_if_let(cx: &EarlyContext, else_: &ast::Expr) {
74     if_let_chain! {[
75         let ast::ExprKind::Block(ref block) = else_.node,
76         let Some(ref else_) = expr_block(block),
77         !in_macro(cx, else_.span),
78     ], {
79         match else_.node {
80             ast::ExprKind::If(..) | ast::ExprKind::IfLet(..) => {
81                 span_lint_and_then(cx,
82                                    COLLAPSIBLE_IF,
83                                    block.span,
84                                    "this `else { if .. }` block can be collapsed", |db| {
85                     db.span_suggestion(block.span, "try", snippet_block(cx, else_.span, "..").into_owned());
86                 });
87             }
88             _ => (),
89         }
90     }}
91 }
92
93 fn check_collapsible_no_if_let(
94     cx: &EarlyContext,
95     expr: &ast::Expr,
96     check: &ast::Expr,
97     then: &ast::Block,
98 ) {
99     if_let_chain! {[
100         let Some(inner) = expr_block(then),
101         let ast::ExprKind::If(ref check_inner, ref content, None) = inner.node,
102     ], {
103         if expr.span.expn_id != inner.span.expn_id {
104             return;
105         }
106         span_lint_and_then(cx, COLLAPSIBLE_IF, expr.span, "this if statement can be collapsed", |db| {
107             db.span_suggestion(expr.span,
108                                "try",
109                                format!("if {} && {} {}",
110                                        check_to_string(cx, check),
111                                        check_to_string(cx, check_inner),
112                                        snippet_block(cx, content.span, "..")));
113         });
114     }}
115 }
116
117 fn requires_brackets(e: &ast::Expr) -> bool {
118     match e.node {
119         ast::ExprKind::Binary(Spanned { node: n, .. }, _, _) if n == ast::BinOpKind::Eq => false,
120         _ => true,
121     }
122 }
123
124 fn check_to_string(cx: &EarlyContext, e: &ast::Expr) -> Cow<'static, str> {
125     if requires_brackets(e) {
126         format!("({})", snippet(cx, e.span, "..")).into()
127     } else {
128         snippet(cx, e.span, "..")
129     }
130 }
131
132 /// If the block contains only one expression, returns it.
133 fn expr_block(block: &ast::Block) -> Option<&ast::Expr> {
134     let mut it = block.stmts.iter();
135
136     if let (Some(stmt), None) = (it.next(), it.next()) {
137         match stmt.node {
138             ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => Some(expr),
139             _ => None,
140         }
141     } else {
142         None
143     }
144 }