1 use clippy_utils
::diagnostics
::span_lint_and_help
;
2 use rustc_hir
::intravisit
::{walk_expr, walk_fn, FnKind, Visitor}
;
3 use rustc_hir
::{Body, Expr, ExprKind, FnDecl, FnHeader, HirId, IsAsync, YieldSource}
;
4 use rustc_lint
::{LateContext, LateLintPass}
;
5 use rustc_middle
::hir
::nested_filter
;
6 use rustc_session
::{declare_lint_pass, declare_tool_lint}
;
11 /// Checks for functions that are declared `async` but have no `.await`s inside of them.
13 /// ### Why is this bad?
14 /// Async functions with no async code create overhead, both mentally and computationally.
15 /// Callers of async methods either need to be calling from an async function themselves or run it on an executor, both of which
16 /// causes runtime overhead and hassle for the caller.
21 /// async fn get_random_number() -> i64 {
22 /// 4 // Chosen by fair dice roll. Guaranteed to be random.
24 /// let number_future = get_random_number();
27 /// fn get_random_number_improved() -> i64 {
28 /// 4 // Chosen by fair dice roll. Guaranteed to be random.
30 /// let number_future = async { get_random_number_improved() };
32 #[clippy::version = "1.54.0"]
35 "finds async functions with no await statements"
38 declare_lint_pass
!(UnusedAsync
=> [UNUSED_ASYNC
]);
40 struct AsyncFnVisitor
<'a
, 'tcx
> {
41 cx
: &'a LateContext
<'tcx
>,
45 impl<'a
, 'tcx
> Visitor
<'tcx
> for AsyncFnVisitor
<'a
, 'tcx
> {
46 type NestedFilter
= nested_filter
::OnlyBodies
;
48 fn visit_expr(&mut self, ex
: &'tcx Expr
<'tcx
>) {
49 if let ExprKind
::Yield(_
, YieldSource
::Await { .. }
) = ex
.kind
{
50 self.found_await
= true;
55 fn nested_visit_map(&mut self) -> Self::Map
{
60 impl<'tcx
> LateLintPass
<'tcx
> for UnusedAsync
{
63 cx
: &LateContext
<'tcx
>,
64 fn_kind
: FnKind
<'tcx
>,
65 fn_decl
: &'tcx FnDecl
<'tcx
>,
70 if let FnKind
::ItemFn(_
, _
, FnHeader { asyncness, .. }
) = &fn_kind
{
71 if matches
!(asyncness
, IsAsync
::Async
) {
72 let mut visitor
= AsyncFnVisitor { cx, found_await: false }
;
73 walk_fn(&mut visitor
, fn_kind
, fn_decl
, body
.id(), span
, hir_id
);
74 if !visitor
.found_await
{
79 "unused `async` for function with no await statements",
81 "consider removing the `async` from this function",