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