]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/manual_async_fn.rs
Rollup merge of #87910 - iago-lito:mark_unsafe_nonzero_arithmetics_as_const, r=joshtr...
[rust.git] / src / tools / clippy / clippy_lints / src / manual_async_fn.rs
1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::match_function_call;
3 use clippy_utils::paths::FUTURE_FROM_GENERATOR;
4 use clippy_utils::source::{position_before_rarrow, snippet_block, snippet_opt};
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir::intravisit::FnKind;
8 use rustc_hir::{
9     AsyncGeneratorKind, Block, Body, Expr, ExprKind, FnDecl, FnRetTy, GeneratorKind, GenericArg, GenericBound, HirId,
10     IsAsync, ItemKind, LifetimeName, TraitRef, Ty, TyKind, TypeBindingKind,
11 };
12 use rustc_lint::{LateContext, LateLintPass};
13 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 use rustc_span::{sym, Span};
15
16 declare_clippy_lint! {
17     /// ### What it does
18     /// It checks for manual implementations of `async` functions.
19     ///
20     /// ### Why is this bad?
21     /// It's more idiomatic to use the dedicated syntax.
22     ///
23     /// ### Example
24     /// ```rust
25     /// use std::future::Future;
26     ///
27     /// fn foo() -> impl Future<Output = i32> { async { 42 } }
28     /// ```
29     /// Use instead:
30     /// ```rust
31     /// async fn foo() -> i32 { 42 }
32     /// ```
33     pub MANUAL_ASYNC_FN,
34     style,
35     "manual implementations of `async` functions can be simplified using the dedicated syntax"
36 }
37
38 declare_lint_pass!(ManualAsyncFn => [MANUAL_ASYNC_FN]);
39
40 impl<'tcx> LateLintPass<'tcx> for ManualAsyncFn {
41     fn check_fn(
42         &mut self,
43         cx: &LateContext<'tcx>,
44         kind: FnKind<'tcx>,
45         decl: &'tcx FnDecl<'_>,
46         body: &'tcx Body<'_>,
47         span: Span,
48         _: HirId,
49     ) {
50         if_chain! {
51             if let Some(header) = kind.header();
52             if let IsAsync::NotAsync = header.asyncness;
53             // Check that this function returns `impl Future`
54             if let FnRetTy::Return(ret_ty) = decl.output;
55             if let Some((trait_ref, output_lifetimes)) = future_trait_ref(cx, ret_ty);
56             if let Some(output) = future_output_ty(trait_ref);
57             if captures_all_lifetimes(decl.inputs, &output_lifetimes);
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) = position_before_rarrow(&header_snip);
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>(
101     cx: &LateContext<'tcx>,
102     ty: &'tcx Ty<'tcx>,
103 ) -> Option<(&'tcx TraitRef<'tcx>, Vec<LifetimeName>)> {
104     if_chain! {
105         if let TyKind::OpaqueDef(item_id, bounds) = ty.kind;
106         let item = cx.tcx.hir().item(item_id);
107         if let ItemKind::OpaqueTy(opaque) = &item.kind;
108         if let Some(trait_ref) = opaque.bounds.iter().find_map(|bound| {
109             if let GenericBound::Trait(poly, _) = bound {
110                 Some(&poly.trait_ref)
111             } else {
112                 None
113             }
114         });
115         if trait_ref.trait_def_id() == cx.tcx.lang_items().future_trait();
116         then {
117             let output_lifetimes = bounds
118                 .iter()
119                 .filter_map(|bound| {
120                     if let GenericArg::Lifetime(lt) = bound {
121                         Some(lt.name)
122                     } else {
123                         None
124                     }
125                 })
126                 .collect();
127
128             return Some((trait_ref, output_lifetimes));
129         }
130     }
131
132     None
133 }
134
135 fn future_output_ty<'tcx>(trait_ref: &'tcx TraitRef<'tcx>) -> Option<&'tcx Ty<'tcx>> {
136     if_chain! {
137         if let Some(segment) = trait_ref.path.segments.last();
138         if let Some(args) = segment.args;
139         if args.bindings.len() == 1;
140         let binding = &args.bindings[0];
141         if binding.ident.name == sym::Output;
142         if let TypeBindingKind::Equality{ty: output} = binding.kind;
143         then {
144             return Some(output)
145         }
146     }
147
148     None
149 }
150
151 fn captures_all_lifetimes(inputs: &[Ty<'_>], output_lifetimes: &[LifetimeName]) -> bool {
152     let input_lifetimes: Vec<LifetimeName> = inputs
153         .iter()
154         .filter_map(|ty| {
155             if let TyKind::Rptr(lt, _) = ty.kind {
156                 Some(lt.name)
157             } else {
158                 None
159             }
160         })
161         .collect();
162
163     // The lint should trigger in one of these cases:
164     // - There are no input lifetimes
165     // - There's only one output lifetime bound using `+ '_`
166     // - All input lifetimes are explicitly bound to the output
167     input_lifetimes.is_empty()
168         || (output_lifetimes.len() == 1 && matches!(output_lifetimes[0], LifetimeName::Underscore))
169         || input_lifetimes
170             .iter()
171             .all(|in_lt| output_lifetimes.iter().any(|out_lt| in_lt == out_lt))
172 }
173
174 fn desugared_async_block<'tcx>(cx: &LateContext<'tcx>, block: &'tcx Block<'tcx>) -> Option<&'tcx Body<'tcx>> {
175     if_chain! {
176         if let Some(block_expr) = block.expr;
177         if let Some(args) = match_function_call(cx, block_expr, &FUTURE_FROM_GENERATOR);
178         if args.len() == 1;
179         if let Expr{kind: ExprKind::Closure(_, _, body_id, ..), ..} = args[0];
180         let closure_body = cx.tcx.hir().body(body_id);
181         if let Some(GeneratorKind::Async(AsyncGeneratorKind::Block)) = closure_body.generator_kind;
182         then {
183             return Some(closure_body);
184         }
185     }
186
187     None
188 }
189
190 fn suggested_ret(cx: &LateContext<'_>, output: &Ty<'_>) -> Option<(&'static str, String)> {
191     match output.kind {
192         TyKind::Tup(tys) if tys.is_empty() => {
193             let sugg = "remove the return type";
194             Some((sugg, "".into()))
195         },
196         _ => {
197             let sugg = "return the output of the future directly";
198             snippet_opt(cx, output.span).map(|snip| (sugg, format!(" -> {}", snip)))
199         },
200     }
201 }