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