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