Skip to content

Commit e8403a8

Browse files
committed
Auto merge of rust-lang#11200 - y21:issue9695, r=Jarcho
[`unused_async`]: don't lint if paths reference async fn without immediate call Fixes rust-lang#9695 Fixes rust-lang#9359 Clippy shouldn't lint unused `async` if there are paths referencing them if that path isn't the receiver of a function call, because that means that the function might be passed to some other function: ```rs async fn f() {} // No await statements, so unused at this point fn requires_fn_future<F: Future<Output = ()>>(_: fn() -> F) {} requires_fn_future(f); // `f`'s asyncness is actually not unused. ``` (This isn't limited to just passing the function as a parameter to another function, it could also first be stored in a variable and later passed to another function as an argument) This requires delaying the linting until post-crate and collecting path references to local async functions along the way. changelog: [`unused_async`]: don't lint if paths reference async fn that require asyncness
2 parents ea21ed7 + 482d5fa commit e8403a8

File tree

4 files changed

+115
-26
lines changed

4 files changed

+115
-26
lines changed

Diff for: clippy_lints/src/lib.rs

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

Diff for: clippy_lints/src/unused_async.rs

+86-22
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
use clippy_utils::diagnostics::span_lint_and_then;
1+
use clippy_utils::diagnostics::span_lint_hir_and_then;
22
use clippy_utils::is_def_id_trait_method;
3+
use rustc_hir::def::DefKind;
34
use rustc_hir::intravisit::{walk_body, walk_expr, walk_fn, FnKind, Visitor};
4-
use rustc_hir::{Body, Expr, ExprKind, FnDecl, YieldSource};
5+
use rustc_hir::{Body, Expr, ExprKind, FnDecl, Node, YieldSource};
56
use rustc_lint::{LateContext, LateLintPass};
67
use rustc_middle::hir::nested_filter;
7-
use rustc_session::{declare_lint_pass, declare_tool_lint};
8-
use rustc_span::def_id::LocalDefId;
8+
use rustc_session::{declare_tool_lint, impl_lint_pass};
9+
use rustc_span::def_id::{LocalDefId, LocalDefIdSet};
910
use rustc_span::Span;
1011

1112
declare_clippy_lint! {
@@ -38,7 +39,24 @@ declare_clippy_lint! {
3839
"finds async functions with no await statements"
3940
}
4041

41-
declare_lint_pass!(UnusedAsync => [UNUSED_ASYNC]);
42+
#[derive(Default)]
43+
pub struct UnusedAsync {
44+
/// Keeps track of async functions used as values (i.e. path expressions to async functions that
45+
/// are not immediately called)
46+
async_fns_as_value: LocalDefIdSet,
47+
/// Functions with unused `async`, linted post-crate after we've found all uses of local async
48+
/// functions
49+
unused_async_fns: Vec<UnusedAsyncFn>,
50+
}
51+
52+
#[derive(Copy, Clone)]
53+
struct UnusedAsyncFn {
54+
def_id: LocalDefId,
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,70 @@ 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-
}
119-
},
120-
);
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.push(UnusedAsyncFn {
126+
await_in_async_block: visitor.await_in_async_block,
127+
fn_span: span,
128+
def_id,
129+
});
121130
}
122131
}
123132
}
133+
134+
fn check_path(&mut self, cx: &LateContext<'tcx>, path: &rustc_hir::Path<'tcx>, hir_id: rustc_hir::HirId) {
135+
fn is_node_func_call(node: Node<'_>, expected_receiver: Span) -> bool {
136+
matches!(
137+
node,
138+
Node::Expr(Expr {
139+
kind: ExprKind::Call(Expr { span, .. }, _) | ExprKind::MethodCall(_, Expr { span, .. }, ..),
140+
..
141+
}) if *span == expected_receiver
142+
)
143+
}
144+
145+
// Find paths to local async functions that aren't immediately called.
146+
// E.g. `async fn f() {}; let x = f;`
147+
// Depending on how `x` is used, f's asyncness might be required despite not having any `await`
148+
// statements, so don't lint at all if there are any such paths.
149+
if let Some(def_id) = path.res.opt_def_id()
150+
&& let Some(local_def_id) = def_id.as_local()
151+
&& let Some(DefKind::Fn) = cx.tcx.opt_def_kind(def_id)
152+
&& cx.tcx.asyncness(def_id).is_async()
153+
&& !is_node_func_call(cx.tcx.hir().get_parent(hir_id), path.span)
154+
{
155+
self.async_fns_as_value.insert(local_def_id);
156+
}
157+
}
158+
159+
// After collecting all unused `async` and problematic paths to such functions,
160+
// lint those unused ones that didn't have any path expressions to them.
161+
fn check_crate_post(&mut self, cx: &LateContext<'tcx>) {
162+
let iter = self
163+
.unused_async_fns
164+
.iter()
165+
.filter(|UnusedAsyncFn { def_id, .. }| (!self.async_fns_as_value.contains(def_id)));
166+
167+
for fun in iter {
168+
span_lint_hir_and_then(
169+
cx,
170+
UNUSED_ASYNC,
171+
cx.tcx.local_def_id_to_hir_id(fun.def_id),
172+
fun.fn_span,
173+
"unused `async` for function with no await statements",
174+
|diag| {
175+
diag.help("consider removing the `async` from this function");
176+
177+
if let Some(span) = fun.await_in_async_block {
178+
diag.span_note(
179+
span,
180+
"`await` used in an async block, which does not require \
181+
the enclosing function to be `async`",
182+
);
183+
}
184+
},
185+
);
186+
}
187+
}
124188
}

Diff for: 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
}

Diff for: tests/ui/unused_async.stderr

+11-3
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,15 @@ LL | ready(()).await;
1717
= note: `-D clippy::unused-async` implied by `-D warnings`
1818

1919
error: unused `async` for function with no await statements
20-
--> $DIR/unused_async.rs:40:1
20+
--> $DIR/unused_async.rs:45:5
21+
|
22+
LL | async fn f3() {}
23+
| ^^^^^^^^^^^^^^^^
24+
|
25+
= help: consider removing the `async` from this function
26+
27+
error: unused `async` for function with no await statements
28+
--> $DIR/unused_async.rs:57:1
2129
|
2230
LL | / async fn foo() -> i32 {
2331
LL | | 4
@@ -27,7 +35,7 @@ LL | | }
2735
= 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)