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