]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_typeck/src/closure.rs
Rollup merge of #104296 - compiler-errors:opaque-ty-ffi-normalization-cycle, r=lcnr
[rust.git] / compiler / rustc_hir_typeck / src / closure.rs
1 //! Code for type-checking closure expressions.
2
3 use super::{check_fn, Expectation, FnCtxt, GeneratorTypes};
4
5 use hir::def::DefKind;
6 use rustc_hir as hir;
7 use rustc_hir::def_id::DefId;
8 use rustc_hir::lang_items::LangItem;
9 use rustc_hir_analysis::astconv::AstConv;
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_macros::{TypeFoldable, TypeVisitable};
14 use rustc_middle::ty::subst::InternalSubsts;
15 use rustc_middle::ty::visit::TypeVisitable;
16 use rustc_middle::ty::{self, Ty};
17 use rustc_span::source_map::Span;
18 use rustc_target::spec::abi::Abi;
19 use rustc_trait_selection::traits;
20 use rustc_trait_selection::traits::error_reporting::ArgKind;
21 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
22 use std::cmp;
23 use std::iter;
24
25 /// What signature do we *expect* the closure to have from context?
26 #[derive(Debug, Clone, TypeFoldable, TypeVisitable)]
27 struct ExpectedSig<'tcx> {
28     /// Span that gave us this expectation, if we know that.
29     cause_span: Option<Span>,
30     sig: ty::PolyFnSig<'tcx>,
31 }
32
33 struct ClosureSignatures<'tcx> {
34     /// The signature users of the closure see.
35     bound_sig: ty::PolyFnSig<'tcx>,
36     /// The signature within the function body.
37     /// This mostly differs in the sense that lifetimes are now early bound and any
38     /// opaque types from the signature expectation are overridden in case there are
39     /// explicit hidden types written by the user in the closure signature.
40     liberated_sig: ty::FnSig<'tcx>,
41 }
42
43 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
44     #[instrument(skip(self, expr, _capture, decl, body_id), level = "debug")]
45     pub fn check_expr_closure(
46         &self,
47         expr: &hir::Expr<'_>,
48         _capture: hir::CaptureBy,
49         decl: &'tcx hir::FnDecl<'tcx>,
50         body_id: hir::BodyId,
51         gen: Option<hir::Movability>,
52         expected: Expectation<'tcx>,
53     ) -> Ty<'tcx> {
54         trace!("decl = {:#?}", decl);
55         trace!("expr = {:#?}", expr);
56
57         // It's always helpful for inference if we know the kind of
58         // closure sooner rather than later, so first examine the expected
59         // type, and see if can glean a closure kind from there.
60         let (expected_sig, expected_kind) = match expected.to_option(self) {
61             Some(ty) => self.deduce_expectations_from_expected_type(ty),
62             None => (None, None),
63         };
64         let body = self.tcx.hir().body(body_id);
65         self.check_closure(expr, expected_kind, decl, body, gen, expected_sig)
66     }
67
68     #[instrument(skip(self, expr, body, decl), level = "debug", ret)]
69     fn check_closure(
70         &self,
71         expr: &hir::Expr<'_>,
72         opt_kind: Option<ty::ClosureKind>,
73         decl: &'tcx hir::FnDecl<'tcx>,
74         body: &'tcx hir::Body<'tcx>,
75         gen: Option<hir::Movability>,
76         expected_sig: Option<ExpectedSig<'tcx>>,
77     ) -> Ty<'tcx> {
78         trace!("decl = {:#?}", decl);
79         let expr_def_id = self.tcx.hir().local_def_id(expr.hir_id);
80         debug!(?expr_def_id);
81
82         let ClosureSignatures { bound_sig, liberated_sig } =
83             self.sig_of_closure(expr.hir_id, expr_def_id.to_def_id(), decl, body, expected_sig);
84
85         debug!(?bound_sig, ?liberated_sig);
86
87         let generator_types = check_fn(
88             self,
89             self.param_env.without_const(),
90             liberated_sig,
91             decl,
92             expr.hir_id,
93             body,
94             gen,
95         )
96         .1;
97
98         let parent_substs = InternalSubsts::identity_for_item(
99             self.tcx,
100             self.tcx.typeck_root_def_id(expr_def_id.to_def_id()),
101         );
102
103         let tupled_upvars_ty = self.next_ty_var(TypeVariableOrigin {
104             kind: TypeVariableOriginKind::ClosureSynthetic,
105             span: self.tcx.hir().span(expr.hir_id),
106         });
107
108         if let Some(GeneratorTypes { resume_ty, yield_ty, interior, movability }) = generator_types
109         {
110             let generator_substs = ty::GeneratorSubsts::new(
111                 self.tcx,
112                 ty::GeneratorSubstsParts {
113                     parent_substs,
114                     resume_ty,
115                     yield_ty,
116                     return_ty: liberated_sig.output(),
117                     witness: interior,
118                     tupled_upvars_ty,
119                 },
120             );
121
122             return self.tcx.mk_generator(
123                 expr_def_id.to_def_id(),
124                 generator_substs.substs,
125                 movability,
126             );
127         }
128
129         // Tuple up the arguments and insert the resulting function type into
130         // the `closures` table.
131         let sig = bound_sig.map_bound(|sig| {
132             self.tcx.mk_fn_sig(
133                 iter::once(self.tcx.intern_tup(sig.inputs())),
134                 sig.output(),
135                 sig.c_variadic,
136                 sig.unsafety,
137                 sig.abi,
138             )
139         });
140
141         debug!(?sig, ?opt_kind);
142
143         let closure_kind_ty = match opt_kind {
144             Some(kind) => kind.to_ty(self.tcx),
145
146             // Create a type variable (for now) to represent the closure kind.
147             // It will be unified during the upvar inference phase (`upvar.rs`)
148             None => self.next_ty_var(TypeVariableOrigin {
149                 // FIXME(eddyb) distinguish closure kind inference variables from the rest.
150                 kind: TypeVariableOriginKind::ClosureSynthetic,
151                 span: expr.span,
152             }),
153         };
154
155         let closure_substs = ty::ClosureSubsts::new(
156             self.tcx,
157             ty::ClosureSubstsParts {
158                 parent_substs,
159                 closure_kind_ty,
160                 closure_sig_as_fn_ptr_ty: self.tcx.mk_fn_ptr(sig),
161                 tupled_upvars_ty,
162             },
163         );
164
165         self.tcx.mk_closure(expr_def_id.to_def_id(), closure_substs.substs)
166     }
167
168     /// Given the expected type, figures out what it can about this closure we
169     /// are about to type check:
170     #[instrument(skip(self), level = "debug")]
171     fn deduce_expectations_from_expected_type(
172         &self,
173         expected_ty: Ty<'tcx>,
174     ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
175         match *expected_ty.kind() {
176             ty::Opaque(def_id, substs) => self.deduce_signature_from_predicates(
177                 self.tcx.bound_explicit_item_bounds(def_id).subst_iter_copied(self.tcx, substs),
178             ),
179             ty::Dynamic(ref object_type, ..) => {
180                 let sig = object_type.projection_bounds().find_map(|pb| {
181                     let pb = pb.with_self_ty(self.tcx, self.tcx.types.trait_object_dummy_self);
182                     self.deduce_sig_from_projection(None, pb)
183                 });
184                 let kind = object_type
185                     .principal_def_id()
186                     .and_then(|did| self.tcx.fn_trait_kind_from_lang_item(did));
187                 (sig, kind)
188             }
189             ty::Infer(ty::TyVar(vid)) => self.deduce_signature_from_predicates(
190                 self.obligations_for_self_ty(vid).map(|obl| (obl.predicate, obl.cause.span)),
191             ),
192             ty::FnPtr(sig) => {
193                 let expected_sig = ExpectedSig { cause_span: None, sig };
194                 (Some(expected_sig), Some(ty::ClosureKind::Fn))
195             }
196             _ => (None, None),
197         }
198     }
199
200     fn deduce_signature_from_predicates(
201         &self,
202         predicates: impl DoubleEndedIterator<Item = (ty::Predicate<'tcx>, Span)>,
203     ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
204         let mut expected_sig = None;
205         let mut expected_kind = None;
206
207         for obligation in traits::elaborate_predicates_with_span(
208             self.tcx,
209             // Reverse the obligations here, since `elaborate_*` uses a stack,
210             // and we want to keep inference generally in the same order of
211             // the registered obligations.
212             predicates.rev(),
213         ) {
214             debug!(?obligation.predicate);
215             let bound_predicate = obligation.predicate.kind();
216
217             // Given a Projection predicate, we can potentially infer
218             // the complete signature.
219             if expected_sig.is_none()
220                 && let ty::PredicateKind::Projection(proj_predicate) = bound_predicate.skip_binder()
221             {
222                 expected_sig = self.normalize_associated_types_in(
223                     obligation.cause.span,
224                     self.deduce_sig_from_projection(
225                     Some(obligation.cause.span),
226                         bound_predicate.rebind(proj_predicate),
227                     ),
228                 );
229             }
230
231             // Even if we can't infer the full signature, we may be able to
232             // infer the kind. This can occur when we elaborate a predicate
233             // like `F : Fn<A>`. Note that due to subtyping we could encounter
234             // many viable options, so pick the most restrictive.
235             let trait_def_id = match bound_predicate.skip_binder() {
236                 ty::PredicateKind::Projection(data) => {
237                     Some(data.projection_ty.trait_def_id(self.tcx))
238                 }
239                 ty::PredicateKind::Trait(data) => Some(data.def_id()),
240                 _ => None,
241             };
242             if let Some(closure_kind) =
243                 trait_def_id.and_then(|def_id| self.tcx.fn_trait_kind_from_lang_item(def_id))
244             {
245                 expected_kind = Some(
246                     expected_kind
247                         .map_or_else(|| closure_kind, |current| cmp::min(current, closure_kind)),
248                 );
249             }
250         }
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.merge_supplied_sig_with_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(_) => self.sig_of_closure_no_expectation(hir_id, expr_def_id, decl, body),
455         }
456     }
457
458     fn sig_of_closure_with_mismatched_number_of_arguments(
459         &self,
460         expr_def_id: DefId,
461         decl: &hir::FnDecl<'_>,
462         body: &hir::Body<'_>,
463         expected_sig: ExpectedSig<'tcx>,
464     ) -> ClosureSignatures<'tcx> {
465         let hir = self.tcx.hir();
466         let expr_map_node = hir.get_if_local(expr_def_id).unwrap();
467         let expected_args: Vec<_> = expected_sig
468             .sig
469             .skip_binder()
470             .inputs()
471             .iter()
472             .map(|ty| ArgKind::from_expected_ty(*ty, None))
473             .collect();
474         let (closure_span, found_args) = match self.get_fn_like_arguments(expr_map_node) {
475             Some((sp, args)) => (Some(sp), args),
476             None => (None, Vec::new()),
477         };
478         let expected_span =
479             expected_sig.cause_span.unwrap_or_else(|| hir.span_if_local(expr_def_id).unwrap());
480         self.report_arg_count_mismatch(
481             expected_span,
482             closure_span,
483             expected_args,
484             found_args,
485             true,
486         )
487         .emit();
488
489         let error_sig = self.error_sig_of_closure(decl);
490
491         self.closure_sigs(expr_def_id, body, error_sig)
492     }
493
494     /// Enforce the user's types against the expectation. See
495     /// `sig_of_closure_with_expectation` for details on the overall
496     /// strategy.
497     #[instrument(level = "debug", skip(self, hir_id, expr_def_id, decl, body, expected_sigs))]
498     fn merge_supplied_sig_with_expectation(
499         &self,
500         hir_id: hir::HirId,
501         expr_def_id: DefId,
502         decl: &hir::FnDecl<'_>,
503         body: &hir::Body<'_>,
504         mut expected_sigs: ClosureSignatures<'tcx>,
505     ) -> InferResult<'tcx, ClosureSignatures<'tcx>> {
506         // Get the signature S that the user gave.
507         //
508         // (See comment on `sig_of_closure_with_expectation` for the
509         // meaning of these letters.)
510         let supplied_sig = self.supplied_sig_of_closure(hir_id, expr_def_id, decl, body);
511
512         debug!(?supplied_sig);
513
514         // FIXME(#45727): As discussed in [this comment][c1], naively
515         // forcing equality here actually results in suboptimal error
516         // messages in some cases.  For now, if there would have been
517         // an obvious error, we fallback to declaring the type of the
518         // closure to be the one the user gave, which allows other
519         // error message code to trigger.
520         //
521         // However, I think [there is potential to do even better
522         // here][c2], since in *this* code we have the precise span of
523         // the type parameter in question in hand when we report the
524         // error.
525         //
526         // [c1]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341089706
527         // [c2]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341096796
528         self.commit_if_ok(|_| {
529             let mut all_obligations = vec![];
530             let inputs: Vec<_> = iter::zip(
531                 decl.inputs,
532                 supplied_sig.inputs().skip_binder(), // binder moved to (*) below
533             )
534             .map(|(hir_ty, &supplied_ty)| {
535                 // Instantiate (this part of..) S to S', i.e., with fresh variables.
536                 self.replace_bound_vars_with_fresh_vars(
537                     hir_ty.span,
538                     LateBoundRegionConversionTime::FnCall,
539                     // (*) binder moved to here
540                     supplied_sig.inputs().rebind(supplied_ty),
541                 )
542             })
543             .collect();
544
545             // The liberated version of this signature should be a subtype
546             // of the liberated form of the expectation.
547             for ((hir_ty, &supplied_ty), expected_ty) in iter::zip(
548                 iter::zip(decl.inputs, &inputs),
549                 expected_sigs.liberated_sig.inputs(), // `liberated_sig` is E'.
550             ) {
551                 // Check that E' = S'.
552                 let cause = self.misc(hir_ty.span);
553                 let InferOk { value: (), obligations } =
554                     self.at(&cause, self.param_env).eq(*expected_ty, supplied_ty)?;
555                 all_obligations.extend(obligations);
556             }
557
558             let supplied_output_ty = self.replace_bound_vars_with_fresh_vars(
559                 decl.output.span(),
560                 LateBoundRegionConversionTime::FnCall,
561                 supplied_sig.output(),
562             );
563             let cause = &self.misc(decl.output.span());
564             let InferOk { value: (), obligations } = self
565                 .at(cause, self.param_env)
566                 .eq(expected_sigs.liberated_sig.output(), supplied_output_ty)?;
567             all_obligations.extend(obligations);
568
569             let inputs = inputs.into_iter().map(|ty| self.resolve_vars_if_possible(ty));
570
571             expected_sigs.liberated_sig = self.tcx.mk_fn_sig(
572                 inputs,
573                 supplied_output_ty,
574                 expected_sigs.liberated_sig.c_variadic,
575                 hir::Unsafety::Normal,
576                 Abi::RustCall,
577             );
578
579             Ok(InferOk { value: expected_sigs, obligations: all_obligations })
580         })
581     }
582
583     /// If there is no expected signature, then we will convert the
584     /// types that the user gave into a signature.
585     ///
586     /// Also, record this closure signature for later.
587     #[instrument(skip(self, decl, body), level = "debug", ret)]
588     fn supplied_sig_of_closure(
589         &self,
590         hir_id: hir::HirId,
591         expr_def_id: DefId,
592         decl: &hir::FnDecl<'_>,
593         body: &hir::Body<'_>,
594     ) -> ty::PolyFnSig<'tcx> {
595         let astconv: &dyn AstConv<'_> = self;
596
597         trace!("decl = {:#?}", decl);
598         debug!(?body.generator_kind);
599
600         let bound_vars = self.tcx.late_bound_vars(hir_id);
601
602         // First, convert the types that the user supplied (if any).
603         let supplied_arguments = decl.inputs.iter().map(|a| astconv.ast_ty_to_ty(a));
604         let supplied_return = match decl.output {
605             hir::FnRetTy::Return(ref output) => astconv.ast_ty_to_ty(&output),
606             hir::FnRetTy::DefaultReturn(_) => match body.generator_kind {
607                 // In the case of the async block that we create for a function body,
608                 // we expect the return type of the block to match that of the enclosing
609                 // function.
610                 Some(hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn)) => {
611                     debug!("closure is async fn body");
612                     self.deduce_future_output_from_obligations(expr_def_id, body.id().hir_id)
613                         .unwrap_or_else(|| {
614                             // AFAIK, deducing the future output
615                             // always succeeds *except* in error cases
616                             // like #65159. I'd like to return Error
617                             // here, but I can't because I can't
618                             // easily (and locally) prove that we
619                             // *have* reported an
620                             // error. --nikomatsakis
621                             astconv.ty_infer(None, decl.output.span())
622                         })
623                 }
624
625                 _ => astconv.ty_infer(None, decl.output.span()),
626             },
627         };
628
629         let result = ty::Binder::bind_with_vars(
630             self.tcx.mk_fn_sig(
631                 supplied_arguments,
632                 supplied_return,
633                 decl.c_variadic,
634                 hir::Unsafety::Normal,
635                 Abi::RustCall,
636             ),
637             bound_vars,
638         );
639         // Astconv can't normalize inputs or outputs with escaping bound vars,
640         // so normalize them here, after we've wrapped them in a binder.
641         let result = self.normalize_associated_types_in(self.tcx.hir().span(hir_id), result);
642
643         let c_result = self.inh.infcx.canonicalize_response(result);
644         self.typeck_results.borrow_mut().user_provided_sigs.insert(expr_def_id, c_result);
645
646         result
647     }
648
649     /// Invoked when we are translating the generator that results
650     /// from desugaring an `async fn`. Returns the "sugared" return
651     /// type of the `async fn` -- that is, the return type that the
652     /// user specified. The "desugared" return type is an `impl
653     /// Future<Output = T>`, so we do this by searching through the
654     /// obligations to extract the `T`.
655     #[instrument(skip(self), level = "debug", ret)]
656     fn deduce_future_output_from_obligations(
657         &self,
658         expr_def_id: DefId,
659         body_id: hir::HirId,
660     ) -> Option<Ty<'tcx>> {
661         let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
662             span_bug!(self.tcx.def_span(expr_def_id), "async fn generator outside of a fn")
663         });
664
665         let ret_ty = ret_coercion.borrow().expected_ty();
666         let ret_ty = self.inh.infcx.shallow_resolve(ret_ty);
667
668         let get_future_output = |predicate: ty::Predicate<'tcx>, span| {
669             // Search for a pending obligation like
670             //
671             // `<R as Future>::Output = T`
672             //
673             // where R is the return type we are expecting. This type `T`
674             // will be our output.
675             let bound_predicate = predicate.kind();
676             if let ty::PredicateKind::Projection(proj_predicate) = bound_predicate.skip_binder() {
677                 self.deduce_future_output_from_projection(
678                     span,
679                     bound_predicate.rebind(proj_predicate),
680                 )
681             } else {
682                 None
683             }
684         };
685
686         let output_ty = match *ret_ty.kind() {
687             ty::Infer(ty::TyVar(ret_vid)) => {
688                 self.obligations_for_self_ty(ret_vid).find_map(|obligation| {
689                     get_future_output(obligation.predicate, obligation.cause.span)
690                 })?
691             }
692             ty::Opaque(def_id, substs) => self
693                 .tcx
694                 .bound_explicit_item_bounds(def_id)
695                 .subst_iter_copied(self.tcx, substs)
696                 .find_map(|(p, s)| get_future_output(p, s))?,
697             ty::Error(_) => return None,
698             ty::Projection(proj)
699                 if self.tcx.def_kind(proj.item_def_id) == DefKind::ImplTraitPlaceholder =>
700             {
701                 self.tcx
702                     .bound_explicit_item_bounds(proj.item_def_id)
703                     .subst_iter_copied(self.tcx, proj.substs)
704                     .find_map(|(p, s)| get_future_output(p, s))?
705             }
706             _ => span_bug!(
707                 self.tcx.def_span(expr_def_id),
708                 "async fn generator return type not an inference variable: {ret_ty}"
709             ),
710         };
711
712         // async fn that have opaque types in their return type need to redo the conversion to inference variables
713         // as they fetch the still opaque version from the signature.
714         let InferOk { value: output_ty, obligations } = self
715             .replace_opaque_types_with_inference_vars(
716                 output_ty,
717                 body_id,
718                 self.tcx.def_span(expr_def_id),
719                 self.param_env,
720             );
721         self.register_predicates(obligations);
722
723         Some(output_ty)
724     }
725
726     /// Given a projection like
727     ///
728     /// `<X as Future>::Output = T`
729     ///
730     /// where `X` is some type that has no late-bound regions, returns
731     /// `Some(T)`. If the projection is for some other trait, returns
732     /// `None`.
733     fn deduce_future_output_from_projection(
734         &self,
735         cause_span: Span,
736         predicate: ty::PolyProjectionPredicate<'tcx>,
737     ) -> Option<Ty<'tcx>> {
738         debug!("deduce_future_output_from_projection(predicate={:?})", predicate);
739
740         // We do not expect any bound regions in our predicate, so
741         // skip past the bound vars.
742         let Some(predicate) = predicate.no_bound_vars() else {
743             debug!("deduce_future_output_from_projection: has late-bound regions");
744             return None;
745         };
746
747         // Check that this is a projection from the `Future` trait.
748         let trait_def_id = predicate.projection_ty.trait_def_id(self.tcx);
749         let future_trait = self.tcx.require_lang_item(LangItem::Future, Some(cause_span));
750         if trait_def_id != future_trait {
751             debug!("deduce_future_output_from_projection: not a future");
752             return None;
753         }
754
755         // The `Future` trait has only one associated item, `Output`,
756         // so check that this is what we see.
757         let output_assoc_item = self.tcx.associated_item_def_ids(future_trait)[0];
758         if output_assoc_item != predicate.projection_ty.item_def_id {
759             span_bug!(
760                 cause_span,
761                 "projecting associated item `{:?}` from future, which is not Output `{:?}`",
762                 predicate.projection_ty.item_def_id,
763                 output_assoc_item,
764             );
765         }
766
767         // Extract the type from the projection. Note that there can
768         // be no bound variables in this type because the "self type"
769         // does not have any regions in it.
770         let output_ty = self.resolve_vars_if_possible(predicate.term);
771         debug!("deduce_future_output_from_projection: output_ty={:?}", output_ty);
772         // This is a projection on a Fn trait so will always be a type.
773         Some(output_ty.ty().unwrap())
774     }
775
776     /// Converts the types that the user supplied, in case that doing
777     /// so should yield an error, but returns back a signature where
778     /// all parameters are of type `TyErr`.
779     fn error_sig_of_closure(&self, decl: &hir::FnDecl<'_>) -> ty::PolyFnSig<'tcx> {
780         let astconv: &dyn AstConv<'_> = self;
781
782         let supplied_arguments = decl.inputs.iter().map(|a| {
783             // Convert the types that the user supplied (if any), but ignore them.
784             astconv.ast_ty_to_ty(a);
785             self.tcx.ty_error()
786         });
787
788         if let hir::FnRetTy::Return(ref output) = decl.output {
789             astconv.ast_ty_to_ty(&output);
790         }
791
792         let result = ty::Binder::dummy(self.tcx.mk_fn_sig(
793             supplied_arguments,
794             self.tcx.ty_error(),
795             decl.c_variadic,
796             hir::Unsafety::Normal,
797             Abi::RustCall,
798         ));
799
800         debug!("supplied_sig_of_closure: result={:?}", result);
801
802         result
803     }
804
805     fn closure_sigs(
806         &self,
807         expr_def_id: DefId,
808         body: &hir::Body<'_>,
809         bound_sig: ty::PolyFnSig<'tcx>,
810     ) -> ClosureSignatures<'tcx> {
811         let liberated_sig = self.tcx().liberate_late_bound_regions(expr_def_id, bound_sig);
812         let liberated_sig = self.inh.normalize_associated_types_in(
813             body.value.span,
814             body.value.hir_id,
815             self.param_env,
816             liberated_sig,
817         );
818         ClosureSignatures { bound_sig, liberated_sig }
819     }
820 }