]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/collapsible_if.rs
Make `CollapsibleIf` an `EarlyLintPass`
[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 std::borrow::Cow;
17 use syntax::codemap::Spanned;
18 use syntax::ast;
19
20 use utils::{in_macro, snippet, snippet_block, span_lint_and_then};
21
22 /// **What it does:** This lint checks for nested `if`-statements which can be collapsed by
23 /// `&&`-combining their conditions and for `else { if .. }` expressions that can be collapsed to
24 /// `else if ..`.
25 ///
26 /// **Why is this bad?** Each `if`-statement adds one level of nesting, which makes code look more complex than it really is.
27 ///
28 /// **Known problems:** None
29 ///
30 /// **Example:** `if x { if y { .. } }`
31 declare_lint! {
32     pub COLLAPSIBLE_IF,
33     Warn,
34     "two nested `if`-expressions can be collapsed into one, e.g. `if x { if y { foo() } }` \
35      can be written as `if x && y { foo() }` and an `else { if .. } expression can be collapsed to \
36      `else if`"
37 }
38
39 #[derive(Copy,Clone)]
40 pub struct CollapsibleIf;
41
42 impl LintPass for CollapsibleIf {
43     fn get_lints(&self) -> LintArray {
44         lint_array!(COLLAPSIBLE_IF)
45     }
46 }
47
48 impl EarlyLintPass for CollapsibleIf {
49     fn check_expr(&mut self, cx: &EarlyContext, expr: &ast::Expr) {
50         if !in_macro(cx, expr.span) {
51             check_if(cx, expr)
52         }
53     }
54 }
55
56 fn check_if(cx: &EarlyContext, e: &ast::Expr) {
57     if let ast::ExprKind::If(ref check, ref then, ref else_) = e.node {
58         if let Some(ref else_) = *else_ {
59             if_let_chain! {[
60                 let ast::ExprKind::Block(ref block) = else_.node,
61                 block.stmts.is_empty(),
62                 let Some(ref else_) = block.expr,
63                 let ast::ExprKind::If(_, _, _) = else_.node
64             ], {
65                 span_lint_and_then(cx,
66                                    COLLAPSIBLE_IF,
67                                    block.span,
68                                    "this `else { if .. }` block can be collapsed", |db| {
69                     db.span_suggestion(block.span, "try", snippet_block(cx, else_.span, "..").into_owned());
70                 });
71             }}
72         } else if let Some(&ast::Expr { node: ast::ExprKind::If(ref check_inner, ref content, None), span: sp, .. }) =
73                single_stmt_of_block(then) {
74             if e.span.expn_id != sp.expn_id {
75                 return;
76             }
77             span_lint_and_then(cx, COLLAPSIBLE_IF, e.span, "this if statement can be collapsed", |db| {
78                 db.span_suggestion(e.span,
79                                    "try",
80                                    format!("if {} && {} {}",
81                                            check_to_string(cx, check),
82                                            check_to_string(cx, check_inner),
83                                            snippet_block(cx, content.span, "..")));
84             });
85         }
86     }
87 }
88
89 fn requires_brackets(e: &ast::Expr) -> bool {
90     match e.node {
91         ast::ExprKind::Binary(Spanned { node: n, .. }, _, _) if n == ast::BinOpKind::Eq => false,
92         _ => true,
93     }
94 }
95
96 fn check_to_string(cx: &EarlyContext, e: &ast::Expr) -> Cow<'static, str> {
97     if requires_brackets(e) {
98         format!("({})", snippet(cx, e.span, "..")).into()
99     } else {
100         snippet(cx, e.span, "..")
101     }
102 }
103
104 fn single_stmt_of_block(block: &ast::Block) -> Option<&ast::Expr> {
105     if block.stmts.len() == 1 && block.expr.is_none() {
106         if let ast::StmtKind::Expr(ref expr, _) = block.stmts[0].node {
107             single_stmt_of_expr(expr)
108         } else {
109             None
110         }
111     } else if block.stmts.is_empty() {
112         if let Some(ref p) = block.expr {
113             Some(p)
114         } else {
115             None
116         }
117     } else {
118         None
119     }
120 }
121
122 fn single_stmt_of_expr(expr: &ast::Expr) -> Option<&ast::Expr> {
123     if let ast::ExprKind::Block(ref block) = expr.node {
124         single_stmt_of_block(block)
125     } else {
126         Some(expr)
127     }
128 }