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