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