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