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