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