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