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