Skip to content

Commit 942e0e6

Browse files
committed
Auto merge of #5800 - montrivo:bugfix/redundant_closure, r=matthiaskrgr
redundant_closure_call - don't lint when used more than once Fixes #3354. changelog: fix redundant_closure_call false positive when closure called more than once
2 parents 8cf4219 + 1ac8b85 commit 942e0e6

10 files changed

+233
-146
lines changed

clippy_lints/src/lib.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,7 @@ mod ptr_offset_with_cast;
276276
mod question_mark;
277277
mod ranges;
278278
mod redundant_clone;
279+
mod redundant_closure_call;
279280
mod redundant_field_names;
280281
mod redundant_pub_crate;
281282
mod redundant_static_lifetimes;
@@ -702,7 +703,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
702703
&misc_early::DOUBLE_NEG,
703704
&misc_early::DUPLICATE_UNDERSCORE_ARGUMENT,
704705
&misc_early::MIXED_CASE_HEX_LITERALS,
705-
&misc_early::REDUNDANT_CLOSURE_CALL,
706706
&misc_early::REDUNDANT_PATTERN,
707707
&misc_early::UNNEEDED_FIELD_PATTERN,
708708
&misc_early::UNNEEDED_WILDCARD_PATTERN,
@@ -759,6 +759,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
759759
&ranges::RANGE_ZIP_WITH_LEN,
760760
&ranges::REVERSED_EMPTY_RANGES,
761761
&redundant_clone::REDUNDANT_CLONE,
762+
&redundant_closure_call::REDUNDANT_CLOSURE_CALL,
762763
&redundant_field_names::REDUNDANT_FIELD_NAMES,
763764
&redundant_pub_crate::REDUNDANT_PUB_CRATE,
764765
&redundant_static_lifetimes::REDUNDANT_STATIC_LIFETIMES,
@@ -1018,6 +1019,8 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
10181019
store.register_early_pass(|| box int_plus_one::IntPlusOne);
10191020
store.register_early_pass(|| box formatting::Formatting);
10201021
store.register_early_pass(|| box misc_early::MiscEarlyLints);
1022+
store.register_early_pass(|| box redundant_closure_call::RedundantClosureCall);
1023+
store.register_late_pass(|| box redundant_closure_call::RedundantClosureCall);
10211024
store.register_early_pass(|| box returns::Return);
10221025
store.register_late_pass(|| box let_and_return::LetReturn);
10231026
store.register_early_pass(|| box collapsible_if::CollapsibleIf);
@@ -1359,7 +1362,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
13591362
LintId::of(&misc_early::DOUBLE_NEG),
13601363
LintId::of(&misc_early::DUPLICATE_UNDERSCORE_ARGUMENT),
13611364
LintId::of(&misc_early::MIXED_CASE_HEX_LITERALS),
1362-
LintId::of(&misc_early::REDUNDANT_CLOSURE_CALL),
13631365
LintId::of(&misc_early::REDUNDANT_PATTERN),
13641366
LintId::of(&misc_early::UNNEEDED_WILDCARD_PATTERN),
13651367
LintId::of(&misc_early::ZERO_PREFIXED_LITERAL),
@@ -1393,6 +1395,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
13931395
LintId::of(&ranges::RANGE_ZIP_WITH_LEN),
13941396
LintId::of(&ranges::REVERSED_EMPTY_RANGES),
13951397
LintId::of(&redundant_clone::REDUNDANT_CLONE),
1398+
LintId::of(&redundant_closure_call::REDUNDANT_CLOSURE_CALL),
13961399
LintId::of(&redundant_field_names::REDUNDANT_FIELD_NAMES),
13971400
LintId::of(&redundant_static_lifetimes::REDUNDANT_STATIC_LIFETIMES),
13981401
LintId::of(&reference::DEREF_ADDROF),
@@ -1593,7 +1596,6 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
15931596
LintId::of(&methods::UNNECESSARY_FILTER_MAP),
15941597
LintId::of(&methods::USELESS_ASREF),
15951598
LintId::of(&misc::SHORT_CIRCUIT_STATEMENT),
1596-
LintId::of(&misc_early::REDUNDANT_CLOSURE_CALL),
15971599
LintId::of(&misc_early::UNNEEDED_WILDCARD_PATTERN),
15981600
LintId::of(&misc_early::ZERO_PREFIXED_LITERAL),
15991601
LintId::of(&needless_bool::BOOL_COMPARISON),
@@ -1608,6 +1610,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
16081610
LintId::of(&precedence::PRECEDENCE),
16091611
LintId::of(&ptr_offset_with_cast::PTR_OFFSET_WITH_CAST),
16101612
LintId::of(&ranges::RANGE_ZIP_WITH_LEN),
1613+
LintId::of(&redundant_closure_call::REDUNDANT_CLOSURE_CALL),
16111614
LintId::of(&reference::DEREF_ADDROF),
16121615
LintId::of(&reference::REF_IN_DEREF),
16131616
LintId::of(&repeat_once::REPEAT_ONCE),

