1 use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg};
2 use clippy_utils::source::snippet_block_with_applicability;
3 use clippy_utils::ty::implements_trait;
4 use clippy_utils::{differing_macro_contexts, get_parent_expr};
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};
15 declare_clippy_lint! {
16 /// **What it does:** Checks for `if` conditions that use blocks containing an
17 /// expression, statements or conditions that use closures with blocks.
19 /// **Why is this bad?** Style, using blocks in the condition makes it hard to read.
21 /// **Known problems:** None.
26 /// if { true } { /* ... */ }
29 /// if true { /* ... */ }
35 /// # fn somefunc() -> bool { true };
37 /// if { let x = somefunc(); x } { /* ... */ }
40 /// let res = { let x = somefunc(); x };
41 /// if res { /* ... */ }
43 pub BLOCKS_IN_IF_CONDITIONS,
45 "useless or complex blocks that can be eliminated in conditions"
48 declare_lint_pass!(BlocksInIfConditions => [BLOCKS_IN_IF_CONDITIONS]);
50 struct ExVisitor<'a, 'tcx> {
51 found_block: Option<&'tcx Expr<'tcx>>,
52 cx: &'a LateContext<'tcx>,
55 impl<'a, 'tcx> Visitor<'tcx> for ExVisitor<'a, 'tcx> {
58 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
59 if let ExprKind::Closure(_, _, eid, _, _) = expr.kind {
60 // do not lint if the closure is called using an iterator (see #1141)
62 if let Some(parent) = get_parent_expr(self.cx, expr);
63 if let ExprKind::MethodCall(_, _, args, _) = parent.kind;
64 let caller = self.cx.typeck_results().expr_ty(&args[0]);
65 if let Some(iter_id) = self.cx.tcx.get_diagnostic_item(sym::Iterator);
66 if implements_trait(self.cx, caller, iter_id, &[]);
72 let body = self.cx.tcx.hir().body(eid);
74 if matches!(ex.kind, ExprKind::Block(_, _)) && !body.value.span.from_expansion() {
75 self.found_block = Some(ex);
79 walk_expr(self, expr);
81 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
82 NestedVisitorMap::None
86 const BRACED_EXPR_MESSAGE: &str = "omit braces around single expression condition";
87 const COMPLEX_BLOCK_MESSAGE: &str = "in an `if` condition, avoid complex blocks or closures with blocks; \
88 instead, move the block or closure higher and bind it with a `let`";
90 impl<'tcx> LateLintPass<'tcx> for BlocksInIfConditions {
91 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
92 if in_external_macro(cx.sess(), expr.span) {
95 if let ExprKind::If(cond, _, _) = &expr.kind {
96 if let ExprKind::Block(block, _) = &cond.kind {
97 if block.rules == BlockCheckMode::DefaultBlock {
98 if block.stmts.is_empty() {
99 if let Some(ex) = &block.expr {
100 // don't dig into the expression here, just suggest that they remove
102 if expr.span.from_expansion() || differing_macro_contexts(expr.span, ex.span) {
105 let mut applicability = Applicability::MachineApplicable;
108 BLOCKS_IN_IF_CONDITIONS,
114 snippet_block_with_applicability(
126 let span = block.expr.as_ref().map_or_else(|| block.stmts[0].span, |e| e.span);
127 if span.from_expansion() || differing_macro_contexts(expr.span, span) {
131 let mut applicability = Applicability::MachineApplicable;
134 BLOCKS_IN_IF_CONDITIONS,
135 expr.span.with_hi(cond.span.hi()),
136 COMPLEX_BLOCK_MESSAGE,
139 "let res = {}; if res",
140 snippet_block_with_applicability(
153 let mut visitor = ExVisitor { found_block: None, cx };
154 walk_expr(&mut visitor, cond);
155 if let Some(block) = visitor.found_block {
156 span_lint(cx, BLOCKS_IN_IF_CONDITIONS, block.span, COMPLEX_BLOCK_MESSAGE);