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