clippy_lints/src/misc_early.rs

Lines changed: 4 additions & 104 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,9 @@
1-
use crate::utils::{
2-
constants, snippet_opt, snippet_with_applicability, span_lint, span_lint_and_help, span_lint_and_sugg,
3-
span_lint_and_then,
4-
};
5-
use if_chain::if_chain;
1+
use crate::utils::{constants, snippet_opt, span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then};
62
use rustc_ast::ast::{
7-
BindingMode, Block, Expr, ExprKind, GenericParamKind, Generics, Lit, LitFloatType, LitIntType, LitKind, Mutability,
8-
NodeId, Pat, PatKind, StmtKind, UnOp,
3+
BindingMode, Expr, ExprKind, GenericParamKind, Generics, Lit, LitFloatType, LitIntType, LitKind, Mutability,
4+
NodeId, Pat, PatKind, UnOp,
95
};
10-
use rustc_ast::visit::{walk_expr, FnKind, Visitor};
6+
use rustc_ast::visit::FnKind;
117
use rustc_data_structures::fx::FxHashMap;
128
use rustc_errors::Applicability;
139
use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
@@ -70,28 +66,6 @@ declare_clippy_lint! {
7066
"function arguments having names which only differ by an underscore"
7167
}
7268

73-
declare_clippy_lint! {
74-
/// **What it does:** Detects closures called in the same expression where they
75-
/// are defined.
76-
///
77-
/// **Why is this bad?** It is unnecessarily adding to the expression's
78-
/// complexity.
79-
///
80-
/// **Known problems:** None.
81-
///
82-
/// **Example:**
83-
/// ```rust,ignore
84-
/// // Bad
85-
/// let a = (|| 42)()
86-
///
87-
/// // Good
88-
/// let a = 42
89-
/// ```
90-
pub REDUNDANT_CLOSURE_CALL,
91-
complexity,
92-
"throwaway closures called in the expression they are defined"
93-
}
94-
9569
declare_clippy_lint! {
9670
/// **What it does:** Detects expressions of the form `--x`.
9771
///
@@ -278,7 +252,6 @@ declare_clippy_lint! {
278252
declare_lint_pass!(MiscEarlyLints => [
279253
UNNEEDED_FIELD_PATTERN,
280254
DUPLICATE_UNDERSCORE_ARGUMENT,
281-
REDUNDANT_CLOSURE_CALL,
282255
DOUBLE_NEG,
283256
MIXED_CASE_HEX_LITERALS,
284257
UNSEPARATED_LITERAL_SUFFIX,
@@ -288,30 +261,6 @@ declare_lint_pass!(MiscEarlyLints => [
288261
UNNEEDED_WILDCARD_PATTERN,
289262
]);
290263

291-
// Used to find `return` statements or equivalents e.g., `?`
292-
struct ReturnVisitor {
293-
found_return: bool,
294-
}
295-
296-
impl ReturnVisitor {
297-
#[must_use]
298-
fn new() -> Self {
299-
Self { found_return: false }
300-
}
301-
}
302-
303-
impl<'ast> Visitor<'ast> for ReturnVisitor {
304-
fn visit_expr(&mut self, ex: &'ast Expr) {
305-
if let ExprKind::Ret(_) = ex.kind {
306-
self.found_return = true;
307-
} else if let ExprKind::Try(_) = ex.kind {
308-
self.found_return = true;
309-
}
310-
311-
walk_expr(self, ex)
312-
}
313-
}
314-
315264
impl EarlyLintPass for MiscEarlyLints {
316265
fn check_generics(&mut self, cx: &EarlyContext<'_>, gen: &Generics) {
317266
for param in &gen.params {
@@ -453,30 +402,6 @@ impl EarlyLintPass for MiscEarlyLints {
453402
return;
454403
}
455404
match expr.kind {
456-
ExprKind::Call(ref paren, _) => {
457-
if let ExprKind::Paren(ref closure) = paren.kind {
458-
if let ExprKind::Closure(_, _, _, ref decl, ref block, _) = closure.kind {
459-
let mut visitor = ReturnVisitor::new();
460-
visitor.visit_expr(block);
461-
if !visitor.found_return {
462-
span_lint_and_then(
463-
cx,
464-
REDUNDANT_CLOSURE_CALL,
465-
expr.span,
466-
"Try not to call a closure in the expression where it is declared.",
467-
|diag| {
468-
if decl.inputs.is_empty() {
469-
let mut app = Applicability::MachineApplicable;
470-
let hint =
471-
snippet_with_applicability(cx, block.span, "..", &mut app).into_owned();
472-
diag.span_suggestion(expr.span, "Try doing something like: ", hint, app);
473-
}
474-
},
475-
);
476-
}
477-
}
478-
}
479-
},
480405
ExprKind::Unary(UnOp::Neg, ref inner) => {
481406
if let ExprKind::Unary(UnOp::Neg, _) = inner.kind {
482407
span_lint(
@@ -491,31 +416,6 @@ impl EarlyLintPass for MiscEarlyLints {
491416
_ => (),
492417
}
493418
}
494-
495-
fn check_block(&mut self, cx: &EarlyContext<'_>, block: &Block) {
496-
for w in block.stmts.windows(2) {
497-
if_chain! {
498-
if let StmtKind::Local(ref local) = w[0].kind;
499-
if let Option::Some(ref t) = local.init;
500-
if let ExprKind::Closure(..) = t.kind;
501-
if let PatKind::Ident(_, ident, _) = local.pat.kind;
502-
if let StmtKind::Semi(ref second) = w[1].kind;
503-
if let ExprKind::Assign(_, ref call, _) = second.kind;
504-
if let ExprKind::Call(ref closure, _) = call.kind;
505-
if let ExprKind::Path(_, ref path) = closure.kind;
506-
then {
507-
if ident == path.segments[0].ident {
508-
span_lint(
509-
cx,
510-
REDUNDANT_CLOSURE_CALL,
511-
second.span,
512-
"Closure called just once immediately after it was declared",
513-
);
514-
}
515-
}
516-
}
517-
}
518-
}
519419
}
520420

521421
impl MiscEarlyLints {
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
use crate::utils::{snippet_with_applicability, span_lint, span_lint_and_then};
2+
use if_chain::if_chain;
3+
use rustc_ast::ast;
4+
use rustc_ast::visit as ast_visit;
5+
use rustc_ast::visit::Visitor as AstVisitor;
6+
use rustc_errors::Applicability;
7+
use rustc_hir as hir;
8+
use rustc_hir::intravisit as hir_visit;
9+
use rustc_hir::intravisit::Visitor as HirVisitor;
10+
use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
11+
use rustc_middle::hir::map::Map;
12+
use rustc_middle::lint::in_external_macro;
13+
use rustc_session::{declare_lint_pass, declare_tool_lint};
14+
15+
declare_clippy_lint! {
16+
/// **What it does:** Detects closures called in the same expression where they
17+
/// are defined.
18+
///
19+
/// **Why is this bad?** It is unnecessarily adding to the expression's
20+
/// complexity.
21+
///
22+
/// **Known problems:** None.
23+
///
24+
/// **Example:**
25+
/// ```rust,ignore
26+
/// // Bad
27+
/// let a = (|| 42)()
28+
///
29+
/// // Good
30+
/// let a = 42
31+
/// ```
32+
pub REDUNDANT_CLOSURE_CALL,
33+
complexity,
34+
"throwaway closures called in the expression they are defined"
35+
}
36+
37+
declare_lint_pass!(RedundantClosureCall => [REDUNDANT_CLOSURE_CALL]);
38+
39+
// Used to find `return` statements or equivalents e.g., `?`
40+
struct ReturnVisitor {
41+
found_return: bool,
42+
}
43+
44+
impl ReturnVisitor {
45+
#[must_use]
46+
fn new() -> Self {
47+
Self { found_return: false }
48+
}
49+
}
50+
51+
impl<'ast> ast_visit::Visitor<'ast> for ReturnVisitor {
52+
fn visit_expr(&mut self, ex: &'ast ast::Expr) {
53+
if let ast::ExprKind::Ret(_) = ex.kind {
54+
self.found_return = true;
55+
} else if let ast::ExprKind::Try(_) = ex.kind {
56+
self.found_return = true;
57+
}
58+
59+
ast_visit::walk_expr(self, ex)
60+
}
61+
}
62+
63+
impl EarlyLintPass for RedundantClosureCall {
64+
fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
65+
if in_external_macro(cx.sess(), expr.span) {
66+
return;
67+
}
68+
if_chain! {
69+
if let ast::ExprKind::Call(ref paren, _) = expr.kind;
70+
if let ast::ExprKind::Paren(ref closure) = paren.kind;
71+
if let ast::ExprKind::Closure(_, _, _, ref decl, ref block, _) = closure.kind;
72+
then {
73+
let mut visitor = ReturnVisitor::new();
74+
visitor.visit_expr(block);
75+
if !visitor.found_return {
76+
span_lint_and_then(
77+
cx,
78+
REDUNDANT_CLOSURE_CALL,
79+
expr.span,
80+
"try not to call a closure in the expression where it is declared.",
81+
|diag| {
82+
if decl.inputs.is_empty() {
83+
let mut app = Applicability::MachineApplicable;
84+
let hint =
85+
snippet_with_applicability(cx, block.span, "..", &mut app).into_owned();
86+
diag.span_suggestion(expr.span, "try doing something like", hint, app);
87+
}
88+
},
89+
);
90+
}
91+
}
92+
}
93+
}
94+
}
95+
96+
impl<'tcx> LateLintPass<'tcx> for RedundantClosureCall {
97+
fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx hir::Block<'_>) {
98+
fn count_closure_usage<'tcx>(block: &'tcx hir::Block<'_>, path: &'tcx hir::Path<'tcx>) -> usize {
99+
struct ClosureUsageCount<'tcx> {
100+
path: &'tcx hir::Path<'tcx>,
101+
count: usize,
102+
};
103+
impl<'tcx> hir_visit::Visitor<'tcx> for ClosureUsageCount<'tcx> {
104+
type Map = Map<'tcx>;
105+
106+
fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
107+
if_chain! {
108+
if let hir::ExprKind::Call(ref closure, _) = expr.kind;
109+
if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = closure.kind;
110+
if self.path.segments[0].ident == path.segments[0].ident
111+
&& self.path.res == path.res;
112+
then {
113+
self.count += 1;
114+
}
115+
}
116+
hir_visit::walk_expr(self, expr);
117+
}
118+
119+
fn nested_visit_map(&mut self) -> hir_visit::NestedVisitorMap<Self::Map> {
120+
hir_visit::NestedVisitorMap::None
121+
}
122+
};
123+
let mut closure_usage_count = ClosureUsageCount { path, count: 0 };
124+
closure_usage_count.visit_block(block);
125+
closure_usage_count.count
126+
}
127+
128+
for w in block.stmts.windows(2) {
129+
if_chain! {
130+
if let hir::StmtKind::Local(ref local) = w[0].kind;
131+
if let Option::Some(ref t) = local.init;
132+
if let hir::ExprKind::Closure(..) = t.kind;
133+
if let hir::PatKind::Binding(_, _, ident, _) = local.pat.kind;
134+
if let hir::StmtKind::Semi(ref second) = w[1].kind;
135+
if let hir::ExprKind::Assign(_, ref call, _) = second.kind;
136+
if let hir::ExprKind::Call(ref closure, _) = call.kind;
137+
if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = closure.kind;
138+
if ident == path.segments[0].ident;
139+
if count_closure_usage(block, path) == 1;
140+
then {
141+
span_lint(
142+
cx,
143+
REDUNDANT_CLOSURE_CALL,
144+
second.span,
145+
"closure called just once immediately after it was declared",
146+
);
147+
}
148+
}
149+
}
150+
}
151+
}

src/lintlist/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1835,7 +1835,7 @@ pub static ref ALL_LINTS: Vec<Lint> = vec![
18351835
group: "complexity",
18361836
desc: "throwaway closures called in the expression they are defined",
18371837
deprecation: None,
1838-
module: "misc_early",
1838+
module: "redundant_closure_call",
18391839
},
18401840
Lint {
18411841
name: "redundant_closure_for_method_calls",

0 commit comments

Comments
 (0)