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