]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/manual_async_fn.rs
b4be3ecfd16211ed27c33d9ec7e117d46ca13a85
[rust.git] / clippy_lints / src / manual_async_fn.rs
1 use crate::utils::paths::{FUTURE_CORE, FUTURE_FROM_GENERATOR, FUTURE_STD};
2 use crate::utils::{match_function_call, match_path, 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;
6 use rustc_hir::{
7     AsyncGeneratorKind, Block, Body, Expr, ExprKind, FnDecl, FnRetTy, GeneratorKind, GenericBound, HirId, IsAsync,
8     ItemKind, TraitRef, Ty, TyKind, TypeBindingKind,
9 };
10 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 use rustc_span::Span;
13
14 declare_clippy_lint! {
15     /// **What it does:** It checks for manual implementations of `async` functions.
16     ///
17     /// **Why is this bad?** It's more idiomatic to use the dedicated syntax.
18     ///
19     /// **Known problems:** None.
20     ///
21     /// **Example:**
22     ///
23     /// ```rust
24     /// use std::future::Future;
25     ///
26     /// fn foo() -> impl Future<Output = i32> { async { 42 } }
27     /// ```
28     /// Use instead:
29     /// ```rust
30     /// use std::future::Future;
31     ///
32     /// async fn foo() -> i32 { 42 }
33     /// ```
34     pub MANUAL_ASYNC_FN,
35     style,
36     "manual implementations of `async` functions can be simplified using the dedicated syntax"
37 }
38
39 declare_lint_pass!(ManualAsyncFn => [MANUAL_ASYNC_FN]);
40
41 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ManualAsyncFn {
42     fn check_fn(
43         &mut self,
44         cx: &LateContext<'a, 'tcx>,
45         kind: FnKind<'tcx>,
46         decl: &'tcx FnDecl<'_>,
47         body: &'tcx Body<'_>,
48         span: Span,
49         _: HirId,
50     ) {
51         if_chain! {
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);
62             then {
63                 let header_span = span.with_hi(ret_ty.span.hi());
64
65                 span_lint_and_then(
66                     cx,
67                     MANUAL_ASYNC_FN,
68                     header_span,
69                     "this function can be simplified using async syntax",
70                     |diag| {
71                         if_chain! {
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);
75                             then {
76                                 let help = format!("make the function `async` and {}", ret_sugg);
77                                 diag.span_suggestion(
78                                     header_span,
79                                     &help,
80                                     format!("async {}{}", &header_snip[..ret_pos], ret_snip),
81                                     Applicability::MachineApplicable
82                                 );
83
84                                 let body_snip = snippet_block(cx, closure_body.value.span, "..", Some(block.span));
85                                 diag.span_suggestion(
86                                     block.span,
87                                     "move the body of the async block to the enclosing function",
88                                     body_snip.to_string(),
89                                     Applicability::MachineApplicable
90                                 );
91                             }
92                         }
93                     },
94                 );
95             }
96         }
97     }
98 }
99
100 fn future_trait_ref<'tcx>(cx: &LateContext<'_, 'tcx>, ty: &'tcx Ty<'tcx>) -> Option<&'tcx TraitRef<'tcx>> {
101     if_chain! {
102         if let TyKind::Def(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         let path = poly.trait_ref.path;
108         if match_path(&path, &FUTURE_CORE) || match_path(&path, &FUTURE_STD);
109         then {
110             return Some(&poly.trait_ref);
111         }
112     }
113
114     None
115 }
116
117 fn future_output_ty<'tcx>(trait_ref: &'tcx TraitRef<'tcx>) -> Option<&'tcx Ty<'tcx>> {
118     if_chain! {
119         if let Some(segment) = trait_ref.path.segments.last();
120         if let Some(args) = segment.args;
121         if args.bindings.len() == 1;
122         let binding = &args.bindings[0];
123         if binding.ident.as_str() == "Output";
124         if let TypeBindingKind::Equality{ty: output} = binding.kind;
125         then {
126             return Some(output)
127         }
128     }
129
130     None
131 }
132
133 fn desugared_async_block<'tcx>(cx: &LateContext<'_, 'tcx>, block: &'tcx Block<'tcx>) -> Option<&'tcx Body<'tcx>> {
134     if_chain! {
135         if let Some(block_expr) = block.expr;
136         if let Some(args) = match_function_call(cx, block_expr, &FUTURE_FROM_GENERATOR);
137         if args.len() == 1;
138         if let Expr{kind: ExprKind::Closure(_, _, body_id, ..), ..} = args[0];
139         let closure_body = cx.tcx.hir().body(body_id);
140         if let Some(GeneratorKind::Async(AsyncGeneratorKind::Block)) = closure_body.generator_kind;
141         then {
142             return Some(closure_body);
143         }
144     }
145
146     None
147 }
148
149 fn suggested_ret(cx: &LateContext<'_, '_>, output: &Ty<'_>) -> Option<(&'static str, String)> {
150     match output.kind {
151         TyKind::Tup(tys) if tys.is_empty() => {
152             let sugg = "remove the return type";
153             Some((sugg, "".into()))
154         },
155         _ => {
156             let sugg = "return the output of the future directly";
157             snippet_opt(cx, output.span).map(|snip| (sugg, format!("-> {}", snip)))
158         },
159     }
160 }