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