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