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