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