Skip to content

Commit acdf43f

Browse files
committed
Auto merge of #7225 - InquisitivePenguin:unnessecary-async, r=llogiq
New lint: `unused_async` changelog: Adds a lint, `unused_async`, which checks for async functions with no await statements `unused_async` is a lint that reduces code smell and overhead by encouraging async functions to be refactored into synchronous functions. Fixes #7176 ### Examples ```rust async fn get_random_number() -> i64 { 4 // Chosen by fair dice roll. Guaranteed to be random. } ``` Could be written as: ```rust fn get_random_number() -> i64 { 4 // Chosen by fair dice roll. Guaranteed to be random. } ``` Something like this, however, should **not** be caught by clippy: ```rust #[async_trait] trait AsyncTrait { async fn foo(); } struct Bar; #[async_trait] impl AsyncTrait for Bar { async fn foo() { println!("bar"); } } ```
2 parents 44e0747 + 75ef9dc commit acdf43f

File tree

5 files changed

+125
-0
lines changed

5 files changed

+125
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2722,6 +2722,7 @@ Released 2018-09-13
27222722
[`unsound_collection_transmute`]: https://rust-lang.github.io/rust-clippy/master/index.html#unsound_collection_transmute
27232723
[`unstable_as_mut_slice`]: https://rust-lang.github.io/rust-clippy/master/index.html#unstable_as_mut_slice
27242724
[`unstable_as_slice`]: https://rust-lang.github.io/rust-clippy/master/index.html#unstable_as_slice
2725+
[`unused_async`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_async
27252726
[`unused_collect`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_collect
27262727
[`unused_io_amount`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_io_amount
27272728
[`unused_self`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_self

clippy_lints/src/lib.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,7 @@ mod unnecessary_sort_by;
364364
mod unnecessary_wraps;
365365
mod unnested_or_patterns;
366366
mod unsafe_removed_from_name;
367+
mod unused_async;
367368
mod unused_io_amount;
368369
mod unused_self;
369370
mod unused_unit;
@@ -961,6 +962,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
961962
unnecessary_wraps::UNNECESSARY_WRAPS,
962963
unnested_or_patterns::UNNESTED_OR_PATTERNS,
963964
unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME,
965+
unused_async::UNUSED_ASYNC,
964966
unused_io_amount::UNUSED_IO_AMOUNT,
965967
unused_self::UNUSED_SELF,
966968
unused_unit::UNUSED_UNIT,
@@ -1273,6 +1275,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
12731275
store.register_late_pass(|| box manual_map::ManualMap);
12741276
store.register_late_pass(move || box if_then_some_else_none::IfThenSomeElseNone::new(msrv));
12751277
store.register_early_pass(|| box bool_assert_comparison::BoolAssertComparison);
1278+
store.register_late_pass(|| box unused_async::UnusedAsync);
12761279

12771280
store.register_group(true, "clippy::restriction", Some("clippy_restriction"), vec![
12781281
LintId::of(arithmetic::FLOAT_ARITHMETIC),
@@ -1417,6 +1420,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
14171420
LintId::of(unit_types::LET_UNIT_VALUE),
14181421
LintId::of(unnecessary_wraps::UNNECESSARY_WRAPS),
14191422
LintId::of(unnested_or_patterns::UNNESTED_OR_PATTERNS),
1423+
LintId::of(unused_async::UNUSED_ASYNC),
14201424
LintId::of(unused_self::UNUSED_SELF),
14211425
LintId::of(wildcard_imports::ENUM_GLOB_USE),
14221426
LintId::of(wildcard_imports::WILDCARD_IMPORTS),

clippy_lints/src/unused_async.rs

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
use clippy_utils::diagnostics::span_lint_and_help;
2+
use rustc_hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor};
3+
use rustc_hir::{Body, Expr, ExprKind, FnDecl, FnHeader, HirId, IsAsync, Item, ItemKind, YieldSource};
4+
use rustc_lint::{LateContext, LateLintPass};
5+
use rustc_middle::hir::map::Map;
6+
use rustc_session::{declare_lint_pass, declare_tool_lint};
7+
use rustc_span::Span;
8+
9+
declare_clippy_lint! {
10+
/// **What it does:** Checks for functions that are declared `async` but have no `.await`s inside of them.
11+
///
12+
/// **Why is this bad?** Async functions with no async code create overhead, both mentally and computationally.
13+
/// Callers of async methods either need to be calling from an async function themselves or run it on an executor, both of which
14+
/// causes runtime overhead and hassle for the caller.
15+
///
16+
/// **Known problems:** None
17+
///
18+
/// **Example:**
19+
///
20+
/// ```rust
21+
/// // Bad
22+
/// async fn get_random_number() -> i64 {
23+
/// 4 // Chosen by fair dice roll. Guaranteed to be random.
24+
/// }
25+
/// let number_future = get_random_number();
26+
///
27+
/// // Good
28+
/// fn get_random_number_improved() -> i64 {
29+
/// 4 // Chosen by fair dice roll. Guaranteed to be random.
30+
/// }
31+
/// let number_future = async { get_random_number_improved() };
32+
/// ```
33+
pub UNUSED_ASYNC,
34+
pedantic,
35+
"finds async functions with no await statements"
36+
}
37+
38+
declare_lint_pass!(UnusedAsync => [UNUSED_ASYNC]);
39+
40+
struct AsyncFnVisitor<'a, 'tcx> {
41+
cx: &'a LateContext<'tcx>,
42+
found_await: bool,
43+
}
44+
45+
impl<'a, 'tcx> Visitor<'tcx> for AsyncFnVisitor<'a, 'tcx> {
46+
type Map = Map<'tcx>;
47+
48+
fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
49+
if let ExprKind::Yield(_, YieldSource::Await { .. }) = ex.kind {
50+
self.found_await = true;
51+
}
52+
walk_expr(self, ex);
53+
}
54+
55+
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
56+
NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
57+
}
58+
}
59+
60+
impl<'tcx> LateLintPass<'tcx> for UnusedAsync {
61+
fn check_item(&mut self, _: &LateContext<'tcx>, item: &'tcx Item<'tcx>) {
62+
if let ItemKind::Trait(..) = item.kind {
63+
return;
64+
}
65+
}
66+
fn check_fn(
67+
&mut self,
68+
cx: &LateContext<'tcx>,
69+
fn_kind: FnKind<'tcx>,
70+
fn_decl: &'tcx FnDecl<'tcx>,
71+
body: &Body<'tcx>,
72+
span: Span,
73+
hir_id: HirId,
74+
) {
75+
if let FnKind::ItemFn(_, _, FnHeader { asyncness, .. }, _) = &fn_kind {
76+
if matches!(asyncness, IsAsync::Async) {
77+
let mut visitor = AsyncFnVisitor { cx, found_await: false };
78+
walk_fn(&mut visitor, fn_kind, fn_decl, body.id(), span, hir_id);
79+
if !visitor.found_await {
80+
span_lint_and_help(
81+
cx,
82+
UNUSED_ASYNC,
83+
span,
84+
"unused `async` for function with no await statements",
85+
None,
86+
"consider removing the `async` from this function",
87+
);
88+
}
89+
}
90+
}
91+
}
92+
}

tests/ui/unused_async.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// edition:2018
2+
#![warn(clippy::unused_async)]
3+
4+
async fn foo() -> i32 {
5+
4
6+
}
7+
8+
async fn bar() -> i32 {
9+
foo().await
10+
}
11+
12+
fn main() {
13+
foo();
14+
bar();
15+
}

tests/ui/unused_async.stderr

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
error: unused `async` for function with no await statements
2+
--> $DIR/unused_async.rs:4:1
3+
|
4+
LL | / async fn foo() -> i32 {
5+
LL | | 4
6+
LL | | }
7+
| |_^
8+
|
9+
= note: `-D clippy::unused-async` implied by `-D warnings`
10+
= help: consider removing the `async` from this function
11+
12+
error: aborting due to previous error
13+

0 commit comments

Comments
 (0)