Skip to content

Commit 75bdbfc

Browse files
committed
Auto merge of rust-lang#11853 - J-ZhengLi:issue11814, r=llogiq
expending lint [`blocks_in_if_conditions`] to check match expr as well closes: rust-lang#11814 changelog: rename lint `blocks_in_if_conditions` to [`blocks_in_conditions`] and expand it to check blocks in match scrutinees
2 parents ee83760 + 40b558a commit 75bdbfc

23 files changed

+334
-229
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4946,6 +4946,7 @@ Released 2018-09-13
49464946
[`blanket_clippy_restriction_lints`]: https://rust-lang.github.io/rust-clippy/master/index.html#blanket_clippy_restriction_lints
49474947
[`block_in_if_condition_expr`]: https://rust-lang.github.io/rust-clippy/master/index.html#block_in_if_condition_expr
49484948
[`block_in_if_condition_stmt`]: https://rust-lang.github.io/rust-clippy/master/index.html#block_in_if_condition_stmt
4949+
[`blocks_in_conditions`]: https://rust-lang.github.io/rust-clippy/master/index.html#blocks_in_conditions
49494950
[`blocks_in_if_conditions`]: https://rust-lang.github.io/rust-clippy/master/index.html#blocks_in_if_conditions
49504951
[`bool_assert_comparison`]: https://rust-lang.github.io/rust-clippy/master/index.html#bool_assert_comparison
49514952
[`bool_comparison`]: https://rust-lang.github.io/rust-clippy/master/index.html#bool_comparison
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
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::visitors::{for_each_expr, Descend};
5+
use clippy_utils::{get_parent_expr, higher};
6+
use core::ops::ControlFlow;
7+
use rustc_errors::Applicability;
8+
use rustc_hir::{BlockCheckMode, Expr, ExprKind, MatchSource};
9+
use rustc_lint::{LateContext, LateLintPass, LintContext};
10+
use rustc_middle::lint::in_external_macro;
11+
use rustc_session::declare_lint_pass;
12+
use rustc_span::sym;
13+
14+
declare_clippy_lint! {
15+
/// ### What it does
16+
/// Checks for `if` conditions that use blocks containing an
17+
/// expression, statements or conditions that use closures with blocks.
18+
///
19+
/// ### Why is this bad?
20+
/// Style, using blocks in the condition makes it hard to read.
21+
///
22+
/// ### Examples
23+
/// ```no_run
24+
/// # fn somefunc() -> bool { true };
25+
/// if { true } { /* ... */ }
26+
///
27+
/// if { let x = somefunc(); x } { /* ... */ }
28+
/// ```
29+
///
30+
/// Use instead:
31+
/// ```no_run
32+
/// # fn somefunc() -> bool { true };
33+
/// if true { /* ... */ }
34+
///
35+
/// let res = { let x = somefunc(); x };
36+
/// if res { /* ... */ }
37+
/// ```
38+
#[clippy::version = "1.45.0"]
39+
pub BLOCKS_IN_CONDITIONS,
40+
style,
41+
"useless or complex blocks that can be eliminated in conditions"
42+
}
43+
44+
declare_lint_pass!(BlocksInConditions => [BLOCKS_IN_CONDITIONS]);
45+
46+
const BRACED_EXPR_MESSAGE: &str = "omit braces around single expression condition";
47+
48+
impl<'tcx> LateLintPass<'tcx> for BlocksInConditions {
49+
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
50+
if in_external_macro(cx.sess(), expr.span) {
51+
return;
52+
}
53+
54+
let Some((cond, keyword, desc)) = higher::If::hir(expr)
55+
.map(|hif| (hif.cond, "if", "an `if` condition"))
56+
.or(if let ExprKind::Match(match_ex, _, MatchSource::Normal) = expr.kind {
57+
Some((match_ex, "match", "a `match` scrutinee"))
58+
} else {
59+
None
60+
})
61+
else {
62+
return;
63+
};
64+
let complex_block_message = &format!(
65+
"in {desc}, avoid complex blocks or closures with blocks; \
66+
instead, move the block or closure higher and bind it with a `let`",
67+
);
68+
69+
if let ExprKind::Block(block, _) = &cond.kind {
70+
if block.rules == BlockCheckMode::DefaultBlock {
71+
if block.stmts.is_empty() {
72+
if let Some(ex) = &block.expr {
73+
// don't dig into the expression here, just suggest that they remove
74+
// the block
75+
if expr.span.from_expansion() || ex.span.from_expansion() {
76+
return;
77+
}
78+
let mut applicability = Applicability::MachineApplicable;
79+
span_lint_and_sugg(
80+
cx,
81+
BLOCKS_IN_CONDITIONS,
82+
cond.span,
83+
BRACED_EXPR_MESSAGE,
84+
"try",
85+
snippet_block_with_applicability(cx, ex.span, "..", Some(expr.span), &mut applicability)
86+
.to_string(),
87+
applicability,
88+
);
89+
}
90+
} else {
91+
let span = block.expr.as_ref().map_or_else(|| block.stmts[0].span, |e| e.span);
92+
if span.from_expansion() || expr.span.from_expansion() {
93+
return;
94+
}
95+
// move block higher
96+
let mut applicability = Applicability::MachineApplicable;
97+
span_lint_and_sugg(
98+
cx,
99+
BLOCKS_IN_CONDITIONS,
100+
expr.span.with_hi(cond.span.hi()),
101+
complex_block_message,
102+
"try",
103+
format!(
104+
"let res = {}; {keyword} res",
105+
snippet_block_with_applicability(cx, block.span, "..", Some(expr.span), &mut applicability),
106+
),
107+
applicability,
108+
);
109+
}
110+
}
111+
} else {
112+
let _: Option<!> = for_each_expr(cond, |e| {
113+
if let ExprKind::Closure(closure) = e.kind {
114+
// do not lint if the closure is called using an iterator (see #1141)
115+
if let Some(parent) = get_parent_expr(cx, e)
116+
&& let ExprKind::MethodCall(_, self_arg, _, _) = &parent.kind
117+
&& let caller = cx.typeck_results().expr_ty(self_arg)
118+
&& let Some(iter_id) = cx.tcx.get_diagnostic_item(sym::Iterator)
119+
&& implements_trait(cx, caller, iter_id, &[])
120+
{
121+
return ControlFlow::Continue(Descend::No);
122+
}
123+
124+
let body = cx.tcx.hir().body(closure.body);
125+
let ex = &body.value;
126+
if let ExprKind::Block(block, _) = ex.kind {
127+
if !body.value.span.from_expansion() && !block.stmts.is_empty() {
128+
span_lint(cx, BLOCKS_IN_CONDITIONS, ex.span, complex_block_message);
129+
return ControlFlow::Continue(Descend::No);
130+
}
131+
}
132+
}
133+
ControlFlow::Continue(Descend::Yes)
134+
});
135+
}
136+
}
137+
}

