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