Skip to content

Commit c6e0e84

Browse files
author
Jackson Lewis
committed
Implement unnecessary-async and UI test
1 parent 182a185 commit c6e0e84

File tree

4 files changed

+124
-0
lines changed

4 files changed

+124
-0
lines changed

clippy_lints/src/lib.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,7 @@ mod unnamed_address;
360360
mod unnecessary_self_imports;
361361
mod unnecessary_sort_by;
362362
mod unnecessary_wraps;
363+
mod unnecessary_async;
363364
mod unnested_or_patterns;
364365
mod unsafe_removed_from_name;
365366
mod unused_io_amount;
@@ -954,6 +955,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
954955
unit_types::UNIT_CMP,
955956
unnamed_address::FN_ADDRESS_COMPARISONS,
956957
unnamed_address::VTABLE_ADDRESS_COMPARISONS,
958+
unnecessary_async::UNNECESSARY_ASYNC,
957959
unnecessary_self_imports::UNNECESSARY_SELF_IMPORTS,
958960
unnecessary_sort_by::UNNECESSARY_SORT_BY,
959961
unnecessary_wraps::UNNECESSARY_WRAPS,
@@ -1271,6 +1273,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
12711273
store.register_late_pass(|| box manual_map::ManualMap);
12721274
store.register_late_pass(move || box if_then_some_else_none::IfThenSomeElseNone::new(msrv));
12731275
store.register_early_pass(|| box bool_assert_comparison::BoolAssertComparison);
1276+
store.register_late_pass(|| box unnecessary_async::UnnecessaryAsync);
12741277

12751278
store.register_group(true, "clippy::restriction", Some("clippy_restriction"), vec![
12761279
LintId::of(arithmetic::FLOAT_ARITHMETIC),
@@ -1412,6 +1415,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
14121415
LintId::of(unicode::NON_ASCII_LITERAL),
14131416
LintId::of(unicode::UNICODE_NOT_NFC),
14141417
LintId::of(unit_types::LET_UNIT_VALUE),
1418+
LintId::of(unnecessary_async::UNNECESSARY_ASYNC),
14151419
LintId::of(unnecessary_wraps::UNNECESSARY_WRAPS),
14161420
LintId::of(unnested_or_patterns::UNNESTED_OR_PATTERNS),
14171421
LintId::of(unused_self::UNUSED_SELF),

clippy_lints/src/unnecessary_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 UNNECESSARY_ASYNC,
34+
pedantic,
35+
"finds async functions with no await statements"
36+
}
37+
38+
declare_lint_pass!(UnnecessaryAsync => [UNNECESSARY_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 UnnecessaryAsync {
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+
UNNECESSARY_ASYNC,
83+
span,
84+
"unnecessary `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/unnecessary_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::unnecessary_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/unnecessary_async.stderr

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
error: unnecessary `async` for function with no await statements
2+
--> $DIR/unnecessary_async.rs:4:1
3+
|
4+
LL | / async fn foo() -> i32 {
5+
LL | | 4
6+
LL | | }
7+
| |_^
8+
|
9+
= note: `-D clippy::unnecessary-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)