]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/collapsible_if.rs
Merge pull request #1054 from Manishearth/rustup
[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() }` and an `else { if .. } expression can be collapsed to \
36      `else if`"
37 }
38
39 #[derive(Copy,Clone)]
40 pub struct CollapsibleIf;
41
42 impl LintPass for CollapsibleIf {
43     fn get_lints(&self) -> LintArray {
44         lint_array!(COLLAPSIBLE_IF)
45     }
46 }
47
48 impl EarlyLintPass for CollapsibleIf {
49     fn check_expr(&mut self, cx: &EarlyContext, expr: &ast::Expr) {
50         if !in_macro(cx, expr.span) {
51             check_if(cx, expr)
52         }
53     }
54 }
55
56 fn check_if(cx: &EarlyContext, expr: &ast::Expr) {
57     match expr.node {
58         ast::ExprKind::If(ref check, ref then, ref else_) => {
59             if let Some(ref else_) = *else_ {
60                 check_collapsible_maybe_if_let(cx, else_);
61             } else {
62                 check_collapsible_no_if_let(cx, expr, check, then);
63             }
64         }
65         ast::ExprKind::IfLet(_, _, _, Some(ref else_)) => {
66             check_collapsible_maybe_if_let(cx, else_);
67         }
68         _ => (),
69     }
70 }
71
72 fn check_collapsible_maybe_if_let(cx: &EarlyContext, else_: &ast::Expr) {
73     if_let_chain! {[
74         let ast::ExprKind::Block(ref block) = else_.node,
75         let Some(ref else_) = expr_block(block),
76         !in_macro(cx, else_.span),
77     ], {
78         match else_.node {
79             ast::ExprKind::If(..) | ast::ExprKind::IfLet(..) => {
80                 span_lint_and_then(cx,
81                                    COLLAPSIBLE_IF,
82                                    block.span,
83                                    "this `else { if .. }` block can be collapsed", |db| {
84                     db.span_suggestion(block.span, "try", snippet_block(cx, else_.span, "..").into_owned());
85                 });
86             }
87             _ => (),
88         }
89     }}
90 }
91
92 fn check_collapsible_no_if_let(
93     cx: &EarlyContext,
94     expr: &ast::Expr,
95     check: &ast::Expr,
96     then: &ast::Block,
97 ) {
98     if_let_chain! {[
99         let Some(inner) = expr_block(then),
100         let ast::ExprKind::If(ref check_inner, ref content, None) = inner.node,
101     ], {
102         if expr.span.expn_id != inner.span.expn_id {
103             return;
104         }
105         span_lint_and_then(cx, COLLAPSIBLE_IF, expr.span, "this if statement can be collapsed", |db| {
106             db.span_suggestion(expr.span,
107                                "try",
108                                format!("if {} && {} {}",
109                                        check_to_string(cx, check),
110                                        check_to_string(cx, check_inner),
111                                        snippet_block(cx, content.span, "..")));
112         });
113     }}
114 }
115
116 fn requires_brackets(e: &ast::Expr) -> bool {
117     match e.node {
118         ast::ExprKind::Binary(Spanned { node: n, .. }, _, _) if n == ast::BinOpKind::Eq => false,
119         _ => true,
120     }
121 }
122
123 fn check_to_string(cx: &EarlyContext, e: &ast::Expr) -> Cow<'static, str> {
124     if requires_brackets(e) {
125         format!("({})", snippet(cx, e.span, "..")).into()
126     } else {
127         snippet(cx, e.span, "..")
128     }
129 }
130
131 /// If the block contains only one expression, returns it.
132 fn expr_block(block: &ast::Block) -> Option<&ast::Expr> {
133     let mut it = block.stmts.iter();
134
135     if let (Some(stmt), None) = (it.next(), it.next()) {
136         match stmt.node {
137             ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => Some(expr),
138             _ => None,
139         }
140     } else {
141         None
142     }
143 }