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