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