|
| 1 | +use clippy_utils::diagnostics::span_lint_hir_and_then; |
| 2 | +use clippy_utils::is_def_id_trait_method; |
| 3 | +use clippy_utils::source::SpanRangeExt; |
| 4 | +use clippy_utils::usage::is_todo_unimplemented_stub; |
| 5 | +use rustc_errors::Applicability; |
| 6 | +use rustc_hir::intravisit::{FnKind, Visitor, walk_expr, walk_fn}; |
| 7 | +use rustc_hir::{ |
| 8 | + Body, Closure, ClosureKind, CoroutineDesugaring, CoroutineKind, Defaultness, Expr, ExprKind, FnDecl, IsAsync, Node, |
| 9 | + TraitItem, YieldSource, |
| 10 | +}; |
| 11 | +use rustc_lint::{LateContext, LateLintPass}; |
| 12 | +use rustc_middle::hir::nested_filter; |
| 13 | +use rustc_session::impl_lint_pass; |
| 14 | +use rustc_span::Span; |
| 15 | +use rustc_span::def_id::LocalDefId; |
| 16 | + |
| 17 | +declare_clippy_lint! { |
| 18 | + /// ### What it does |
| 19 | + /// Checks for trait function implementations that are declared `async` but have no `.await`s inside of them. |
| 20 | + /// |
| 21 | + /// ### Why is this bad? |
| 22 | + /// Async functions with no async code create computational overhead. |
| 23 | + /// Even though the trait requires the function to return a future, |
| 24 | + /// returning a `core::future::ready` with the result is more efficient. |
| 25 | + /// |
| 26 | + /// ### Example |
| 27 | + /// ```no_run |
| 28 | + /// impl AsyncTrait for Example { |
| 29 | + /// async fn get_random_number() -> i64 { |
| 30 | + /// 4 // Chosen by fair dice roll. Guaranteed to be random. |
| 31 | + /// } |
| 32 | + /// } |
| 33 | + /// ``` |
| 34 | + /// |
| 35 | + /// Use instead: |
| 36 | + /// ```no_run |
| 37 | + /// impl AsyncTrait for Example { |
| 38 | + /// fn get_random_number() -> impl Future<Output = i64> { |
| 39 | + /// core::future::ready(4) // Chosen by fair dice roll. Guaranteed to be random. |
| 40 | + /// } |
| 41 | + /// } |
| 42 | + /// |
| 43 | + /// ### Note |
| 44 | + /// An `async` block generates code that defers execution until the Future is polled. |
| 45 | + /// When using `core::future::ready` the code is executed immediately. |
| 46 | + /// ``` |
| 47 | + #[clippy::version = "1.94.0"] |
| 48 | + pub UNUSED_ASYNC_TRAIT_IMPL, |
| 49 | + pedantic, |
| 50 | + "finds async trait impl functions with no await statements" |
| 51 | +} |
| 52 | + |
| 53 | +pub struct UnusedAsyncTraitImpl; |
| 54 | + |
| 55 | +impl_lint_pass!(UnusedAsyncTraitImpl => [UNUSED_ASYNC_TRAIT_IMPL]); |
| 56 | + |
| 57 | +struct AsyncFnVisitor<'a, 'tcx> { |
| 58 | + cx: &'a LateContext<'tcx>, |
| 59 | + found_await: bool, |
| 60 | + async_depth: usize, |
| 61 | +} |
| 62 | + |
| 63 | +impl<'tcx> Visitor<'tcx> for AsyncFnVisitor<'_, 'tcx> { |
| 64 | + type NestedFilter = nested_filter::OnlyBodies; |
| 65 | + |
| 66 | + fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) { |
| 67 | + if let ExprKind::Yield(_, YieldSource::Await { .. }) = ex.kind |
| 68 | + && self.async_depth == 1 |
| 69 | + { |
| 70 | + self.found_await = true; |
| 71 | + } |
| 72 | + |
| 73 | + let is_async_block = matches!( |
| 74 | + ex.kind, |
| 75 | + ExprKind::Closure(Closure { |
| 76 | + kind: ClosureKind::Coroutine(CoroutineKind::Desugared(CoroutineDesugaring::Async, _)), |
| 77 | + .. |
| 78 | + }) |
| 79 | + ); |
| 80 | + |
| 81 | + if is_async_block { |
| 82 | + self.async_depth += 1; |
| 83 | + } |
| 84 | + |
| 85 | + walk_expr(self, ex); |
| 86 | + |
| 87 | + if is_async_block { |
| 88 | + self.async_depth -= 1; |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt { |
| 93 | + self.cx.tcx |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +impl<'tcx> LateLintPass<'tcx> for UnusedAsyncTraitImpl { |
| 98 | + fn check_fn( |
| 99 | + &mut self, |
| 100 | + cx: &LateContext<'tcx>, |
| 101 | + fn_kind: FnKind<'tcx>, |
| 102 | + fn_decl: &'tcx FnDecl<'tcx>, |
| 103 | + body: &Body<'tcx>, |
| 104 | + span: Span, |
| 105 | + def_id: LocalDefId, |
| 106 | + ) { |
| 107 | + if let IsAsync::Async(async_span) = fn_kind.asyncness() |
| 108 | + && !span.from_expansion() |
| 109 | + && is_def_id_trait_method(cx, def_id) |
| 110 | + && !is_default_trait_impl(cx, def_id) |
| 111 | + && !async_fn_contains_todo_unimplemented_macro(cx, body) |
| 112 | + { |
| 113 | + let mut visitor = AsyncFnVisitor { |
| 114 | + cx, |
| 115 | + found_await: false, |
| 116 | + async_depth: 0, |
| 117 | + }; |
| 118 | + walk_fn(&mut visitor, fn_kind, fn_decl, body.id(), def_id); |
| 119 | + if !visitor.found_await { |
| 120 | + span_lint_hir_and_then( |
| 121 | + cx, |
| 122 | + UNUSED_ASYNC_TRAIT_IMPL, |
| 123 | + cx.tcx.local_def_id_to_hir_id(def_id), |
| 124 | + span, |
| 125 | + "unused `async` for async trait impl function with no await statements", |
| 126 | + |diag| { |
| 127 | + if let Some(output_src) = fn_decl.output.span().get_source_text(cx) |
| 128 | + && let Some(body_src) = body.value.span.get_source_text(cx) |
| 129 | + { |
| 130 | + let output_str = output_src.as_str(); |
| 131 | + let body_str = body_src.as_str(); |
| 132 | + |
| 133 | + let sugg = vec![ |
| 134 | + (async_span, String::new()), |
| 135 | + (fn_decl.output.span(), format!("impl Future<Output = {output_str}>")), |
| 136 | + (body.value.span, format!("{{ core::future::ready({body_str}) }}")), |
| 137 | + ]; |
| 138 | + |
| 139 | + diag.help("a Future can be constructed from the return value with `core::future::ready`"); |
| 140 | + diag.multipart_suggestion( |
| 141 | + format!("consider removing the `async` from this function and returning `impl Future<Output = {output_str}>` instead"), |
| 142 | + sugg, |
| 143 | + Applicability::MachineApplicable |
| 144 | + ); |
| 145 | + } |
| 146 | + }, |
| 147 | + ); |
| 148 | + } |
| 149 | + } |
| 150 | + } |
| 151 | +} |
| 152 | + |
| 153 | +fn is_default_trait_impl(cx: &LateContext<'_>, def_id: LocalDefId) -> bool { |
| 154 | + matches!( |
| 155 | + cx.tcx.hir_node_by_def_id(def_id), |
| 156 | + Node::TraitItem(TraitItem { |
| 157 | + defaultness: Defaultness::Default { .. }, |
| 158 | + .. |
| 159 | + }) |
| 160 | + ) |
| 161 | +} |
| 162 | + |
| 163 | +fn async_fn_contains_todo_unimplemented_macro(cx: &LateContext<'_>, body: &Body<'_>) -> bool { |
| 164 | + if let ExprKind::Closure(closure) = body.value.kind |
| 165 | + && let ClosureKind::Coroutine(CoroutineKind::Desugared(CoroutineDesugaring::Async, _)) = closure.kind |
| 166 | + && let body = cx.tcx.hir_body(closure.body) |
| 167 | + && let ExprKind::Block(block, _) = body.value.kind |
| 168 | + && block.stmts.is_empty() |
| 169 | + && let Some(expr) = block.expr |
| 170 | + && let ExprKind::DropTemps(inner) = expr.kind |
| 171 | + { |
| 172 | + return is_todo_unimplemented_stub(cx, inner); |
| 173 | + } |
| 174 | + |
| 175 | + false |
| 176 | +} |
0 commit comments