1 use crate::utils::paths::FUTURE_FROM_GENERATOR;
2 use crate::utils::{match_function_call, snippet_block, snippet_opt, span_lint_and_then};
3 use if_chain::if_chain;
4 use rustc_errors::Applicability;
5 use rustc_hir::intravisit::FnKind;
7 AsyncGeneratorKind, Block, Body, Expr, ExprKind, FnDecl, FnRetTy, GeneratorKind, GenericBound, HirId, IsAsync,
8 ItemKind, TraitRef, Ty, TyKind, TypeBindingKind,
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 declare_clippy_lint! {
15 /// **What it does:** It checks for manual implementations of `async` functions.
17 /// **Why is this bad?** It's more idiomatic to use the dedicated syntax.
19 /// **Known problems:** None.
24 /// use std::future::Future;
26 /// fn foo() -> impl Future<Output = i32> { async { 42 } }
30 /// use std::future::Future;
32 /// async fn foo() -> i32 { 42 }
36 "manual implementations of `async` functions can be simplified using the dedicated syntax"
39 declare_lint_pass!(ManualAsyncFn => [MANUAL_ASYNC_FN]);
41 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ManualAsyncFn {
44 cx: &LateContext<'a, 'tcx>,
46 decl: &'tcx FnDecl<'_>,
52 if let Some(header) = kind.header();
53 if let IsAsync::NotAsync = header.asyncness;
54 // Check that this function returns `impl Future`
55 if let FnRetTy::Return(ret_ty) = decl.output;
56 if let Some(trait_ref) = future_trait_ref(cx, ret_ty);
57 if let Some(output) = future_output_ty(trait_ref);
58 // Check that the body of the function consists of one async block
59 if let ExprKind::Block(block, _) = body.value.kind;
60 if block.stmts.is_empty();
61 if let Some(closure_body) = desugared_async_block(cx, block);
63 let header_span = span.with_hi(ret_ty.span.hi());
69 "this function can be simplified using the `async fn` syntax",
72 if let Some(header_snip) = snippet_opt(cx, header_span);
73 if let Some(ret_pos) = header_snip.rfind("->");
74 if let Some((ret_sugg, ret_snip)) = suggested_ret(cx, output);
76 let help = format!("make the function `async` and {}", ret_sugg);
80 format!("async {}{}", &header_snip[..ret_pos], ret_snip),
81 Applicability::MachineApplicable
84 let body_snip = snippet_block(cx, closure_body.value.span, "..", Some(block.span));
87 "move the body of the async block to the enclosing function",
88 body_snip.to_string(),
89 Applicability::MachineApplicable
100 fn future_trait_ref<'tcx>(cx: &LateContext<'_, 'tcx>, ty: &'tcx Ty<'tcx>) -> Option<&'tcx TraitRef<'tcx>> {
102 if let TyKind::OpaqueDef(item_id, _) = ty.kind;
103 let item = cx.tcx.hir().item(item_id.id);
104 if let ItemKind::OpaqueTy(opaque) = &item.kind;
105 if opaque.bounds.len() == 1;
106 if let GenericBound::Trait(poly, _) = &opaque.bounds[0];
107 if poly.trait_ref.trait_def_id() == cx.tcx.lang_items().future_trait();
109 return Some(&poly.trait_ref);
116 fn future_output_ty<'tcx>(trait_ref: &'tcx TraitRef<'tcx>) -> Option<&'tcx Ty<'tcx>> {
118 if let Some(segment) = trait_ref.path.segments.last();
119 if let Some(args) = segment.args;
120 if args.bindings.len() == 1;
121 let binding = &args.bindings[0];
122 if binding.ident.as_str() == "Output";
123 if let TypeBindingKind::Equality{ty: output} = binding.kind;
132 fn desugared_async_block<'tcx>(cx: &LateContext<'_, 'tcx>, block: &'tcx Block<'tcx>) -> Option<&'tcx Body<'tcx>> {
134 if let Some(block_expr) = block.expr;
135 if let Some(args) = match_function_call(cx, block_expr, &FUTURE_FROM_GENERATOR);
137 if let Expr{kind: ExprKind::Closure(_, _, body_id, ..), ..} = args[0];
138 let closure_body = cx.tcx.hir().body(body_id);
139 if let Some(GeneratorKind::Async(AsyncGeneratorKind::Block)) = closure_body.generator_kind;
141 return Some(closure_body);
148 fn suggested_ret(cx: &LateContext<'_, '_>, output: &Ty<'_>) -> Option<(&'static str, String)> {
150 TyKind::Tup(tys) if tys.is_empty() => {
151 let sugg = "remove the return type";
152 Some((sugg, "".into()))
155 let sugg = "return the output of the future directly";
156 snippet_opt(cx, output.span).map(|snip| (sugg, format!("-> {}", snip)))