Skip to content

Commit 0fecaf1

Browse files
committed
redundant_closure_call - extract lint from misc_early.rs, adapt to LatePass
1 parent c720d82 commit 0fecaf1

File tree

8 files changed

+196
-151
lines changed

8 files changed

+196
-151
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 & 128 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,15 @@
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};
1410
use rustc_middle::lint::in_external_macro;
1511
use rustc_session::{declare_lint_pass, declare_tool_lint};
1612
use rustc_span::source_map::Span;
17-
use rustc_span::symbol::Ident;
1813

1914
declare_clippy_lint! {
2015
/// **What it does:** Checks for structure field patterns bound to wildcards.
@@ -71,28 +66,6 @@ declare_clippy_lint! {
7166
"function arguments having names which only differ by an underscore"
7267
}
7368

74-
declare_clippy_lint! {
75-
/// **What it does:** Detects closures called in the same expression where they
76-
/// are defined.
77-
///
78-
/// **Why is this bad?** It is unnecessarily adding to the expression's
79-
/// complexity.
80-
///
81-
/// **Known problems:** None.
82-
///
83-
/// **Example:**
84-
/// ```rust,ignore
85-
/// // Bad
86-
/// let a = (|| 42)()
87-
///
88-
/// // Good
89-
/// let a = 42
90-
/// ```
91-
pub REDUNDANT_CLOSURE_CALL,
92-
complexity,
93-
"throwaway closures called in the expression they are defined"
94-
}
95-
9669
declare_clippy_lint! {
9770
/// **What it does:** Detects expressions of the form `--x`.
9871
///
@@ -279,7 +252,6 @@ declare_clippy_lint! {
279252
declare_lint_pass!(MiscEarlyLints => [
280253
UNNEEDED_FIELD_PATTERN,
281254
DUPLICATE_UNDERSCORE_ARGUMENT,
282-
REDUNDANT_CLOSURE_CALL,
283255
DOUBLE_NEG,
284256
MIXED_CASE_HEX_LITERALS,
285257
UNSEPARATED_LITERAL_SUFFIX,
@@ -289,30 +261,6 @@ declare_lint_pass!(MiscEarlyLints => [
289261
UNNEEDED_WILDCARD_PATTERN,
290262
]);
291263

292-
// Used to find `return` statements or equivalents e.g., `?`
293-
struct ReturnVisitor {
294-
found_return: bool,
295-
}
296-
297-
impl ReturnVisitor {
298-
#[must_use]
299-
fn new() -> Self {
300-
Self { found_return: false }
301-
}
302-
}
303-
304-
impl<'ast> Visitor<'ast> for ReturnVisitor {
305-
fn visit_expr(&mut self, ex: &'ast Expr) {
306-
if let ExprKind::Ret(_) = ex.kind {
307-
self.found_return = true;
308-
} else if let ExprKind::Try(_) = ex.kind {
309-
self.found_return = true;
310-
}
311-
312-
walk_expr(self, ex)
313-
}
314-
}
315-
316264
impl EarlyLintPass for MiscEarlyLints {
317265
fn check_generics(&mut self, cx: &EarlyContext<'_>, gen: &Generics) {
318266
for param in &gen.params {
@@ -454,30 +402,6 @@ impl EarlyLintPass for MiscEarlyLints {
454402
return;
455403
}
456404
match expr.kind {
457-
ExprKind::Call(ref paren, _) => {
458-
if let ExprKind::Paren(ref closure) = paren.kind {
459-
if let ExprKind::Closure(_, _, _, ref decl, ref block, _) = closure.kind {
460-
let mut visitor = ReturnVisitor::new();
461-
visitor.visit_expr(block);
462-
if !visitor.found_return {
463-
span_lint_and_then(
464-
cx,
465-
REDUNDANT_CLOSURE_CALL,
466-
expr.span,
467-
"Try not to call a closure in the expression where it is declared.",
468-
|diag| {
469-
if decl.inputs.is_empty() {
470-
let mut app = Applicability::MachineApplicable;
471-
let hint =
472-
snippet_with_applicability(cx, block.span, "..", &mut app).into_owned();
473-
diag.span_suggestion(expr.span, "Try doing something like: ", hint, app);
474-
}
475-
},
476-
);
477-
}
478-
}
479-
}
480-
},
481405
ExprKind::Unary(UnOp::Neg, ref inner) => {
482406
if let ExprKind::Unary(UnOp::Neg, _) = inner.kind {
483407
span_lint(
@@ -492,54 +416,6 @@ impl EarlyLintPass for MiscEarlyLints {
492416
_ => (),
493417
}
494418
}
495-
496-
fn check_block(&mut self, cx: &EarlyContext<'_>, block: &Block) {
497-
fn count_closure_usage(block: &Block, ident: &Ident) -> usize {
498-
struct ClosureUsageCount<'ast> {
499-
ident: &'ast Ident,
500-
count: usize,
501-
};
502-
impl<'ast> Visitor<'ast> for ClosureUsageCount<'ast> {
503-
fn visit_expr(&mut self, expr: &'ast Expr) {
504-
if_chain! {
505-
if let ExprKind::Call(ref closure, _) = expr.kind;
506-
if let ExprKind::Path(_, ref path) = closure.kind;
507-
if self.ident == &path.segments[0].ident;
508-
then {
509-
self.count += 1;
510-
}
511-
}
512-
walk_expr(self, expr);
513-
}
514-
}
515-
let mut closure_usage_count = ClosureUsageCount { ident, count: 0 };
516-
closure_usage_count.visit_block(block);
517-
closure_usage_count.count
518-
}
519-
520-
for w in block.stmts.windows(2) {
521-
if_chain! {
522-
if let StmtKind::Local(ref local) = w[0].kind;
523-
if let Option::Some(ref t) = local.init;
524-
if let ExprKind::Closure(..) = t.kind;
525-
if let PatKind::Ident(_, ident, _) = local.pat.kind;
526-
if let StmtKind::Semi(ref second) = w[1].kind;
527-
if let ExprKind::Assign(_, ref call, _) = second.kind;
528-
if let ExprKind::Call(ref closure, _) = call.kind;
529-
if let ExprKind::Path(_, ref path) = closure.kind;
530-
if ident == path.segments[0].ident;
531-
if count_closure_usage(block, &ident) == 1;
532-
then {
533-
span_lint(
534-
cx,
535-
REDUNDANT_CLOSURE_CALL,
536-
second.span,
537-
"Closure called just once immediately after it was declared",
538-
);
539-
}
540-
}
541-
}
542-
}
543419
}
544420

545421
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+
use rustc_span::symbol::Ident;
15+
16+
declare_clippy_lint! {
17+
/// **What it does:** Detects closures called in the same expression where they
18+
/// are defined.
19+
///
20+
/// **Why is this bad?** It is unnecessarily adding to the expression's
21+
/// complexity.
22+
///
23+
/// **Known problems:** None.
24+
///
25+
/// **Example:**
26+
/// ```rust,ignore
27+
/// // Bad
28+
/// let a = (|| 42)()
29+
///
30+
/// // Good
31+
/// let a = 42
32+
/// ```
33+
pub REDUNDANT_CLOSURE_CALL,
34+
complexity,
35+
"throwaway closures called in the expression they are defined"
36+
}
37+
38+
declare_lint_pass!(RedundantClosureCall => [REDUNDANT_CLOSURE_CALL]);
39+
40+
// Used to find `return` statements or equivalents e.g., `?`
41+
struct ReturnVisitor {
42+
found_return: bool,
43+
}
44+
45+
impl ReturnVisitor {
46+
#[must_use]
47+
fn new() -> Self {
48+
Self { found_return: false }
49+
}
50+
}
51+
52+
impl<'ast> ast_visit::Visitor<'ast> for ReturnVisitor {
53+
fn visit_expr(&mut self, ex: &'ast ast::Expr) {
54+
if let ast::ExprKind::Ret(_) = ex.kind {
55+
self.found_return = true;
56+
} else if let ast::ExprKind::Try(_) = ex.kind {
57+
self.found_return = true;
58+
}
59+
60+
ast_visit::walk_expr(self, ex)
61+
}
62+
}
63+
64+
impl EarlyLintPass for RedundantClosureCall {
65+
fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
66+
if in_external_macro(cx.sess(), expr.span) {
67+
return;
68+
}
69+
if_chain! {
70+
if let ast::ExprKind::Call(ref paren, _) = expr.kind;
71+
if let ast::ExprKind::Paren(ref closure) = paren.kind;
72+
if let ast::ExprKind::Closure(_, _, _, ref decl, ref block, _) = closure.kind;
73+
then {
74+
let mut visitor = ReturnVisitor::new();
75+
visitor.visit_expr(block);
76+
if !visitor.found_return {
77+
span_lint_and_then(
78+
cx,
79+
REDUNDANT_CLOSURE_CALL,
80+
expr.span,
81+
"Try not to call a closure in the expression where it is declared.",
82+
|diag| {
83+
if decl.inputs.is_empty() {
84+
let mut app = Applicability::MachineApplicable;
85+
let hint =
86+
snippet_with_applicability(cx, block.span, "..", &mut app).into_owned();
87+
diag.span_suggestion(expr.span, "Try doing something like: ", hint, app);
88+
}
89+
},
90+
);
91+
}
92+
}
93+
}
94+
}
95+
}
96+
97+
impl<'tcx> LateLintPass<'tcx> for RedundantClosureCall {
98+
fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx hir::Block<'_>) {
99+
fn count_closure_usage<'tcx>(block: &'tcx hir::Block<'_>, ident: &'tcx Ident) -> usize {
100+
struct ClosureUsageCount<'tcx> {
101+
ident: &'tcx Ident,
102+
count: usize,
103+
};
104+
impl<'tcx> hir_visit::Visitor<'tcx> for ClosureUsageCount<'tcx> {
105+
type Map = Map<'tcx>;
106+
107+
fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
108+
if_chain! {
109+
if let hir::ExprKind::Call(ref closure, _) = expr.kind;
110+
if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = closure.kind;
111+
if self.ident == &path.segments[0].ident;
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 { ident, 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, &ident) == 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+
}

0 commit comments

Comments
 (0)