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