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