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