]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/collapsible_if.rs
Merge pull request #3269 from rust-lang-nursery/relicense
[rust.git] / clippy_lints / src / collapsible_if.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10
11 //! Checks for if expressions that contain only an if expression.
12 //!
13 //! For example, the lint would catch:
14 //!
15 //! ```rust,ignore
16 //! if x {
17 //!     if y {
18 //!         println!("Hello world");
19 //!     }
20 //! }
21 //! ```
22 //!
23 //! This lint is **warn** by default
24
25 use crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
26 use crate::rustc::{declare_tool_lint, lint_array};
27 use if_chain::if_chain;
28 use crate::syntax::ast;
29
30 use crate::utils::{in_macro, snippet_block, span_lint_and_sugg, span_lint_and_then};
31 use crate::utils::sugg::Sugg;
32 use crate::rustc_errors::Applicability;
33
34 /// **What it does:** Checks for nested `if` statements which can be collapsed
35 /// by `&&`-combining their conditions and for `else { if ... }` expressions
36 /// that
37 /// can be collapsed to `else if ...`.
38 ///
39 /// **Why is this bad?** Each `if`-statement adds one level of nesting, which
40 /// makes code look more complex than it really is.
41 ///
42 /// **Known problems:** None.
43 ///
44 /// **Example:**
45 /// ```rust,ignore
46 /// if x {
47 ///     if y {
48 ///         …
49 ///     }
50 /// }
51 ///
52 /// // or
53 ///
54 /// if x {
55 ///     …
56 /// } else {
57 ///     if y {
58 ///         …
59 ///     }
60 /// }
61 /// ```
62 ///
63 /// Should be written:
64 ///
65 /// ```rust.ignore
66 /// if x && y {
67 ///     …
68 /// }
69 ///
70 /// // or
71 ///
72 /// if x {
73 ///     …
74 /// } else if y {
75 ///     …
76 /// }
77 /// ```
78 declare_clippy_lint! {
79     pub COLLAPSIBLE_IF,
80     style,
81     "`if`s that can be collapsed (e.g. `if x { if y { ... } }` and `else { if x { ... } }`)"
82 }
83
84 #[derive(Copy, Clone)]
85 pub struct CollapsibleIf;
86
87 impl LintPass for CollapsibleIf {
88     fn get_lints(&self) -> LintArray {
89         lint_array!(COLLAPSIBLE_IF)
90     }
91 }
92
93 impl EarlyLintPass for CollapsibleIf {
94     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
95         if !in_macro(expr.span) {
96             check_if(cx, expr)
97         }
98     }
99 }
100
101 fn check_if(cx: &EarlyContext<'_>, expr: &ast::Expr) {
102     match expr.node {
103         ast::ExprKind::If(ref check, ref then, ref else_) => if let Some(ref else_) = *else_ {
104             check_collapsible_maybe_if_let(cx, else_);
105         } else {
106             check_collapsible_no_if_let(cx, expr, check, then);
107         },
108         ast::ExprKind::IfLet(_, _, _, Some(ref else_)) => {
109             check_collapsible_maybe_if_let(cx, else_);
110         },
111         _ => (),
112     }
113 }
114
115 fn check_collapsible_maybe_if_let(cx: &EarlyContext<'_>, else_: &ast::Expr) {
116     if_chain! {
117         if let ast::ExprKind::Block(ref block, _) = else_.node;
118         if let Some(else_) = expr_block(block);
119         if !in_macro(else_.span);
120         then {
121             match else_.node {
122                 ast::ExprKind::If(..) | ast::ExprKind::IfLet(..) => {
123                     span_lint_and_sugg(cx,
124                                        COLLAPSIBLE_IF,
125                                        block.span,
126                                        "this `else { if .. }` block can be collapsed",
127                                        "try",
128                                        snippet_block(cx, else_.span, "..").into_owned());
129                 }
130                 _ => (),
131             }
132         }
133     }
134 }
135
136 fn check_collapsible_no_if_let(cx: &EarlyContext<'_>, expr: &ast::Expr, check: &ast::Expr, then: &ast::Block) {
137     if_chain! {
138         if let Some(inner) = expr_block(then);
139         if let ast::ExprKind::If(ref check_inner, ref content, None) = inner.node;
140         then {
141             if expr.span.ctxt() != inner.span.ctxt() {
142                 return;
143             }
144             span_lint_and_then(cx, COLLAPSIBLE_IF, expr.span, "this if statement can be collapsed", |db| {
145                 let lhs = Sugg::ast(cx, check, "..");
146                 let rhs = Sugg::ast(cx, check_inner, "..");
147                 db.span_suggestion_with_applicability(
148                     expr.span,
149                     "try",
150                     format!(
151                         "if {} {}",
152                         lhs.and(&rhs),
153                         snippet_block(cx, content.span, ".."),
154                     ),
155                     Applicability::MachineApplicable, // snippet
156                 );
157             });
158         }
159     }
160 }
161
162 /// If the block contains only one expression, return it.
163 fn expr_block(block: &ast::Block) -> Option<&ast::Expr> {
164     let mut it = block.stmts.iter();
165
166     if let (Some(stmt), None) = (it.next(), it.next()) {
167         match stmt.node {
168             ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => Some(expr),
169             _ => None,
170         }
171     } else {
172         None
173     }
174 }