]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/collapsible_if.rs
Rollup merge of #102846 - zertosh:update-syn, r=dtolnay
[rust.git] / src / tools / clippy / 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 clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
16 use clippy_utils::source::{snippet, snippet_block, snippet_block_with_applicability};
17 use clippy_utils::sugg::Sugg;
18 use if_chain::if_chain;
19 use rustc_ast::ast;
20 use rustc_errors::Applicability;
21 use rustc_lint::{EarlyContext, EarlyLintPass};
22 use rustc_session::{declare_lint_pass, declare_tool_lint};
23 use rustc_span::Span;
24
25 declare_clippy_lint! {
26     /// ### What it does
27     /// Checks for nested `if` statements which can be collapsed
28     /// by `&&`-combining their conditions.
29     ///
30     /// ### Why is this bad?
31     /// Each `if`-statement adds one level of nesting, which
32     /// makes code look more complex than it really is.
33     ///
34     /// ### Example
35     /// ```rust
36     /// # let (x, y) = (true, true);
37     /// if x {
38     ///     if y {
39     ///         // …
40     ///     }
41     /// }
42     /// ```
43     ///
44     /// Use instead:
45     /// ```rust
46     /// # let (x, y) = (true, true);
47     /// if x && y {
48     ///     // …
49     /// }
50     /// ```
51     #[clippy::version = "pre 1.29.0"]
52     pub COLLAPSIBLE_IF,
53     style,
54     "nested `if`s that can be collapsed (e.g., `if x { if y { ... } }`"
55 }
56
57 declare_clippy_lint! {
58     /// ### What it does
59     /// Checks for collapsible `else { if ... }` expressions
60     /// that can be collapsed to `else if ...`.
61     ///
62     /// ### Why is this bad?
63     /// Each `if`-statement adds one level of nesting, which
64     /// makes code look more complex than it really is.
65     ///
66     /// ### Example
67     /// ```rust,ignore
68     ///
69     /// if x {
70     ///     …
71     /// } else {
72     ///     if y {
73     ///         …
74     ///     }
75     /// }
76     /// ```
77     ///
78     /// Should be written:
79     ///
80     /// ```rust,ignore
81     /// if x {
82     ///     …
83     /// } else if y {
84     ///     …
85     /// }
86     /// ```
87     #[clippy::version = "1.51.0"]
88     pub COLLAPSIBLE_ELSE_IF,
89     style,
90     "nested `else`-`if` expressions that can be collapsed (e.g., `else { if x { ... } }`)"
91 }
92
93 declare_lint_pass!(CollapsibleIf => [COLLAPSIBLE_IF, COLLAPSIBLE_ELSE_IF]);
94
95 impl EarlyLintPass for CollapsibleIf {
96     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
97         if !expr.span.from_expansion() {
98             check_if(cx, expr);
99         }
100     }
101 }
102
103 fn check_if(cx: &EarlyContext<'_>, expr: &ast::Expr) {
104     if let ast::ExprKind::If(check, then, else_) = &expr.kind {
105         if let Some(else_) = else_ {
106             check_collapsible_maybe_if_let(cx, then.span, else_);
107         } else if let ast::ExprKind::Let(..) = check.kind {
108             // Prevent triggering on `if let a = b { if c { .. } }`.
109         } else {
110             check_collapsible_no_if_let(cx, expr, check, then);
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 = snippet_block(cx, expr.span, "..", None)
118         .trim_start_matches(|c: char| c.is_whitespace() || c == '{')
119         .to_owned();
120     trimmed_block_text.starts_with("//") || trimmed_block_text.starts_with("/*")
121 }
122
123 fn check_collapsible_maybe_if_let(cx: &EarlyContext<'_>, then_span: Span, else_: &ast::Expr) {
124     if_chain! {
125         if let ast::ExprKind::Block(ref block, _) = else_.kind;
126         if !block_starts_with_comment(cx, block);
127         if let Some(else_) = expr_block(block);
128         if else_.attrs.is_empty();
129         if !else_.span.from_expansion();
130         if let ast::ExprKind::If(..) = else_.kind;
131         then {
132             // Prevent "elseif"
133             // Check that the "else" is followed by whitespace
134             let up_to_else = then_span.between(block.span);
135             let requires_space = if let Some(c) = snippet(cx, up_to_else, "..").chars().last() { !c.is_whitespace() } else { false };
136
137             let mut applicability = Applicability::MachineApplicable;
138             span_lint_and_sugg(
139                 cx,
140                 COLLAPSIBLE_ELSE_IF,
141                 block.span,
142                 "this `else { if .. }` block can be collapsed",
143                 "collapse nested if block",
144                 format!(
145                     "{}{}",
146                     if requires_space { " " } else { "" },
147                     snippet_block_with_applicability(cx, else_.span, "..", Some(block.span), &mut applicability)
148                 ),
149                 applicability,
150             );
151         }
152     }
153 }
154
155 fn check_collapsible_no_if_let(cx: &EarlyContext<'_>, expr: &ast::Expr, check: &ast::Expr, then: &ast::Block) {
156     if_chain! {
157         if !block_starts_with_comment(cx, then);
158         if let Some(inner) = expr_block(then);
159         if inner.attrs.is_empty();
160         if let ast::ExprKind::If(ref check_inner, ref content, None) = inner.kind;
161         // Prevent triggering on `if c { if let a = b { .. } }`.
162         if !matches!(check_inner.kind, ast::ExprKind::Let(..));
163         if expr.span.ctxt() == inner.span.ctxt();
164         then {
165             span_lint_and_then(cx, COLLAPSIBLE_IF, expr.span, "this `if` statement can be collapsed", |diag| {
166                 let lhs = Sugg::ast(cx, check, "..");
167                 let rhs = Sugg::ast(cx, check_inner, "..");
168                 diag.span_suggestion(
169                     expr.span,
170                     "collapse nested if block",
171                     format!(
172                         "if {} {}",
173                         lhs.and(&rhs),
174                         snippet_block(cx, content.span, "..", Some(expr.span)),
175                     ),
176                     Applicability::MachineApplicable, // snippet
177                 );
178             });
179         }
180     }
181 }
182
183 /// If the block contains only one expression, return it.
184 fn expr_block(block: &ast::Block) -> Option<&ast::Expr> {
185     let mut it = block.stmts.iter();
186
187     if let (Some(stmt), None) = (it.next(), it.next()) {
188         match stmt.kind {
189             ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => Some(expr),
190             _ => None,
191         }
192     } else {
193         None
194     }
195 }