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