2 differing_macro_contexts, get_parent_expr, get_trait_def_id, implements_trait, paths,
3 snippet_block_with_applicability, span_lint, span_lint_and_sugg,
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
8 use rustc_hir::{BlockCheckMode, Expr, ExprKind};
9 use rustc_lint::{LateContext, LateLintPass, LintContext};
10 use rustc_middle::hir::map::Map;
11 use rustc_middle::lint::in_external_macro;
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 declare_clippy_lint! {
15 /// **What it does:** Checks for `if` conditions that use blocks containing an
16 /// expression, statements or conditions that use closures with blocks.
18 /// **Why is this bad?** Style, using blocks in the condition makes it hard to read.
20 /// **Known problems:** None.
25 /// if { true } { /* ... */ }
28 /// if true { /* ... */ }
34 /// # fn somefunc() -> bool { true };
36 /// if { let x = somefunc(); x } { /* ... */ }
39 /// let res = { let x = somefunc(); x };
40 /// if res { /* ... */ }
42 pub BLOCKS_IN_IF_CONDITIONS,
44 "useless or complex blocks that can be eliminated in conditions"
47 declare_lint_pass!(BlocksInIfConditions => [BLOCKS_IN_IF_CONDITIONS]);
49 struct ExVisitor<'a, 'tcx> {
50 found_block: Option<&'tcx Expr<'tcx>>,
51 cx: &'a LateContext<'tcx>,
54 impl<'a, 'tcx> Visitor<'tcx> for ExVisitor<'a, 'tcx> {
57 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
58 if let ExprKind::Closure(_, _, eid, _, _) = expr.kind {
59 // do not lint if the closure is called using an iterator (see #1141)
61 if let Some(parent) = get_parent_expr(self.cx, expr);
62 if let ExprKind::MethodCall(_, _, args, _) = parent.kind;
63 let caller = self.cx.typeck_results().expr_ty(&args[0]);
64 if let Some(iter_id) = get_trait_def_id(self.cx, &paths::ITERATOR);
65 if implements_trait(self.cx, caller, iter_id, &[]);
71 let body = self.cx.tcx.hir().body(eid);
73 if matches!(ex.kind, ExprKind::Block(_, _)) && !body.value.span.from_expansion() {
74 self.found_block = Some(ex);
78 walk_expr(self, expr);
80 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
81 NestedVisitorMap::None
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`";
89 impl<'tcx> LateLintPass<'tcx> for BlocksInIfConditions {
90 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
91 if in_external_macro(cx.sess(), expr.span) {
94 if let ExprKind::If(cond, _, _) = &expr.kind {
95 if let ExprKind::Block(block, _) = &cond.kind {
96 if block.rules == BlockCheckMode::DefaultBlock {
97 if block.stmts.is_empty() {
98 if let Some(ex) = &block.expr {
99 // don't dig into the expression here, just suggest that they remove
101 if expr.span.from_expansion() || differing_macro_contexts(expr.span, ex.span) {
104 let mut applicability = Applicability::MachineApplicable;
107 BLOCKS_IN_IF_CONDITIONS,
113 snippet_block_with_applicability(
125 let span = block.expr.as_ref().map_or_else(|| block.stmts[0].span, |e| e.span);
126 if span.from_expansion() || differing_macro_contexts(expr.span, span) {
130 let mut applicability = Applicability::MachineApplicable;
133 BLOCKS_IN_IF_CONDITIONS,
134 expr.span.with_hi(cond.span.hi()),
135 COMPLEX_BLOCK_MESSAGE,
138 "let res = {}; if res",
139 snippet_block_with_applicability(
152 let mut visitor = ExVisitor { found_block: None, cx };
153 walk_expr(&mut visitor, cond);
154 if let Some(block) = visitor.found_block {
155 span_lint(cx, BLOCKS_IN_IF_CONDITIONS, block.span, COMPLEX_BLOCK_MESSAGE);