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