]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/collapsible_if.rs
Merge pull request #3465 from flip1995/rustfmt
[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 //! Checks for if expressions that contain only an if expression.
11 //!
12 //! For example, the lint would catch:
13 //!
14 //! ```rust,ignore
15 //! if x {
16 //!     if y {
17 //!         println!("Hello world");
18 //!     }
19 //! }
20 //! ```
21 //!
22 //! This lint is **warn** by default
23
24 use crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
25 use crate::rustc::{declare_tool_lint, lint_array};
26 use crate::syntax::ast;
27 use if_chain::if_chain;
28
29 use crate::rustc_errors::Applicability;
30 use crate::utils::sugg::Sugg;
31 use crate::utils::{in_macro, snippet_block, snippet_block_with_applicability, span_lint_and_sugg, span_lint_and_then};
32
33 /// **What it does:** Checks for nested `if` statements which can be collapsed
34 /// by `&&`-combining their conditions and for `else { if ... }` expressions
35 /// that
36 /// can be collapsed to `else if ...`.
37 ///
38 /// **Why is this bad?** Each `if`-statement adds one level of nesting, which
39 /// makes code look more complex than it really is.
40 ///
41 /// **Known problems:** None.
42 ///
43 /// **Example:**
44 /// ```rust,ignore
45 /// if x {
46 ///     if y {
47 ///         …
48 ///     }
49 /// }
50 ///
51 /// // or
52 ///
53 /// if x {
54 ///     …
55 /// } else {
56 ///     if y {
57 ///         …
58 ///     }
59 /// }
60 /// ```
61 ///
62 /// Should be written:
63 ///
64 /// ```rust.ignore
65 /// if x && y {
66 ///     …
67 /// }
68 ///
69 /// // or
70 ///
71 /// if x {
72 ///     …
73 /// } else if y {
74 ///     …
75 /// }
76 /// ```
77 declare_clippy_lint! {
78     pub COLLAPSIBLE_IF,
79     style,
80     "`if`s that can be collapsed (e.g. `if x { if y { ... } }` and `else { if x { ... } }`)"
81 }
82
83 #[derive(Copy, Clone)]
84 pub struct CollapsibleIf;
85
86 impl LintPass for CollapsibleIf {
87     fn get_lints(&self) -> LintArray {
88         lint_array!(COLLAPSIBLE_IF)
89     }
90 }
91
92 impl EarlyLintPass for CollapsibleIf {
93     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
94         if !in_macro(expr.span) {
95             check_if(cx, expr)
96         }
97     }
98 }
99
100 fn check_if(cx: &EarlyContext<'_>, expr: &ast::Expr) {
101     match expr.node {
102         ast::ExprKind::If(ref check, ref then, ref else_) => {
103             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         },
109         ast::ExprKind::IfLet(_, _, _, Some(ref else_)) => {
110             check_collapsible_maybe_if_let(cx, else_);
111         },
112         _ => (),
113     }
114 }
115
116 fn block_starts_with_comment(cx: &EarlyContext<'_>, expr: &ast::Block) -> bool {
117     // We trim all opening braces and whitespaces and then check if the next string is a comment.
118     let trimmed_block_text = snippet_block(cx, expr.span, "..")
119         .trim_left_matches(|c: char| c.is_whitespace() || c == '{')
120         .to_owned();
121     trimmed_block_text.starts_with("//") || trimmed_block_text.starts_with("/*")
122 }
123
124 fn check_collapsible_maybe_if_let(cx: &EarlyContext<'_>, else_: &ast::Expr) {
125     if_chain! {
126         if let ast::ExprKind::Block(ref block, _) = else_.node;
127         if !block_starts_with_comment(cx, block);
128         if let Some(else_) = expr_block(block);
129         if !in_macro(else_.span);
130         then {
131             match else_.node {
132                 ast::ExprKind::If(..) | ast::ExprKind::IfLet(..) => {
133                     let mut applicability = Applicability::MachineApplicable;
134                     span_lint_and_sugg(
135                         cx,
136                         COLLAPSIBLE_IF,
137                         block.span,
138                         "this `else { if .. }` block can be collapsed",
139                         "try",
140                         snippet_block_with_applicability(cx, else_.span, "..", &mut applicability).into_owned(),
141                         applicability,
142                     );
143                 }
144                 _ => (),
145             }
146         }
147     }
148 }
149
150 fn check_collapsible_no_if_let(cx: &EarlyContext<'_>, expr: &ast::Expr, check: &ast::Expr, then: &ast::Block) {
151     if_chain! {
152         if !block_starts_with_comment(cx, then);
153         if let Some(inner) = expr_block(then);
154         if let ast::ExprKind::If(ref check_inner, ref content, None) = inner.node;
155         then {
156             if expr.span.ctxt() != inner.span.ctxt() {
157                 return;
158             }
159             span_lint_and_then(cx, COLLAPSIBLE_IF, expr.span, "this if statement can be collapsed", |db| {
160                 let lhs = Sugg::ast(cx, check, "..");
161                 let rhs = Sugg::ast(cx, check_inner, "..");
162                 db.span_suggestion_with_applicability(
163                     expr.span,
164                     "try",
165                     format!(
166                         "if {} {}",
167                         lhs.and(&rhs),
168                         snippet_block(cx, content.span, ".."),
169                     ),
170                     Applicability::MachineApplicable, // snippet
171                 );
172             });
173         }
174     }
175 }
176
177 /// If the block contains only one expression, return it.
178 fn expr_block(block: &ast::Block) -> Option<&ast::Expr> {
179     let mut it = block.stmts.iter();
180
181     if let (Some(stmt), None) = (it.next(), it.next()) {
182         match stmt.node {
183             ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => Some(expr),
184             _ => None,
185         }
186     } else {
187         None
188     }
189 }