]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/collapsible_if.rs
Add applicability level to (nearly) every span_lint_and_sugg function
[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, snippet_block_with_applicability, 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 block_starts_with_comment(cx: &EarlyContext<'_>, expr: &ast::Block) -> bool {
116     // We trim all opening braces and whitespaces and then check if the next string is a comment.
117     let trimmed_block_text =
118         snippet_block(cx, expr.span, "..").trim_left_matches(|c: char| c.is_whitespace() || c == '{').to_owned();
119     trimmed_block_text.starts_with("//") || trimmed_block_text.starts_with("/*")
120 }
121
122 fn check_collapsible_maybe_if_let(cx: &EarlyContext<'_>, else_: &ast::Expr) {
123     if_chain! {
124         if let ast::ExprKind::Block(ref block, _) = else_.node;
125         if !block_starts_with_comment(cx, block);
126         if let Some(else_) = expr_block(block);
127         if !in_macro(else_.span);
128         then {
129             match else_.node {
130                 ast::ExprKind::If(..) | ast::ExprKind::IfLet(..) => {
131                     let mut applicability = Applicability::MachineApplicable;
132                     span_lint_and_sugg(
133                         cx,
134                         COLLAPSIBLE_IF,
135                         block.span,
136                         "this `else { if .. }` block can be collapsed",
137                         "try",
138                         snippet_block_with_applicability(cx, else_.span, "..", &mut applicability).into_owned(),
139                         applicability,
140                     );
141                 }
142                 _ => (),
143             }
144         }
145     }
146 }
147
148 fn check_collapsible_no_if_let(cx: &EarlyContext<'_>, expr: &ast::Expr, check: &ast::Expr, then: &ast::Block) {
149     if_chain! {
150         if !block_starts_with_comment(cx, then);
151         if let Some(inner) = expr_block(then);
152         if let ast::ExprKind::If(ref check_inner, ref content, None) = inner.node;
153         then {
154             if expr.span.ctxt() != inner.span.ctxt() {
155                 return;
156             }
157             span_lint_and_then(cx, COLLAPSIBLE_IF, expr.span, "this if statement can be collapsed", |db| {
158                 let lhs = Sugg::ast(cx, check, "..");
159                 let rhs = Sugg::ast(cx, check_inner, "..");
160                 db.span_suggestion_with_applicability(
161                     expr.span,
162                     "try",
163                     format!(
164                         "if {} {}",
165                         lhs.and(&rhs),
166                         snippet_block(cx, content.span, ".."),
167                     ),
168                     Applicability::MachineApplicable, // snippet
169                 );
170             });
171         }
172     }
173 }
174
175 /// If the block contains only one expression, return it.
176 fn expr_block(block: &ast::Block) -> Option<&ast::Expr> {
177     let mut it = block.stmts.iter();
178
179     if let (Some(stmt), None) = (it.next(), it.next()) {
180         match stmt.node {
181             ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => Some(expr),
182             _ => None,
183         }
184     } else {
185         None
186     }
187 }