]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/collapsible_if.rs
Merge pull request #2764 from phansch/integration_tests
[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_sugg, 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
23 /// that
24 /// can be collapsed to `else if ...`.
25 ///
26 /// **Why is this bad?** Each `if`-statement adds one level of nesting, which
27 /// makes code look more complex than it really is.
28 ///
29 /// **Known problems:** None.
30 ///
31 /// **Example:**
32 /// ```rust,ignore
33 /// if x {
34 ///     if y {
35 ///         …
36 ///     }
37 /// }
38 ///
39 /// // or
40 ///
41 /// if x {
42 ///     …
43 /// } else {
44 ///     if y {
45 ///         …
46 ///     }
47 /// }
48 /// ```
49 ///
50 /// Should be written:
51 ///
52 /// ```rust.ignore
53 /// if x && y {
54 ///     …
55 /// }
56 ///
57 /// // or
58 ///
59 /// if x {
60 ///     …
61 /// } else if y {
62 ///     …
63 /// }
64 /// ```
65 declare_clippy_lint! {
66     pub COLLAPSIBLE_IF,
67     style,
68     "`if`s that can be collapsed (e.g. `if x { if y { ... } }` and `else { if x { ... } }`)"
69 }
70
71 #[derive(Copy, Clone)]
72 pub struct CollapsibleIf;
73
74 impl LintPass for CollapsibleIf {
75     fn get_lints(&self) -> LintArray {
76         lint_array!(COLLAPSIBLE_IF)
77     }
78 }
79
80 impl EarlyLintPass for CollapsibleIf {
81     fn check_expr(&mut self, cx: &EarlyContext, expr: &ast::Expr) {
82         if !in_macro(expr.span) {
83             check_if(cx, expr)
84         }
85     }
86 }
87
88 fn check_if(cx: &EarlyContext, expr: &ast::Expr) {
89     match expr.node {
90         ast::ExprKind::If(ref check, ref then, ref else_) => 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         ast::ExprKind::IfLet(_, _, _, Some(ref else_)) => {
96             check_collapsible_maybe_if_let(cx, else_);
97         },
98         _ => (),
99     }
100 }
101
102 fn check_collapsible_maybe_if_let(cx: &EarlyContext, else_: &ast::Expr) {
103     if_chain! {
104         if let ast::ExprKind::Block(ref block, _) = else_.node;
105         if let Some(else_) = expr_block(block);
106         if !in_macro(else_.span);
107         then {
108             match else_.node {
109                 ast::ExprKind::If(..) | ast::ExprKind::IfLet(..) => {
110                     span_lint_and_sugg(cx,
111                                        COLLAPSIBLE_IF,
112                                        block.span,
113                                        "this `else { if .. }` block can be collapsed",
114                                        "try",
115                                        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_chain! {
125         if let Some(inner) = expr_block(then);
126         if let ast::ExprKind::If(ref check_inner, ref content, None) = inner.node;
127         then {
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
144 /// If the block contains only one expression, return it.
145 fn expr_block(block: &ast::Block) -> Option<&ast::Expr> {
146     let mut it = block.stmts.iter();
147
148     if let (Some(stmt), None) = (it.next(), it.next()) {
149         match stmt.node {
150             ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => Some(expr),
151             _ => None,
152         }
153     } else {
154         None
155     }
156 }