]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/closure.rs
Auto merge of #101361 - Dylan-DPC:rollup-xj1syld, r=Dylan-DPC
[rust.git] / compiler / rustc_typeck / src / check / closure.rs
1 //! Code for type-checking closure expressions.
2
3 use super::{check_fn, Expectation, FnCtxt, GeneratorTypes};
4
5 use crate::astconv::AstConv;
6 use crate::rustc_middle::ty::subst::Subst;
7 use rustc_hir as hir;
8 use rustc_hir::def_id::DefId;
9 use rustc_hir::lang_items::LangItem;
10 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
11 use rustc_infer::infer::LateBoundRegionConversionTime;
12 use rustc_infer::infer::{InferOk, InferResult};
13 use rustc_middle::ty::subst::InternalSubsts;
14 use rustc_middle::ty::visit::TypeVisitable;
15 use rustc_middle::ty::{self, Ty};
16 use rustc_span::source_map::Span;
17 use rustc_target::spec::abi::Abi;
18 use rustc_trait_selection::traits::error_reporting::ArgKind;
19 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
20 use std::cmp;
21 use std::iter;
22
23 /// What signature do we *expect* the closure to have from context?
24 #[derive(Debug)]
25 struct ExpectedSig<'tcx> {
26     /// Span that gave us this expectation, if we know that.
27     cause_span: Option<Span>,
28     sig: ty::PolyFnSig<'tcx>,
29 }
30
31 struct ClosureSignatures<'tcx> {
32     bound_sig: ty::PolyFnSig<'tcx>,
33     liberated_sig: ty::FnSig<'tcx>,
34 }
35
36 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
37     #[instrument(skip(self, expr, _capture, decl, body_id), level = "debug")]
38     pub fn check_expr_closure(
39         &self,
40         expr: &hir::Expr<'_>,
41         _capture: hir::CaptureBy,
42         decl: &'tcx hir::FnDecl<'tcx>,
43         body_id: hir::BodyId,
44         gen: Option<hir::Movability>,
45         expected: Expectation<'tcx>,
46     ) -> Ty<'tcx> {
47         trace!("decl = {:#?}", decl);
48         trace!("expr = {:#?}", expr);
49
50         // It's always helpful for inference if we know the kind of
51         // closure sooner rather than later, so first examine the expected
52         // type, and see if can glean a closure kind from there.
53         let (expected_sig, expected_kind) = match expected.to_option(self) {
54             Some(ty) => self.deduce_expectations_from_expected_type(ty),
55             None => (None, None),
56         };
57         let body = self.tcx.hir().body(body_id);
58         self.check_closure(expr, expected_kind, decl, body, gen, expected_sig)
59     }
60
61     #[instrument(skip(self, expr, body, decl), level = "debug", ret)]
62     fn check_closure(
63         &self,
64         expr: &hir::Expr<'_>,
65         opt_kind: Option<ty::ClosureKind>,
66         decl: &'tcx hir::FnDecl<'tcx>,
67         body: &'tcx hir::Body<'tcx>,
68         gen: Option<hir::Movability>,
69         expected_sig: Option<ExpectedSig<'tcx>>,
70     ) -> Ty<'tcx> {
71         trace!("decl = {:#?}", decl);
72         let expr_def_id = self.tcx.hir().local_def_id(expr.hir_id);
73         debug!(?expr_def_id);
74
75         let ClosureSignatures { bound_sig, liberated_sig } =
76             self.sig_of_closure(expr.hir_id, expr_def_id.to_def_id(), decl, body, expected_sig);
77
78         debug!(?bound_sig, ?liberated_sig);
79
80         let return_type_pre_known = !liberated_sig.output().is_ty_infer();
81
82         let generator_types = check_fn(
83             self,
84             self.param_env.without_const(),
85             liberated_sig,
86             decl,
87             expr.hir_id,
88             body,
89             gen,
90             return_type_pre_known,
91         )
92         .1;
93
94         let parent_substs = InternalSubsts::identity_for_item(
95             self.tcx,
96             self.tcx.typeck_root_def_id(expr_def_id.to_def_id()),
97         );
98
99         let tupled_upvars_ty = self.next_ty_var(TypeVariableOrigin {
100             kind: TypeVariableOriginKind::ClosureSynthetic,
101             span: self.tcx.hir().span(expr.hir_id),
102         });
103
104         if let Some(GeneratorTypes { resume_ty, yield_ty, interior, movability }) = generator_types
105         {
106             let generator_substs = ty::GeneratorSubsts::new(
107                 self.tcx,
108                 ty::GeneratorSubstsParts {
109                     parent_substs,
110                     resume_ty,
111                     yield_ty,
112                     return_ty: liberated_sig.output(),
113                     witness: interior,
114                     tupled_upvars_ty,
115                 },
116             );
117
118             return self.tcx.mk_generator(
119                 expr_def_id.to_def_id(),
120                 generator_substs.substs,
121                 movability,
122             );
123         }
124
125         // Tuple up the arguments and insert the resulting function type into
126         // the `closures` table.
127         let sig = bound_sig.map_bound(|sig| {
128             self.tcx.mk_fn_sig(
129                 iter::once(self.tcx.intern_tup(sig.inputs())),
130                 sig.output(),
131                 sig.c_variadic,
132                 sig.unsafety,
133                 sig.abi,
134             )
135         });
136
137         debug!(?sig, ?opt_kind);
138
139         let closure_kind_ty = match opt_kind {
140             Some(kind) => kind.to_ty(self.tcx),
141
142             // Create a type variable (for now) to represent the closure kind.
143             // It will be unified during the upvar inference phase (`upvar.rs`)
144             None => self.next_ty_var(TypeVariableOrigin {
145                 // FIXME(eddyb) distinguish closure kind inference variables from the rest.
146                 kind: TypeVariableOriginKind::ClosureSynthetic,
147                 span: expr.span,
148             }),
149         };
150
151         let closure_substs = ty::ClosureSubsts::new(
152             self.tcx,
153             ty::ClosureSubstsParts {
154                 parent_substs,
155                 closure_kind_ty,
156                 closure_sig_as_fn_ptr_ty: self.tcx.mk_fn_ptr(sig),
157                 tupled_upvars_ty,
158             },
159         );
160
161         self.tcx.mk_closure(expr_def_id.to_def_id(), closure_substs.substs)
162     }
163
164     /// Given the expected type, figures out what it can about this closure we
165     /// are about to type check:
166     #[instrument(skip(self), level = "debug")]
167     fn deduce_expectations_from_expected_type(
168         &self,
169         expected_ty: Ty<'tcx>,
170     ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
171         match *expected_ty.kind() {
172             ty::Opaque(def_id, substs) => {
173                 let bounds = self.tcx.bound_explicit_item_bounds(def_id);
174                 let sig = bounds
175                     .transpose_iter()
176                     .map(|e| e.map_bound(|e| *e).transpose_tuple2())
177                     .find_map(|(pred, span)| match pred.0.kind().skip_binder() {
178                         ty::PredicateKind::Projection(proj_predicate) => self
179                             .deduce_sig_from_projection(
180                                 Some(span.0),
181                                 pred.0
182                                     .kind()
183                                     .rebind(pred.rebind(proj_predicate).subst(self.tcx, substs)),
184                             ),
185                         _ => None,
186                     });
187
188                 let kind = bounds
189                     .transpose_iter()
190                     .map(|e| e.map_bound(|e| *e).transpose_tuple2())
191                     .filter_map(|(pred, _)| match pred.0.kind().skip_binder() {
192                         ty::PredicateKind::Trait(tp) => {
193                             self.tcx.fn_trait_kind_from_lang_item(tp.def_id())
194                         }
195                         _ => None,
196                     })
197                     .fold(None, |best, cur| Some(best.map_or(cur, |best| cmp::min(best, cur))));
198                 trace!(?sig, ?kind);
199                 (sig, kind)
200             }
201             ty::Dynamic(ref object_type, ..) => {
202                 let sig = object_type.projection_bounds().find_map(|pb| {
203                     let pb = pb.with_self_ty(self.tcx, self.tcx.types.trait_object_dummy_self);
204                     self.deduce_sig_from_projection(None, pb)
205                 });
206                 let kind = object_type
207                     .principal_def_id()
208                     .and_then(|did| self.tcx.fn_trait_kind_from_lang_item(did));
209                 (sig, kind)
210             }
211             ty::Infer(ty::TyVar(vid)) => self.deduce_expectations_from_obligations(vid),
212             ty::FnPtr(sig) => {
213                 let expected_sig = ExpectedSig { cause_span: None, sig };
214                 (Some(expected_sig), Some(ty::ClosureKind::Fn))
215             }
216             _ => (None, None),
217         }
218     }
219
220     fn deduce_expectations_from_obligations(
221         &self,
222         expected_vid: ty::TyVid,
223     ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
224         let expected_sig =
225             self.obligations_for_self_ty(expected_vid).find_map(|(_, obligation)| {
226                 debug!(?obligation.predicate);
227
228                 let bound_predicate = obligation.predicate.kind();
229                 if let ty::PredicateKind::Projection(proj_predicate) =
230                     obligation.predicate.kind().skip_binder()
231                 {
232                     // Given a Projection predicate, we can potentially infer
233                     // the complete signature.
234                     self.deduce_sig_from_projection(
235                         Some(obligation.cause.span),
236                         bound_predicate.rebind(proj_predicate),
237                     )
238                 } else {
239                     None
240                 }
241             });
242
243         // Even if we can't infer the full signature, we may be able to
244         // infer the kind. This can occur when we elaborate a predicate
245         // like `F : Fn<A>`. Note that due to subtyping we could encounter
246         // many viable options, so pick the most restrictive.
247         let expected_kind = self
248             .obligations_for_self_ty(expected_vid)
249             .filter_map(|(tr, _)| self.tcx.fn_trait_kind_from_lang_item(tr.def_id()))
250             .fold(None, |best, cur| Some(best.map_or(cur, |best| cmp::min(best, cur))));
251
252         (expected_sig, expected_kind)
253     }
254
255     /// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce
256     /// everything we need to know about a closure or generator.
257     ///
258     /// The `cause_span` should be the span that caused us to
259     /// have this expected signature, or `None` if we can't readily
260     /// know that.
261     #[instrument(level = "debug", skip(self, cause_span), ret)]
262     fn deduce_sig_from_projection(
263         &self,
264         cause_span: Option<Span>,
265         projection: ty::PolyProjectionPredicate<'tcx>,
266     ) -> Option<ExpectedSig<'tcx>> {
267         let tcx = self.tcx;
268
269         let trait_def_id = projection.trait_def_id(tcx);
270
271         let is_fn = tcx.fn_trait_kind_from_lang_item(trait_def_id).is_some();
272         let gen_trait = tcx.require_lang_item(LangItem::Generator, cause_span);
273         let is_gen = gen_trait == trait_def_id;
274         if !is_fn && !is_gen {
275             debug!("not fn or generator");
276             return None;
277         }
278
279         if is_gen {
280             // Check that we deduce the signature from the `<_ as std::ops::Generator>::Return`
281             // associated item and not yield.
282             let return_assoc_item = self.tcx.associated_item_def_ids(gen_trait)[1];
283             if return_assoc_item != projection.projection_def_id() {
284                 debug!("not return assoc item of generator");
285                 return None;
286             }
287         }
288
289         let input_tys = if is_fn {
290             let arg_param_ty = projection.skip_binder().projection_ty.substs.type_at(1);
291             let arg_param_ty = self.resolve_vars_if_possible(arg_param_ty);
292             debug!(?arg_param_ty);
293
294             match arg_param_ty.kind() {
295                 &ty::Tuple(tys) => tys,
296                 _ => return None,
297             }
298         } else {
299             // Generators with a `()` resume type may be defined with 0 or 1 explicit arguments,
300             // else they must have exactly 1 argument. For now though, just give up in this case.
301             return None;
302         };
303
304         // Since this is a return parameter type it is safe to unwrap.
305         let ret_param_ty = projection.skip_binder().term.ty().unwrap();
306         let ret_param_ty = self.resolve_vars_if_possible(ret_param_ty);
307         debug!(?ret_param_ty);
308
309         let sig = projection.rebind(self.tcx.mk_fn_sig(
310             input_tys.iter(),
311             ret_param_ty,
312             false,
313             hir::Unsafety::Normal,
314             Abi::Rust,
315         ));
316
317         Some(ExpectedSig { cause_span, sig })
318     }
319
320     fn sig_of_closure(
321         &self,
322         hir_id: hir::HirId,
323         expr_def_id: DefId,
324         decl: &hir::FnDecl<'_>,
325         body: &hir::Body<'_>,
326         expected_sig: Option<ExpectedSig<'tcx>>,
327     ) -> ClosureSignatures<'tcx> {
328         if let Some(e) = expected_sig {
329             self.sig_of_closure_with_expectation(hir_id, expr_def_id, decl, body, e)
330         } else {
331             self.sig_of_closure_no_expectation(hir_id, expr_def_id, decl, body)
332         }
333     }
334
335     /// If there is no expected signature, then we will convert the
336     /// types that the user gave into a signature.
337     #[instrument(skip(self, hir_id, expr_def_id, decl, body), level = "debug")]
338     fn sig_of_closure_no_expectation(
339         &self,
340         hir_id: hir::HirId,
341         expr_def_id: DefId,
342         decl: &hir::FnDecl<'_>,
343         body: &hir::Body<'_>,
344     ) -> ClosureSignatures<'tcx> {
345         let bound_sig = self.supplied_sig_of_closure(hir_id, expr_def_id, decl, body);
346
347         self.closure_sigs(expr_def_id, body, bound_sig)
348     }
349
350     /// Invoked to compute the signature of a closure expression. This
351     /// combines any user-provided type annotations (e.g., `|x: u32|
352     /// -> u32 { .. }`) with the expected signature.
353     ///
354     /// The approach is as follows:
355     ///
356     /// - Let `S` be the (higher-ranked) signature that we derive from the user's annotations.
357     /// - Let `E` be the (higher-ranked) signature that we derive from the expectations, if any.
358     ///   - If we have no expectation `E`, then the signature of the closure is `S`.
359     ///   - Otherwise, the signature of the closure is E. Moreover:
360     ///     - Skolemize the late-bound regions in `E`, yielding `E'`.
361     ///     - Instantiate all the late-bound regions bound in the closure within `S`
362     ///       with fresh (existential) variables, yielding `S'`
363     ///     - Require that `E' = S'`
364     ///       - We could use some kind of subtyping relationship here,
365     ///         I imagine, but equality is easier and works fine for
366     ///         our purposes.
367     ///
368     /// The key intuition here is that the user's types must be valid
369     /// from "the inside" of the closure, but the expectation
370     /// ultimately drives the overall signature.
371     ///
372     /// # Examples
373     ///
374     /// ```ignore (illustrative)
375     /// fn with_closure<F>(_: F)
376     ///   where F: Fn(&u32) -> &u32 { .. }
377     ///
378     /// with_closure(|x: &u32| { ... })
379     /// ```
380     ///
381     /// Here:
382     /// - E would be `fn(&u32) -> &u32`.
383     /// - S would be `fn(&u32) ->
384     /// - E' is `&'!0 u32 -> &'!0 u32`
385     /// - S' is `&'?0 u32 -> ?T`
386     ///
387     /// S' can be unified with E' with `['?0 = '!0, ?T = &'!10 u32]`.
388     ///
389     /// # Arguments
390     ///
391     /// - `expr_def_id`: the `DefId` of the closure expression
392     /// - `decl`: the HIR declaration of the closure
393     /// - `body`: the body of the closure
394     /// - `expected_sig`: the expected signature (if any). Note that
395     ///   this is missing a binder: that is, there may be late-bound
396     ///   regions with depth 1, which are bound then by the closure.
397     #[instrument(skip(self, hir_id, expr_def_id, decl, body), level = "debug")]
398     fn sig_of_closure_with_expectation(
399         &self,
400         hir_id: hir::HirId,
401         expr_def_id: DefId,
402         decl: &hir::FnDecl<'_>,
403         body: &hir::Body<'_>,
404         expected_sig: ExpectedSig<'tcx>,
405     ) -> ClosureSignatures<'tcx> {
406         // Watch out for some surprises and just ignore the
407         // expectation if things don't see to match up with what we
408         // expect.
409         if expected_sig.sig.c_variadic() != decl.c_variadic {
410             return self.sig_of_closure_no_expectation(hir_id, expr_def_id, decl, body);
411         } else if expected_sig.sig.skip_binder().inputs_and_output.len() != decl.inputs.len() + 1 {
412             return self.sig_of_closure_with_mismatched_number_of_arguments(
413                 expr_def_id,
414                 decl,
415                 body,
416                 expected_sig,
417             );
418         }
419
420         // Create a `PolyFnSig`. Note the oddity that late bound
421         // regions appearing free in `expected_sig` are now bound up
422         // in this binder we are creating.
423         assert!(!expected_sig.sig.skip_binder().has_vars_bound_above(ty::INNERMOST));
424         let bound_sig = expected_sig.sig.map_bound(|sig| {
425             self.tcx.mk_fn_sig(
426                 sig.inputs().iter().cloned(),
427                 sig.output(),
428                 sig.c_variadic,
429                 hir::Unsafety::Normal,
430                 Abi::RustCall,
431             )
432         });
433
434         // `deduce_expectations_from_expected_type` introduces
435         // late-bound lifetimes defined elsewhere, which we now
436         // anonymize away, so as not to confuse the user.
437         let bound_sig = self.tcx.anonymize_late_bound_regions(bound_sig);
438
439         let closure_sigs = self.closure_sigs(expr_def_id, body, bound_sig);
440
441         // Up till this point, we have ignored the annotations that the user
442         // gave. This function will check that they unify successfully.
443         // Along the way, it also writes out entries for types that the user
444         // wrote into our typeck results, which are then later used by the privacy
445         // check.
446         match self.check_supplied_sig_against_expectation(
447             hir_id,
448             expr_def_id,
449             decl,
450             body,
451             &closure_sigs,
452         ) {
453             Ok(infer_ok) => self.register_infer_ok_obligations(infer_ok),
454             Err(_) => return self.sig_of_closure_no_expectation(hir_id, expr_def_id, decl, body),
455         }
456
457         closure_sigs
458     }
459
460     fn sig_of_closure_with_mismatched_number_of_arguments(
461         &self,
462         expr_def_id: DefId,
463         decl: &hir::FnDecl<'_>,
464         body: &hir::Body<'_>,
465         expected_sig: ExpectedSig<'tcx>,
466     ) -> ClosureSignatures<'tcx> {
467         let hir = self.tcx.hir();
468         let expr_map_node = hir.get_if_local(expr_def_id).unwrap();
469         let expected_args: Vec<_> = expected_sig
470             .sig
471             .skip_binder()
472             .inputs()
473             .iter()
474             .map(|ty| ArgKind::from_expected_ty(*ty, None))
475             .collect();
476         let (closure_span, found_args) = match self.get_fn_like_arguments(expr_map_node) {
477             Some((sp, args)) => (Some(sp), args),
478             None => (None, Vec::new()),
479         };
480         let expected_span =
481             expected_sig.cause_span.unwrap_or_else(|| hir.span_if_local(expr_def_id).unwrap());
482         self.report_arg_count_mismatch(
483             expected_span,
484             closure_span,
485             expected_args,
486             found_args,
487             true,
488         )
489         .emit();
490
491         let error_sig = self.error_sig_of_closure(decl);
492
493         self.closure_sigs(expr_def_id, body, error_sig)
494     }
495
496     /// Enforce the user's types against the expectation. See
497     /// `sig_of_closure_with_expectation` for details on the overall
498     /// strategy.
499     fn check_supplied_sig_against_expectation(
500         &self,
501         hir_id: hir::HirId,
502         expr_def_id: DefId,
503         decl: &hir::FnDecl<'_>,
504         body: &hir::Body<'_>,
505         expected_sigs: &ClosureSignatures<'tcx>,
506     ) -> InferResult<'tcx, ()> {
507         // Get the signature S that the user gave.
508         //
509         // (See comment on `sig_of_closure_with_expectation` for the
510         // meaning of these letters.)
511         let supplied_sig = self.supplied_sig_of_closure(hir_id, expr_def_id, decl, body);
512
513         debug!("check_supplied_sig_against_expectation: supplied_sig={:?}", supplied_sig);
514
515         // FIXME(#45727): As discussed in [this comment][c1], naively
516         // forcing equality here actually results in suboptimal error
517         // messages in some cases.  For now, if there would have been
518         // an obvious error, we fallback to declaring the type of the
519         // closure to be the one the user gave, which allows other
520         // error message code to trigger.
521         //
522         // However, I think [there is potential to do even better
523         // here][c2], since in *this* code we have the precise span of
524         // the type parameter in question in hand when we report the
525         // error.
526         //
527         // [c1]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341089706
528         // [c2]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341096796
529         self.commit_if_ok(|_| {
530             let mut all_obligations = vec![];
531
532             // The liberated version of this signature should be a subtype
533             // of the liberated form of the expectation.
534             for ((hir_ty, &supplied_ty), expected_ty) in iter::zip(
535                 iter::zip(
536                     decl.inputs,
537                     supplied_sig.inputs().skip_binder(), // binder moved to (*) below
538                 ),
539                 expected_sigs.liberated_sig.inputs(), // `liberated_sig` is E'.
540             ) {
541                 // Instantiate (this part of..) S to S', i.e., with fresh variables.
542                 let supplied_ty = self.replace_bound_vars_with_fresh_vars(
543                     hir_ty.span,
544                     LateBoundRegionConversionTime::FnCall,
545                     supplied_sig.inputs().rebind(supplied_ty),
546                 ); // recreated from (*) above
547
548                 // Check that E' = S'.
549                 let cause = self.misc(hir_ty.span);
550                 let InferOk { value: (), obligations } =
551                     self.at(&cause, self.param_env).eq(*expected_ty, supplied_ty)?;
552                 all_obligations.extend(obligations);
553             }
554
555             let supplied_output_ty = self.replace_bound_vars_with_fresh_vars(
556                 decl.output.span(),
557                 LateBoundRegionConversionTime::FnCall,
558                 supplied_sig.output(),
559             );
560             let cause = &self.misc(decl.output.span());
561             let InferOk { value: (), obligations } = self
562                 .at(cause, self.param_env)
563                 .eq(expected_sigs.liberated_sig.output(), supplied_output_ty)?;
564             all_obligations.extend(obligations);
565
566             Ok(InferOk { value: (), obligations: all_obligations })
567         })
568     }
569
570     /// If there is no expected signature, then we will convert the
571     /// types that the user gave into a signature.
572     ///
573     /// Also, record this closure signature for later.
574     #[instrument(skip(self, decl, body), level = "debug", ret)]
575     fn supplied_sig_of_closure(
576         &self,
577         hir_id: hir::HirId,
578         expr_def_id: DefId,
579         decl: &hir::FnDecl<'_>,
580         body: &hir::Body<'_>,
581     ) -> ty::PolyFnSig<'tcx> {
582         let astconv: &dyn AstConv<'_> = self;
583
584         trace!("decl = {:#?}", decl);
585         debug!(?body.generator_kind);
586
587         let bound_vars = self.tcx.late_bound_vars(hir_id);
588
589         // First, convert the types that the user supplied (if any).
590         let supplied_arguments = decl.inputs.iter().map(|a| astconv.ast_ty_to_ty(a));
591         let supplied_return = match decl.output {
592             hir::FnRetTy::Return(ref output) => astconv.ast_ty_to_ty(&output),
593             hir::FnRetTy::DefaultReturn(_) => match body.generator_kind {
594                 // In the case of the async block that we create for a function body,
595                 // we expect the return type of the block to match that of the enclosing
596                 // function.
597                 Some(hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn)) => {
598                     debug!("closure is async fn body");
599                     self.deduce_future_output_from_obligations(expr_def_id, body.id().hir_id)
600                         .unwrap_or_else(|| {
601                             // AFAIK, deducing the future output
602                             // always succeeds *except* in error cases
603                             // like #65159. I'd like to return Error
604                             // here, but I can't because I can't
605                             // easily (and locally) prove that we
606                             // *have* reported an
607                             // error. --nikomatsakis
608                             astconv.ty_infer(None, decl.output.span())
609                         })
610                 }
611
612                 _ => astconv.ty_infer(None, decl.output.span()),
613             },
614         };
615
616         let result = ty::Binder::bind_with_vars(
617             self.tcx.mk_fn_sig(
618                 supplied_arguments,
619                 supplied_return,
620                 decl.c_variadic,
621                 hir::Unsafety::Normal,
622                 Abi::RustCall,
623             ),
624             bound_vars,
625         );
626
627         let c_result = self.inh.infcx.canonicalize_response(result);
628         self.typeck_results.borrow_mut().user_provided_sigs.insert(expr_def_id, c_result);
629
630         result
631     }
632
633     /// Invoked when we are translating the generator that results
634     /// from desugaring an `async fn`. Returns the "sugared" return
635     /// type of the `async fn` -- that is, the return type that the
636     /// user specified. The "desugared" return type is an `impl
637     /// Future<Output = T>`, so we do this by searching through the
638     /// obligations to extract the `T`.
639     #[instrument(skip(self), level = "debug", ret)]
640     fn deduce_future_output_from_obligations(
641         &self,
642         expr_def_id: DefId,
643         body_id: hir::HirId,
644     ) -> Option<Ty<'tcx>> {
645         let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
646             span_bug!(self.tcx.def_span(expr_def_id), "async fn generator outside of a fn")
647         });
648
649         let ret_ty = ret_coercion.borrow().expected_ty();
650         let ret_ty = self.inh.infcx.shallow_resolve(ret_ty);
651
652         let get_future_output = |predicate: ty::Predicate<'tcx>, span| {
653             // Search for a pending obligation like
654             //
655             // `<R as Future>::Output = T`
656             //
657             // where R is the return type we are expecting. This type `T`
658             // will be our output.
659             let bound_predicate = predicate.kind();
660             if let ty::PredicateKind::Projection(proj_predicate) = bound_predicate.skip_binder() {
661                 self.deduce_future_output_from_projection(
662                     span,
663                     bound_predicate.rebind(proj_predicate),
664                 )
665             } else {
666                 None
667             }
668         };
669
670         let output_ty = match *ret_ty.kind() {
671             ty::Infer(ty::TyVar(ret_vid)) => {
672                 self.obligations_for_self_ty(ret_vid).find_map(|(_, obligation)| {
673                     get_future_output(obligation.predicate, obligation.cause.span)
674                 })?
675             }
676             ty::Opaque(def_id, substs) => self
677                 .tcx
678                 .bound_explicit_item_bounds(def_id)
679                 .transpose_iter()
680                 .map(|e| e.map_bound(|e| *e).transpose_tuple2())
681                 .find_map(|(p, s)| get_future_output(p.subst(self.tcx, substs), s.0))?,
682             ty::Error(_) => return None,
683             _ => span_bug!(
684                 self.tcx.def_span(expr_def_id),
685                 "async fn generator return type not an inference variable"
686             ),
687         };
688
689         // async fn that have opaque types in their return type need to redo the conversion to inference variables
690         // as they fetch the still opaque version from the signature.
691         let InferOk { value: output_ty, obligations } = self
692             .replace_opaque_types_with_inference_vars(
693                 output_ty,
694                 body_id,
695                 self.tcx.def_span(expr_def_id),
696                 self.param_env,
697             );
698         self.register_predicates(obligations);
699
700         Some(output_ty)
701     }
702
703     /// Given a projection like
704     ///
705     /// `<X as Future>::Output = T`
706     ///
707     /// where `X` is some type that has no late-bound regions, returns
708     /// `Some(T)`. If the projection is for some other trait, returns
709     /// `None`.
710     fn deduce_future_output_from_projection(
711         &self,
712         cause_span: Span,
713         predicate: ty::PolyProjectionPredicate<'tcx>,
714     ) -> Option<Ty<'tcx>> {
715         debug!("deduce_future_output_from_projection(predicate={:?})", predicate);
716
717         // We do not expect any bound regions in our predicate, so
718         // skip past the bound vars.
719         let Some(predicate) = predicate.no_bound_vars() else {
720             debug!("deduce_future_output_from_projection: has late-bound regions");
721             return None;
722         };
723
724         // Check that this is a projection from the `Future` trait.
725         let trait_def_id = predicate.projection_ty.trait_def_id(self.tcx);
726         let future_trait = self.tcx.require_lang_item(LangItem::Future, Some(cause_span));
727         if trait_def_id != future_trait {
728             debug!("deduce_future_output_from_projection: not a future");
729             return None;
730         }
731
732         // The `Future` trait has only one associated item, `Output`,
733         // so check that this is what we see.
734         let output_assoc_item = self.tcx.associated_item_def_ids(future_trait)[0];
735         if output_assoc_item != predicate.projection_ty.item_def_id {
736             span_bug!(
737                 cause_span,
738                 "projecting associated item `{:?}` from future, which is not Output `{:?}`",
739                 predicate.projection_ty.item_def_id,
740                 output_assoc_item,
741             );
742         }
743
744         // Extract the type from the projection. Note that there can
745         // be no bound variables in this type because the "self type"
746         // does not have any regions in it.
747         let output_ty = self.resolve_vars_if_possible(predicate.term);
748         debug!("deduce_future_output_from_projection: output_ty={:?}", output_ty);
749         // This is a projection on a Fn trait so will always be a type.
750         Some(output_ty.ty().unwrap())
751     }
752
753     /// Converts the types that the user supplied, in case that doing
754     /// so should yield an error, but returns back a signature where
755     /// all parameters are of type `TyErr`.
756     fn error_sig_of_closure(&self, decl: &hir::FnDecl<'_>) -> ty::PolyFnSig<'tcx> {
757         let astconv: &dyn AstConv<'_> = self;
758
759         let supplied_arguments = decl.inputs.iter().map(|a| {
760             // Convert the types that the user supplied (if any), but ignore them.
761             astconv.ast_ty_to_ty(a);
762             self.tcx.ty_error()
763         });
764
765         if let hir::FnRetTy::Return(ref output) = decl.output {
766             astconv.ast_ty_to_ty(&output);
767         }
768
769         let result = ty::Binder::dummy(self.tcx.mk_fn_sig(
770             supplied_arguments,
771             self.tcx.ty_error(),
772             decl.c_variadic,
773             hir::Unsafety::Normal,
774             Abi::RustCall,
775         ));
776
777         debug!("supplied_sig_of_closure: result={:?}", result);
778
779         result
780     }
781
782     fn closure_sigs(
783         &self,
784         expr_def_id: DefId,
785         body: &hir::Body<'_>,
786         bound_sig: ty::PolyFnSig<'tcx>,
787     ) -> ClosureSignatures<'tcx> {
788         let liberated_sig = self.tcx().liberate_late_bound_regions(expr_def_id, bound_sig);
789         let liberated_sig = self.inh.normalize_associated_types_in(
790             body.value.span,
791             body.value.hir_id,
792             self.param_env,
793             liberated_sig,
794         );
795         ClosureSignatures { bound_sig, liberated_sig }
796     }
797 }