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