Skip to content

Commit 37b8366

Browse files
committed
[unused_async]: don't lint if paths reference async fn without call
1 parent 7c5095c commit 37b8366

File tree

4 files changed

+123
-33
lines changed

4 files changed

+123
-33
lines changed

clippy_lints/src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -911,7 +911,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
911911
store.register_late_pass(move |_| Box::new(if_then_some_else_none::IfThenSomeElseNone::new(msrv())));
912912
store.register_late_pass(|_| Box::new(bool_assert_comparison::BoolAssertComparison));
913913
store.register_early_pass(move || Box::new(module_style::ModStyle));
914-
store.register_late_pass(|_| Box::new(unused_async::UnusedAsync));
914+
store.register_late_pass(|_| Box::<unused_async::UnusedAsync>::default());
915915
let disallowed_types = conf.disallowed_types.clone();
916916
store.register_late_pass(move |_| Box::new(disallowed_types::DisallowedTypes::new(disallowed_types.clone())));
917917
let import_renames = conf.enforced_import_renames.clone();

clippy_lints/src/unused_async.rs

+84-19
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
use clippy_utils::diagnostics::span_lint_and_then;
22
use clippy_utils::is_def_id_trait_method;
3+
use rustc_data_structures::fx::FxHashMap;
4+
use rustc_hir::def::DefKind;
35
use rustc_hir::intravisit::{walk_body, walk_expr, walk_fn, FnKind, Visitor};
4-
use rustc_hir::{Body, Expr, ExprKind, FnDecl, YieldSource};
6+
use rustc_hir::{Body, Expr, ExprKind, FnDecl, Node, YieldSource};
57
use rustc_lint::{LateContext, LateLintPass};
68
use rustc_middle::hir::nested_filter;
7-
use rustc_session::{declare_lint_pass, declare_tool_lint};
8-
use rustc_span::def_id::LocalDefId;
9+
use rustc_session::{declare_tool_lint, impl_lint_pass};
10+
use rustc_span::def_id::{LocalDefId, LocalDefIdSet};
911
use rustc_span::Span;
1012

1113
declare_clippy_lint! {
@@ -38,7 +40,23 @@ declare_clippy_lint! {
3840
"finds async functions with no await statements"
3941
}
4042

41-
declare_lint_pass!(UnusedAsync => [UNUSED_ASYNC]);
43+
#[derive(Default)]
44+
pub struct UnusedAsync {
45+
/// Keeps track of async functions used as values (i.e. path expressions to async functions that
46+
/// are not immediately called)
47+
async_fns_as_value: LocalDefIdSet,
48+
/// Functions with unused `async`, linted post-crate after we've found all uses of local async
49+
/// functions
50+
unused_async_fns: FxHashMap<LocalDefId, UnusedAsyncFn>,
51+
}
52+
53+
#[derive(Copy, Clone)]
54+
struct UnusedAsyncFn {
55+
fn_span: Span,
56+
await_in_async_block: Option<Span>,
57+
}
58+
59+
impl_lint_pass!(UnusedAsync => [UNUSED_ASYNC]);
4260

4361
struct AsyncFnVisitor<'a, 'tcx> {
4462
cx: &'a LateContext<'tcx>,
@@ -101,24 +119,71 @@ impl<'tcx> LateLintPass<'tcx> for UnusedAsync {
101119
};
102120
walk_fn(&mut visitor, fn_kind, fn_decl, body.id(), def_id);
103121
if !visitor.found_await {
104-
span_lint_and_then(
105-
cx,
106-
UNUSED_ASYNC,
107-
span,
108-
"unused `async` for function with no await statements",
109-
|diag| {
110-
diag.help("consider removing the `async` from this function");
111-
112-
if let Some(span) = visitor.await_in_async_block {
113-
diag.span_note(
114-
span,
115-
"`await` used in an async block, which does not require \
116-
the enclosing function to be `async`",
117-
);
118-
}
122+
// Don't lint just yet, but store the necessary information for later.
123+
// The actual linting happens in `check_crate_post`, once we've found all
124+
// uses of local async functions that do require asyncness to pass typeck
125+
self.unused_async_fns.insert(
126+
def_id,
127+
UnusedAsyncFn {
128+
await_in_async_block: visitor.await_in_async_block,
129+
fn_span: span,
119130
},
120131
);
121132
}
122133
}
123134
}
135+
136+
fn check_path(&mut self, cx: &LateContext<'tcx>, path: &rustc_hir::Path<'tcx>, hir_id: rustc_hir::HirId) {
137+
fn is_node_func_call(node: Node<'_>, expected_receiver: Span) -> bool {
138+
matches!(
139+
node,
140+
Node::Expr(Expr {
141+
kind: ExprKind::Call(Expr { span, .. }, _) | ExprKind::MethodCall(_, Expr { span, .. }, ..),
142+
..
143+
}) if *span == expected_receiver
144+
)
145+
}
146+
147+
// Find paths to local async functions that aren't immediately called.
148+
// E.g. `async fn f() {}; let x = f;`
149+
// Depending on how `x` is used, f's asyncness might be required despite not having any `await`
150+
// statements, so don't lint at all if there are any such paths.
151+
if let Some(def_id) = path.res.opt_def_id()
152+
&& let Some(local_def_id) = def_id.as_local()
153+
&& let Some(DefKind::Fn) = cx.tcx.opt_def_kind(def_id)
154+
&& cx.tcx.asyncness(def_id).is_async()
155+
&& !is_node_func_call(cx.tcx.hir().get_parent(hir_id), path.span)
156+
{
157+
self.async_fns_as_value.insert(local_def_id);
158+
}
159+
}
160+
161+
// After collecting all unused `async` and problematic paths to such functions,
162+
// lint those unused ones that didn't have any path expressions to them.
163+
fn check_crate_post(&mut self, cx: &LateContext<'tcx>) {
164+
let iter = self
165+
.unused_async_fns
166+
.iter()
167+
.filter_map(|(did, item)| (!self.async_fns_as_value.contains(did)).then_some(item));
168+
169+
for fun in iter {
170+
span_lint_and_then(
171+
cx,
172+
UNUSED_ASYNC,
173+
fun.fn_span,
174+
"unused `async` for function with no await statements",
175+
|diag| {
176+
diag.help("consider removing the `async` from this function");
177+
178+
if let Some(span) = fun.await_in_async_block {
179+
diag.span_note(
180+
span,
181+
"`await` used in an async block, which does not require \
182+
the enclosing function to be `async`",
183+
);
184+
}
185+
},
186+
);
187+
}
188+
}
124189
}

tests/ui/unused_async.rs

+17
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,23 @@ mod issue10459 {
3737
}
3838
}
3939

