]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/collapsible_if.rs
First try for a fix for rustc 1.18.0-nightly (5c94997b6 2017-03-30
[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 //! ```rust,ignore
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 syntax::ast;
17
18 use utils::{in_macro, snippet_block, span_lint_and_then};
19 use utils::sugg::Sugg;
20
21 /// **What it does:** Checks for nested `if` statements which can be collapsed
22 /// by `&&`-combining their conditions and for `else { if ... }` expressions that
23 /// can be collapsed to `else if ...`.
24 ///
25 /// **Why is this bad?** Each `if`-statement adds one level of nesting, which
26 /// makes code look more complex than it really is.
27 ///
28 /// **Known problems:** None.
29 ///
30 /// **Example:**
31 /// ```rust,ignore
32 /// if x {
33 ///     if y {
34 ///         …
35 ///     }
36 /// }
37 ///
38 /// // or
39 ///
40 /// if x {
41 ///     …
42 /// } else {
43 ///     if y {
44 ///         …
45 ///     }
46 /// }
47 /// ```
48 ///
49 /// Should be written:
50 ///
51 /// ```rust.ignore
52 /// if x && y {
53 ///     …
54 /// }
55 ///
56 /// // or
57 ///
58 /// if x {
59 ///     …
60 /// } else if y {
61 ///     …
62 /// }
63 /// ```
64 declare_lint! {
65     pub COLLAPSIBLE_IF,
66     Warn,
67     "`if`s that can be collapsed (e.g. `if x { if y { ... } }` and `else { if x { ... } }`)"
68 }
69
70 #[derive(Copy,Clone)]
71 pub struct CollapsibleIf;
72
73 impl LintPass for CollapsibleIf {
74     fn get_lints(&self) -> LintArray {
75         lint_array!(COLLAPSIBLE_IF)
76     }
77 }
78
79 impl EarlyLintPass for CollapsibleIf {
80     fn check_expr(&mut self, cx: &EarlyContext, expr: &ast::Expr) {
81         if !in_macro(cx, expr.span) {
82             check_if(cx, expr)
83         }
84     }
85 }
86
87 fn check_if(cx: &EarlyContext, expr: &ast::Expr) {
88     match expr.node {
89         ast::ExprKind::If(ref check, ref then, ref else_) => {
90             if let Some(ref else_) = *else_ {
91                 check_collapsible_maybe_if_let(cx, else_);
92             } else {
93                 check_collapsible_no_if_let(cx, expr, check, then);
94             }
95         },
96         ast::ExprKind::IfLet(_, _, _, Some(ref else_)) => {
97             check_collapsible_maybe_if_let(cx, else_);
98         },
99         _ => (),
100     }
101 }
102
103 fn check_collapsible_maybe_if_let(cx: &EarlyContext, else_: &ast::Expr) {
104     if_let_chain! {[
105         let ast::ExprKind::Block(ref block) = else_.node,
106         let Some(ref else_) = expr_block(block),
107         !in_macro(cx, else_.span),
108     ], {
109         match else_.node {
110             ast::ExprKind::If(..) | ast::ExprKind::IfLet(..) => {
111                 span_lint_and_then(cx,
112                                    COLLAPSIBLE_IF,
113                                    block.span,
114                                    "this `else { if .. }` block can be collapsed", |db| {
115                     db.span_suggestion(block.span, "try", snippet_block(cx, else_.span, "..").into_owned());
116                 });
117             }
118             _ => (),
119         }
120     }}
121 }
122
123 fn check_collapsible_no_if_let(cx: &EarlyContext, expr: &ast::Expr, check: &ast::Expr, then: &ast::Block) {
124     if_let_chain! {[
125         let Some(inner) = expr_block(then),
126         let ast::ExprKind::If(ref check_inner, ref content, None) = inner.node,
127     ], {
128         if expr.span.ctxt != inner.span.ctxt {
129             return;
130         }
131         span_lint_and_then(cx, COLLAPSIBLE_IF, expr.span, "this if statement can be collapsed", |db| {
132             let lhs = Sugg::ast(cx, check, "..");
133             let rhs = Sugg::ast(cx, check_inner, "..");
134             db.span_suggestion(expr.span,
135                                "try",
136                                format!("if {} {}",
137                                        lhs.and(rhs),
138                                        snippet_block(cx, content.span, "..")));
139         });
140     }}
141 }
142
143 /// If the block contains only one expression, return it.
144 fn expr_block(block: &ast::Block) -> Option<&ast::Expr> {
145     let mut it = block.stmts.iter();
146
147     if let (Some(stmt), None) = (it.next(), it.next()) {
148         match stmt.node {
149             ast::StmtKind::Expr(ref expr) |
150             ast::StmtKind::Semi(ref expr) => Some(expr),
151             _ => None,
152         }
153     } else {
154         None
155     }
156 }