]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/collapsible_if.rs
Use `utils::sugg` in `COLLAPSIBLE_IF`
[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:** `if x { if y { .. } }`
30 declare_lint! {
31     pub COLLAPSIBLE_IF,
32     Warn,
33     "two nested `if`-expressions can be collapsed into one, e.g. `if x { if y { foo() } }` \
34      can be written as `if x && y { foo() }` and an `else { if .. } expression can be collapsed to \
35      `else if`"
36 }
37
38 #[derive(Copy,Clone)]
39 pub struct CollapsibleIf;
40
41 impl LintPass for CollapsibleIf {
42     fn get_lints(&self) -> LintArray {
43         lint_array!(COLLAPSIBLE_IF)
44     }
45 }
46
47 impl EarlyLintPass for CollapsibleIf {
48     fn check_expr(&mut self, cx: &EarlyContext, expr: &ast::Expr) {
49         if !in_macro(cx, expr.span) {
50             check_if(cx, expr)
51         }
52     }
53 }
54
55 fn check_if(cx: &EarlyContext, expr: &ast::Expr) {
56     match expr.node {
57         ast::ExprKind::If(ref check, ref then, ref else_) => {
58             if let Some(ref else_) = *else_ {
59                 check_collapsible_maybe_if_let(cx, else_);
60             } else {
61                 check_collapsible_no_if_let(cx, expr, check, then);
62             }
63         }
64         ast::ExprKind::IfLet(_, _, _, Some(ref else_)) => {
65             check_collapsible_maybe_if_let(cx, else_);
66         }
67         _ => (),
68     }
69 }
70
71 fn check_collapsible_maybe_if_let(cx: &EarlyContext, else_: &ast::Expr) {
72     if_let_chain! {[
73         let ast::ExprKind::Block(ref block) = else_.node,
74         block.stmts.is_empty(),
75         let Some(ref else_) = block.expr,
76     ], {
77         match else_.node {
78             ast::ExprKind::If(..) | ast::ExprKind::IfLet(..) => {
79                 span_lint_and_then(cx,
80                                    COLLAPSIBLE_IF,
81                                    block.span,
82                                    "this `else { if .. }` block can be collapsed", |db| {
83                     db.span_suggestion(block.span, "try", snippet_block(cx, else_.span, "..").into_owned());
84                 });
85             }
86             _ => (),
87         }
88     }}
89 }
90
91 fn check_collapsible_no_if_let(
92     cx: &EarlyContext,
93     expr: &ast::Expr,
94     check: &ast::Expr,
95     then: &ast::Block,
96 ) {
97     if_let_chain! {[
98         let Some(inner) = single_stmt_of_block(then),
99         let ast::ExprKind::If(ref check_inner, ref content, None) = inner.node,
100     ], {
101         if expr.span.expn_id != inner.span.expn_id {
102             return;
103         }
104         span_lint_and_then(cx, COLLAPSIBLE_IF, expr.span, "this if statement can be collapsed", |db| {
105             let lhs = Sugg::ast(cx, check, "..");
106             let rhs = Sugg::ast(cx, check_inner, "..");
107             db.span_suggestion(expr.span,
108                                "try",
109                                format!("if {} {}",
110                                        lhs.and(&rhs),
111                                        snippet_block(cx, content.span, "..")));
112         });
113     }}
114 }
115
116 fn single_stmt_of_block(block: &ast::Block) -> Option<&ast::Expr> {
117     if block.stmts.len() == 1 && block.expr.is_none() {
118         if let ast::StmtKind::Expr(ref expr, _) = block.stmts[0].node {
119             single_stmt_of_expr(expr)
120         } else {
121             None
122         }
123     } else if block.stmts.is_empty() {
124         if let Some(ref p) = block.expr {
125             Some(p)
126         } else {
127             None
128         }
129     } else {
130         None
131     }
132 }
133
134 fn single_stmt_of_expr(expr: &ast::Expr) -> Option<&ast::Expr> {
135     if let ast::ExprKind::Block(ref block) = expr.node {
136         single_stmt_of_block(block)
137     } else {
138         Some(expr)
139     }
140 }