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