]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/blocks_in_if_conditions.rs
Remove a span from hir::ExprKind::MethodCall
[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::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, Visitor};
9 use rustc_hir::{BlockCheckMode, 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     /// // Bad
26     /// if { true } { /* ... */ }
27     ///
28     /// // Good
29     /// if true { /* ... */ }
30     /// ```
31     ///
32     /// // or
33     ///
34     /// ```rust
35     /// # fn somefunc() -> bool { true };
36     /// // Bad
37     /// if { let x = somefunc(); x } { /* ... */ }
38     ///
39     /// // Good
40     /// let res = { let x = somefunc(); x };
41     /// if res { /* ... */ }
42     /// ```
43     #[clippy::version = "1.45.0"]
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     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(_, [self_arg, ..], _) = &parent.kind;
63                 let caller = self.cx.typeck_results().expr_ty(self_arg);
64                 if let Some(iter_id) = self.cx.tcx.get_diagnostic_item(sym::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 let ExprKind::Block(block, _) = ex.kind {
74                 if !body.value.span.from_expansion() && !block.stmts.is_empty() {
75                     self.found_block = Some(ex);
76                     return;
77                 }
78             }
79         }
80         walk_expr(self, expr);
81     }
82 }
83
84 const BRACED_EXPR_MESSAGE: &str = "omit braces around single expression condition";
85 const COMPLEX_BLOCK_MESSAGE: &str = "in an `if` condition, avoid complex blocks or closures with blocks; \
86                                     instead, move the block or closure higher and bind it with a `let`";
87
88 impl<'tcx> LateLintPass<'tcx> for BlocksInIfConditions {
89     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
90         if in_external_macro(cx.sess(), expr.span) {
91             return;
92         }
93         if let Some(higher::If { cond, .. }) = higher::If::hir(expr) {
94             if let ExprKind::Block(block, _) = &cond.kind {
95                 if block.rules == BlockCheckMode::DefaultBlock {
96                     if block.stmts.is_empty() {
97                         if let Some(ex) = &block.expr {
98                             // don't dig into the expression here, just suggest that they remove
99                             // the block
100                             if expr.span.from_expansion() || differing_macro_contexts(expr.span, ex.span) {
101                                 return;
102                             }
103                             let mut applicability = Applicability::MachineApplicable;
104                             span_lint_and_sugg(
105                                 cx,
106                                 BLOCKS_IN_IF_CONDITIONS,
107                                 cond.span,
108                                 BRACED_EXPR_MESSAGE,
109                                 "try",
110                                 format!(
111                                     "{}",
112                                     snippet_block_with_applicability(
113                                         cx,
114                                         ex.span,
115                                         "..",
116                                         Some(expr.span),
117                                         &mut applicability
118                                     )
119                                 ),
120                                 applicability,
121                             );
122                         }
123                     } else {
124                         let span = block.expr.as_ref().map_or_else(|| block.stmts[0].span, |e| e.span);
125                         if span.from_expansion() || differing_macro_contexts(expr.span, span) {
126                             return;
127                         }
128                         // move block higher
129                         let mut applicability = Applicability::MachineApplicable;
130                         span_lint_and_sugg(
131                             cx,
132                             BLOCKS_IN_IF_CONDITIONS,
133                             expr.span.with_hi(cond.span.hi()),
134                             COMPLEX_BLOCK_MESSAGE,
135                             "try",
136                             format!(
137                                 "let res = {}; if res",
138                                 snippet_block_with_applicability(
139                                     cx,
140                                     block.span,
141                                     "..",
142                                     Some(expr.span),
143                                     &mut applicability
144                                 ),
145                             ),
146                             applicability,
147                         );
148                     }
149                 }
150             } else {
151                 let mut visitor = ExVisitor { found_block: None, cx };
152                 walk_expr(&mut visitor, cond);
153                 if let Some(block) = visitor.found_block {
154                     span_lint(cx, BLOCKS_IN_IF_CONDITIONS, block.span, COMPLEX_BLOCK_MESSAGE);
155                 }
156             }
157         }
158     }
159 }