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