clippy_lints/src/blocks_in_if_conditions.rs

Lines changed: 0 additions & 139 deletions
This file was deleted.

clippy_lints/src/declared_lints.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
6363
crate::await_holding_invalid::AWAIT_HOLDING_INVALID_TYPE_INFO,
6464
crate::await_holding_invalid::AWAIT_HOLDING_LOCK_INFO,
6565
crate::await_holding_invalid::AWAIT_HOLDING_REFCELL_REF_INFO,
66-
crate::blocks_in_if_conditions::BLOCKS_IN_IF_CONDITIONS_INFO,
66+
crate::blocks_in_conditions::BLOCKS_IN_CONDITIONS_INFO,
6767
crate::bool_assert_comparison::BOOL_ASSERT_COMPARISON_INFO,
6868
crate::bool_to_int_with_if::BOOL_TO_INT_WITH_IF_INFO,
6969
crate::booleans::NONMINIMAL_BOOL_INFO,

clippy_lints/src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ mod assertions_on_result_states;
7474
mod async_yields_async;
7575
mod attrs;
7676
mod await_holding_invalid;
77-
mod blocks_in_if_conditions;
77+
mod blocks_in_conditions;
7878
mod bool_assert_comparison;
7979
mod bool_to_int_with_if;
8080
mod booleans;
@@ -654,7 +654,7 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
654654
store.register_late_pass(|_| Box::<significant_drop_tightening::SignificantDropTightening<'_>>::default());
655655
store.register_late_pass(|_| Box::new(len_zero::LenZero));
656656
store.register_late_pass(|_| Box::new(attrs::Attributes));
657-
store.register_late_pass(|_| Box::new(blocks_in_if_conditions::BlocksInIfConditions));
657+
store.register_late_pass(|_| Box::new(blocks_in_conditions::BlocksInConditions));
658658
store.register_late_pass(|_| Box::new(unicode::Unicode));
659659
store.register_late_pass(|_| Box::new(uninit_vec::UninitVec));
660660
store.register_late_pass(|_| Box::new(unit_return_expecting_ord::UnitReturnExpectingOrd));

clippy_lints/src/renamed_lints.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@
44
pub static RENAMED_LINTS: &[(&str, &str)] = &[
55
("clippy::almost_complete_letter_range", "clippy::almost_complete_range"),
66
("clippy::blacklisted_name", "clippy::disallowed_names"),
7-
("clippy::block_in_if_condition_expr", "clippy::blocks_in_if_conditions"),
8-
("clippy::block_in_if_condition_stmt", "clippy::blocks_in_if_conditions"),
7+
("clippy::block_in_if_condition_expr", "clippy::blocks_in_conditions"),
8+
("clippy::block_in_if_condition_stmt", "clippy::blocks_in_conditions"),
9+
("clippy::blocks_in_if_conditions", "clippy::blocks_in_conditions"),
910
("clippy::box_vec", "clippy::box_collection"),
1011
("clippy::const_static_lifetime", "clippy::redundant_static_lifetimes"),
1112
("clippy::cyclomatic_complexity", "clippy::cognitive_complexity"),

tests/ui-toml/excessive_nesting/excessive_nesting.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
#![allow(clippy::never_loop)]
1010
#![allow(clippy::needless_if)]
1111
#![warn(clippy::excessive_nesting)]
12-
#![allow(clippy::collapsible_if)]
12+
#![allow(clippy::collapsible_if, clippy::blocks_in_conditions)]
1313

1414
#[macro_use]
1515
extern crate proc_macros;

tests/ui/bind_instead_of_map_multipart.fixed

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#![deny(clippy::bind_instead_of_map)]
2-
#![allow(clippy::blocks_in_if_conditions)]
2+
#![allow(clippy::blocks_in_conditions)]
33

44
pub fn main() {
55
let _ = Some("42").map(|s| if s.len() < 42 { 0 } else { s.len() });

tests/ui/bind_instead_of_map_multipart.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#![deny(clippy::bind_instead_of_map)]
2-
#![allow(clippy::blocks_in_if_conditions)]
2+
#![allow(clippy::blocks_in_conditions)]
33

44
pub fn main() {
55
let _ = Some("42").and_then(|s| if s.len() < 42 { Some(0) } else { Some(s.len()) });

tests/ui/blocks_in_if_conditions.fixed renamed to tests/ui/blocks_in_conditions.fixed

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#![warn(clippy::blocks_in_if_conditions)]
1+
#![warn(clippy::blocks_in_conditions)]
22
#![allow(unused, clippy::let_and_return, clippy::needless_if)]
33
#![warn(clippy::nonminimal_bool)]
44

@@ -21,6 +21,7 @@ fn macro_if() {
2121

2222
fn condition_has_block() -> i32 {
2323
let res = {
24+
//~^ ERROR: in an `if` condition, avoid complex blocks or closures with blocks; instead, move the block or closure higher and bind it with a `let`
2425
let x = 3;
2526
x == 3
2627
}; if res {
@@ -32,6 +33,7 @@ fn condition_has_block() -> i32 {
3233

3334
fn condition_has_block_with_single_expression() -> i32 {
3435
if true { 6 } else { 10 }
36+
//~^ ERROR: omit braces around single expression condition
3537
}
3638

3739
fn condition_is_normal() -> i32 {
@@ -61,4 +63,26 @@ fn block_in_assert() {
6163
);
6264
}
6365

66+
// issue #11814
67+
fn block_in_match_expr(num: i32) -> i32 {
68+
let res = {
69+
//~^ ERROR: in a `match` scrutinee, avoid complex blocks or closures with blocks; instead, move the block or closure higher and bind it with a `let`
70+
let opt = Some(2);
71+
opt
72+
}; match res {
73+
Some(0) => 1,
74+
Some(n) => num * 2,
75+
None => 0,
76+
};
77+
78+
match unsafe {
79+
let hearty_hearty_hearty = vec![240, 159, 146, 150];
80+
String::from_utf8_unchecked(hearty_hearty_hearty).as_str()
81+
} {
82+
"💖" => 1,
83+
"what" => 2,
84+
_ => 3,
85+
}
86+
}
87+
6488
fn main() {}

0 commit comments

Comments
 (0)