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