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