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