40+
mod issue9695 {
41+
use std::future::Future;
42+
43+
async fn f() {}
44+
async fn f2() {}
45+
async fn f3() {}
46+
47+
fn needs_async_fn<F: Future<Output = ()>>(_: fn() -> F) {}
48+
49+
fn test() {
50+
let x = f;
51+
needs_async_fn(x); // async needed in f
52+
needs_async_fn(f2); // async needed in f2
53+
f3(); // async not needed in f3
54+
}
55+
}
56+
4057
async fn foo() -> i32 {
4158
4
4259
}

tests/ui/unused_async.stderr

+21-13
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,22 @@
1+
error: unused `async` for function with no await statements
2+
--> $DIR/unused_async.rs:45:5
3+
|
4+
LL | async fn f3() {}
5+
| ^^^^^^^^^^^^^^^^
6+
|
7+
= help: consider removing the `async` from this function
8+
= note: `-D clippy::unused-async` implied by `-D warnings`
9+
10+
error: unused `async` for function with no await statements
11+
--> $DIR/unused_async.rs:57:1
12+
|
13+
LL | / async fn foo() -> i32 {
14+
LL | | 4
15+
LL | | }
16+
| |_^
17+
|
18+
= help: consider removing the `async` from this function
19+
120
error: unused `async` for function with no await statements
221
--> $DIR/unused_async.rs:13:5
322
|
@@ -14,20 +33,9 @@ note: `await` used in an async block, which does not require the enclosing funct
1433
|
1534
LL | ready(()).await;
1635
| ^^^^^
17-
= note: `-D clippy::unused-async` implied by `-D warnings`
18-
19-
error: unused `async` for function with no await statements
20-
--> $DIR/unused_async.rs:40:1
21-
|
22-
LL | / async fn foo() -> i32 {
23-
LL | | 4
24-
LL | | }
25-
| |_^
26-
|
27-
= help: consider removing the `async` from this function
2836

2937
error: unused `async` for function with no await statements
30-
--> $DIR/unused_async.rs:51:5
38+
--> $DIR/unused_async.rs:68:5
3139
|
3240
LL | / async fn unused(&self) -> i32 {
3341
LL | | 1
@@ -36,5 +44,5 @@ LL | | }
3644
|
3745
= help: consider removing the `async` from this function
3846

39-
error: aborting due to 3 previous errors
47+
error: aborting due to 4 previous errors
4048

0 commit comments

Comments
 (0)