1 use crate::utils::{implements_trait, snippet, span_lint_and_then};
2 use rustc_errors::Applicability;
3 use rustc_hir::{AsyncGeneratorKind, Body, BodyId, ExprKind, GeneratorKind, QPath};
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
8 /// **What it does:** Checks for async blocks that yield values of types
9 /// that can themselves be awaited.
11 /// **Why is this bad?** An await is likely missing.
13 /// **Known problems:** None.
36 pub ASYNC_YIELDS_ASYNC,
38 "async blocks that return a type that can be awaited"
41 declare_lint_pass!(AsyncYieldsAsync => [ASYNC_YIELDS_ASYNC]);
43 impl<'tcx> LateLintPass<'tcx> for AsyncYieldsAsync {
44 fn check_body(&mut self, cx: &LateContext<'tcx>, body: &'tcx Body<'_>) {
45 use AsyncGeneratorKind::{Block, Closure};
46 // For functions, with explicitly defined types, don't warn.
47 // XXXkhuey maybe we should?
48 if let Some(GeneratorKind::Async(Block | Closure)) = body.generator_kind {
49 if let Some(future_trait_def_id) = cx.tcx.lang_items().future_trait() {
50 let body_id = BodyId {
51 hir_id: body.value.hir_id,
53 let def_id = cx.tcx.hir().body_owner_def_id(body_id);
54 let typeck_results = cx.tcx.typeck(def_id);
55 let expr_ty = typeck_results.expr_ty(&body.value);
57 if implements_trait(cx, expr_ty, future_trait_def_id, &[]) {
58 let return_expr_span = match &body.value.kind {
59 // XXXkhuey there has to be a better way.
60 ExprKind::Block(block, _) => block.expr.map(|e| e.span),
61 ExprKind::Path(QPath::Resolved(_, path)) => Some(path.span),
64 if let Some(return_expr_span) = return_expr_span {
69 "an async construct yields a type which is itself awaitable",
71 db.span_label(body.value.span, "outer async construct");
72 db.span_label(return_expr_span, "awaitable value not awaited");
75 "consider awaiting this value",
76 format!("{}.await", snippet(cx, return_expr_span, "..")),
77 Applicability::MaybeIncorrect,