]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/block_in_if_condition.rs
d004dcddfea013861f514ca3eab01d29fb9d7a10
[rust.git] / clippy_lints / src / block_in_if_condition.rs
1 use crate::utils::{differing_macro_contexts, higher, snippet_block_with_applicability, span_lint, span_lint_and_sugg};
2 use matches::matches;
3 use rustc::hir::map::Map;
4 use rustc::lint::in_external_macro;
5 use rustc_errors::Applicability;
6 use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
7 use rustc_hir::{BlockCheckMode, Expr, ExprKind};
8 use rustc_lint::{LateContext, LateLintPass, LintContext};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10
11 declare_clippy_lint! {
12     /// **What it does:** Checks for `if` conditions that use blocks to contain an
13     /// expression.
14     ///
15     /// **Why is this bad?** It isn't really Rust style, same as using parentheses
16     /// to contain expressions.
17     ///
18     /// **Known problems:** None.
19     ///
20     /// **Example:**
21     /// ```rust
22     /// if { true } { /* ... */ }
23     /// ```
24     pub BLOCK_IN_IF_CONDITION_EXPR,
25     style,
26     "braces that can be eliminated in conditions, e.g., `if { true } ...`"
27 }
28
29 declare_clippy_lint! {
30     /// **What it does:** Checks for `if` conditions that use blocks containing
31     /// statements, or conditions that use closures with blocks.
32     ///
33     /// **Why is this bad?** Using blocks in the condition makes it hard to read.
34     ///
35     /// **Known problems:** None.
36     ///
37     /// **Example:**
38     /// ```ignore
39     /// if { let x = somefunc(); x } {}
40     /// // or
41     /// if somefunc(|x| { x == 47 }) {}
42     /// ```
43     pub BLOCK_IN_IF_CONDITION_STMT,
44     style,
45     "complex blocks in conditions, e.g., `if { let x = true; x } ...`"
46 }
47
48 declare_lint_pass!(BlockInIfCondition => [BLOCK_IN_IF_CONDITION_EXPR, BLOCK_IN_IF_CONDITION_STMT]);
49
50 struct ExVisitor<'a, 'tcx> {
51     found_block: Option<&'tcx Expr<'tcx>>,
52     cx: &'a LateContext<'a, '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             let body = self.cx.tcx.hir().body(eid);
61             let ex = &body.value;
62             if matches!(ex.kind, ExprKind::Block(_, _)) && !body.value.span.from_expansion() {
63                 self.found_block = Some(ex);
64                 return;
65             }
66         }
67         walk_expr(self, expr);
68     }
69     fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
70         NestedVisitorMap::None
71     }
72 }
73
74 const BRACED_EXPR_MESSAGE: &str = "omit braces around single expression condition";
75 const COMPLEX_BLOCK_MESSAGE: &str = "in an `if` condition, avoid complex blocks or closures with blocks; \
76                                      instead, move the block or closure higher and bind it with a `let`";
77
78 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BlockInIfCondition {
79     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
80         if in_external_macro(cx.sess(), expr.span) {
81             return;
82         }
83         if let Some((cond, _, _)) = higher::if_block(&expr) {
84             if let ExprKind::Block(block, _) = &cond.kind {
85                 if block.rules == BlockCheckMode::DefaultBlock {
86                     if block.stmts.is_empty() {
87                         if let Some(ex) = &block.expr {
88                             // don't dig into the expression here, just suggest that they remove
89                             // the block
90                             if expr.span.from_expansion() || differing_macro_contexts(expr.span, ex.span) {
91                                 return;
92                             }
93                             let mut applicability = Applicability::MachineApplicable;
94                             span_lint_and_sugg(
95                                 cx,
96                                 BLOCK_IN_IF_CONDITION_EXPR,
97                                 cond.span,
98                                 BRACED_EXPR_MESSAGE,
99                                 "try",
100                                 format!(
101                                     "{}",
102                                     snippet_block_with_applicability(
103                                         cx,
104                                         ex.span,
105                                         "..",
106                                         Some(expr.span),
107                                         &mut applicability
108                                     )
109                                 ),
110                                 applicability,
111                             );
112                         }
113                     } else {
114                         let span = block.expr.as_ref().map_or_else(|| block.stmts[0].span, |e| e.span);
115                         if span.from_expansion() || differing_macro_contexts(expr.span, span) {
116                             return;
117                         }
118                         // move block higher
119                         let mut applicability = Applicability::MachineApplicable;
120                         span_lint_and_sugg(
121                             cx,
122                             BLOCK_IN_IF_CONDITION_STMT,
123                             expr.span.with_hi(cond.span.hi()),
124                             COMPLEX_BLOCK_MESSAGE,
125                             "try",
126                             format!(
127                                 "let res = {}; if res",
128                                 snippet_block_with_applicability(
129                                     cx,
130                                     block.span,
131                                     "..",
132                                     Some(expr.span),
133                                     &mut applicability
134                                 ),
135                             ),
136                             applicability,
137                         );
138                     }
139                 }
140             } else {
141                 let mut visitor = ExVisitor { found_block: None, cx };
142                 walk_expr(&mut visitor, cond);
143                 if let Some(block) = visitor.found_block {
144                     span_lint(cx, BLOCK_IN_IF_CONDITION_STMT, block.span, COMPLEX_BLOCK_MESSAGE);
145                 }
146             }
147         }
148     }
149 }