]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/blocks_in_if_conditions.rs
Auto merge of #9655 - llogiq:unbox-default, r=dswij
[rust.git] / clippy_lints / src / blocks_in_if_conditions.rs
1 use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg};
2 use clippy_utils::get_parent_expr;
3 use clippy_utils::higher;
4 use clippy_utils::source::snippet_block_with_applicability;
5 use clippy_utils::ty::implements_trait;
6 use clippy_utils::visitors::{for_each_expr, Descend};
7 use core::ops::ControlFlow;
8 use if_chain::if_chain;
9 use rustc_errors::Applicability;
10 use rustc_hir::{BlockCheckMode, Expr, ExprKind};
11 use rustc_lint::{LateContext, LateLintPass, LintContext};
12 use rustc_middle::lint::in_external_macro;
13 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 use rustc_span::sym;
15
16 declare_clippy_lint! {
17     /// ### What it does
18     /// Checks for `if` conditions that use blocks containing an
19     /// expression, statements or conditions that use closures with blocks.
20     ///
21     /// ### Why is this bad?
22     /// Style, using blocks in the condition makes it hard to read.
23     ///
24     /// ### Examples
25     /// ```rust
26     /// # fn somefunc() -> bool { true };
27     /// if { true } { /* ... */ }
28     ///
29     /// if { let x = somefunc(); x } { /* ... */ }
30     /// ```
31     ///
32     /// Use instead:
33     /// ```rust
34     /// # fn somefunc() -> bool { true };
35     /// if true { /* ... */ }
36     ///
37     /// let res = { let x = somefunc(); x };
38     /// if res { /* ... */ }
39     /// ```
40     #[clippy::version = "1.45.0"]
41     pub BLOCKS_IN_IF_CONDITIONS,
42     style,
43     "useless or complex blocks that can be eliminated in conditions"
44 }
45
46 declare_lint_pass!(BlocksInIfConditions => [BLOCKS_IN_IF_CONDITIONS]);
47
48 const BRACED_EXPR_MESSAGE: &str = "omit braces around single expression condition";
49 const COMPLEX_BLOCK_MESSAGE: &str = "in an `if` condition, avoid complex blocks or closures with blocks; \
50                                     instead, move the block or closure higher and bind it with a `let`";
51
52 impl<'tcx> LateLintPass<'tcx> for BlocksInIfConditions {
53     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
54         if in_external_macro(cx.sess(), expr.span) {
55             return;
56         }
57         if let Some(higher::If { cond, .. }) = higher::If::hir(expr) {
58             if let ExprKind::Block(block, _) = &cond.kind {
59                 if block.rules == BlockCheckMode::DefaultBlock {
60                     if block.stmts.is_empty() {
61                         if let Some(ex) = &block.expr {
62                             // don't dig into the expression here, just suggest that they remove
63                             // the block
64                             if expr.span.from_expansion() || ex.span.from_expansion() {
65                                 return;
66                             }
67                             let mut applicability = Applicability::MachineApplicable;
68                             span_lint_and_sugg(
69                                 cx,
70                                 BLOCKS_IN_IF_CONDITIONS,
71                                 cond.span,
72                                 BRACED_EXPR_MESSAGE,
73                                 "try",
74                                 format!(
75                                     "{}",
76                                     snippet_block_with_applicability(
77                                         cx,
78                                         ex.span,
79                                         "..",
80                                         Some(expr.span),
81                                         &mut applicability
82                                     )
83                                 ),
84                                 applicability,
85                             );
86                         }
87                     } else {
88                         let span = block.expr.as_ref().map_or_else(|| block.stmts[0].span, |e| e.span);
89                         if span.from_expansion() || expr.span.from_expansion() {
90                             return;
91                         }
92                         // move block higher
93                         let mut applicability = Applicability::MachineApplicable;
94                         span_lint_and_sugg(
95                             cx,
96                             BLOCKS_IN_IF_CONDITIONS,
97                             expr.span.with_hi(cond.span.hi()),
98                             COMPLEX_BLOCK_MESSAGE,
99                             "try",
100                             format!(
101                                 "let res = {}; if res",
102                                 snippet_block_with_applicability(
103                                     cx,
104                                     block.span,
105                                     "..",
106                                     Some(expr.span),
107                                     &mut applicability
108                                 ),
109                             ),
110                             applicability,
111                         );
112                     }
113                 }
114             } else {
115                 let _: Option<!> = for_each_expr(cond, |e| {
116                     if let ExprKind::Closure(closure) = e.kind {
117                         // do not lint if the closure is called using an iterator (see #1141)
118                         if_chain! {
119                             if let Some(parent) = get_parent_expr(cx, e);
120                             if let ExprKind::MethodCall(_, self_arg, _, _) = &parent.kind;
121                             let caller = cx.typeck_results().expr_ty(self_arg);
122                             if let Some(iter_id) = cx.tcx.get_diagnostic_item(sym::Iterator);
123                             if implements_trait(cx, caller, iter_id, &[]);
124                             then {
125                                 return ControlFlow::Continue(Descend::No);
126                             }
127                         }
128
129                         let body = cx.tcx.hir().body(closure.body);
130                         let ex = &body.value;
131                         if let ExprKind::Block(block, _) = ex.kind {
132                             if !body.value.span.from_expansion() && !block.stmts.is_empty() {
133                                 span_lint(cx, BLOCKS_IN_IF_CONDITIONS, ex.span, COMPLEX_BLOCK_MESSAGE);
134                                 return ControlFlow::Continue(Descend::No);
135                             }
136                         }
137                     }
138                     ControlFlow::Continue(Descend::Yes)
139                 });
140             }
141         }
142     }
143 }