]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/manual_async_fn.rs
Rollup merge of #74196 - GuillaumeGomez:auto-collapse-implementors, r=Manishearth
[rust.git] / src / tools / clippy / clippy_lints / src / manual_async_fn.rs
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;
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<'tcx> LateLintPass<'tcx> for ManualAsyncFn {
42     fn check_fn(
43         &mut self,
44         cx: &LateContext<'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 the `async fn` 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::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();
108         then {
109             return Some(&poly.trait_ref);
110         }
111     }
112
113     None
114 }
115
116 fn future_output_ty<'tcx>(trait_ref: &'tcx TraitRef<'tcx>) -> Option<&'tcx Ty<'tcx>> {
117     if_chain! {
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;
124         then {
125             return Some(output)
126         }
127     }
128
129     None
130 }
131
132 fn desugared_async_block<'tcx>(cx: &LateContext<'tcx>, block: &'tcx Block<'tcx>) -> Option<&'tcx Body<'tcx>> {
133     if_chain! {
134         if let Some(block_expr) = block.expr;
135         if let Some(args) = match_function_call(cx, block_expr, &FUTURE_FROM_GENERATOR);
136         if args.len() == 1;
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;
140         then {
141             return Some(closure_body);
142         }
143     }
144
145     None
146 }
147
148 fn suggested_ret(cx: &LateContext<'_>, output: &Ty<'_>) -> Option<(&'static str, String)> {
149     match output.kind {
150         TyKind::Tup(tys) if tys.is_empty() => {
151             let sugg = "remove the return type";
152             Some((sugg, "".into()))
153         },
154         _ => {
155             let sugg = "return the output of the future directly";
156             snippet_opt(cx, output.span).map(|snip| (sugg, format!("-> {}", snip)))
157         },
158     }
159 }