]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/closure.rs
6b7848c2eb982eef3c485369265ddd0745209a5d
[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 rustc_hir as hir;
7 use rustc_hir::def_id::DefId;
8 use rustc_hir::lang_items::{FutureTraitLangItem, GeneratorTraitLangItem};
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, GenericParamDefKind, Ty};
15 use rustc_span::source_map::Span;
16 use rustc_target::spec::abi::Abi;
17 use rustc_trait_selection::traits::error_reporting::ArgKind;
18 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
19 use std::cmp;
20 use std::iter;
21
22 /// What signature do we *expect* the closure to have from context?
23 #[derive(Debug)]
24 struct ExpectedSig<'tcx> {
25     /// Span that gave us this expectation, if we know that.
26     cause_span: Option<Span>,
27     sig: ty::FnSig<'tcx>,
28 }
29
30 struct ClosureSignatures<'tcx> {
31     bound_sig: ty::PolyFnSig<'tcx>,
32     liberated_sig: ty::FnSig<'tcx>,
33 }
34
35 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
36     pub fn check_expr_closure(
37         &self,
38         expr: &hir::Expr<'_>,
39         _capture: hir::CaptureBy,
40         decl: &'tcx hir::FnDecl<'tcx>,
41         body_id: hir::BodyId,
42         gen: Option<hir::Movability>,
43         expected: Expectation<'tcx>,
44     ) -> Ty<'tcx> {
45         debug!("check_expr_closure(expr={:?},expected={:?})", expr, expected);
46
47         // It's always helpful for inference if we know the kind of
48         // closure sooner rather than later, so first examine the expected
49         // type, and see if can glean a closure kind from there.
50         let (expected_sig, expected_kind) = match expected.to_option(self) {
51             Some(ty) => self.deduce_expectations_from_expected_type(ty),
52             None => (None, None),
53         };
54         let body = self.tcx.hir().body(body_id);
55         self.check_closure(expr, expected_kind, decl, body, gen, expected_sig)
56     }
57
58     fn check_closure(
59         &self,
60         expr: &hir::Expr<'_>,
61         opt_kind: Option<ty::ClosureKind>,
62         decl: &'tcx hir::FnDecl<'tcx>,
63         body: &'tcx hir::Body<'tcx>,
64         gen: Option<hir::Movability>,
65         expected_sig: Option<ExpectedSig<'tcx>>,
66     ) -> Ty<'tcx> {
67         debug!("check_closure(opt_kind={:?}, expected_sig={:?})", opt_kind, expected_sig);
68
69         let expr_def_id = self.tcx.hir().local_def_id(expr.hir_id);
70
71         let ClosureSignatures { bound_sig, liberated_sig } =
72             self.sig_of_closure(expr_def_id.to_def_id(), decl, body, expected_sig);
73
74         debug!("check_closure: ty_of_closure returns {:?}", liberated_sig);
75
76         let generator_types =
77             check_fn(self, self.param_env, liberated_sig, decl, expr.hir_id, body, gen).1;
78
79         let base_substs = InternalSubsts::identity_for_item(
80             self.tcx,
81             self.tcx.closure_base_def_id(expr_def_id.to_def_id()),
82         );
83         // HACK(eddyb) this hardcodes indices into substs but it should rely on
84         // `ClosureSubsts` and `GeneratorSubsts` providing constructors, instead.
85         // That would also remove the need for most of the inference variables,
86         // as they immediately unified with the actual type below, including
87         // the `InferCtxt::closure_sig` and `ClosureSubsts::sig_ty` methods.
88         let tupled_upvars_idx = base_substs.len() + if generator_types.is_some() { 4 } else { 2 };
89         let substs =
90             base_substs.extend_to(self.tcx, expr_def_id.to_def_id(), |param, _| match param.kind {
91                 GenericParamDefKind::Lifetime => span_bug!(expr.span, "closure has lifetime param"),
92                 GenericParamDefKind::Type { .. } => if param.index as usize == tupled_upvars_idx {
93                     self.tcx.mk_tup(self.tcx.upvars_mentioned(expr_def_id).iter().flat_map(
94                         |upvars| {
95                             upvars.iter().map(|(&var_hir_id, _)| {
96                                 // Create type variables (for now) to represent the transformed
97                                 // types of upvars. These will be unified during the upvar
98                                 // inference phase (`upvar.rs`).
99                                 self.infcx.next_ty_var(TypeVariableOrigin {
100                                     // FIXME(eddyb) distinguish upvar inference variables from the rest.
101                                     kind: TypeVariableOriginKind::ClosureSynthetic,
102                                     span: self.tcx.hir().span(var_hir_id),
103                                 })
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(proj_predicate) =
210                     obligation.predicate.ignore_quantifiers().skip_binder().kind()
211                 {
212                     // Given a Projection predicate, we can potentially infer
213                     // the complete signature.
214                     self.deduce_sig_from_projection(
215                         Some(obligation.cause.span),
216                         ty::Binder::bind(proj_predicate),
217                     )
218                 } else {
219                     None
220                 }
221             });
222
223         // Even if we can't infer the full signature, we may be able to
224         // infer the kind. This can occur if there is a trait-reference
225         // like `F : Fn<A>`. Note that due to subtyping we could encounter
226         // many viable options, so pick the most restrictive.
227         let expected_kind = self
228             .obligations_for_self_ty(expected_vid)
229             .filter_map(|(tr, _)| self.tcx.fn_trait_kind_from_lang_item(tr.def_id()))
230             .fold(None, |best, cur| Some(best.map_or(cur, |best| cmp::min(best, cur))));
231
232         (expected_sig, expected_kind)
233     }
234
235     /// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce
236     /// everything we need to know about a closure or generator.
237     ///
238     /// The `cause_span` should be the span that caused us to
239     /// have this expected signature, or `None` if we can't readily
240     /// know that.
241     fn deduce_sig_from_projection(
242         &self,
243         cause_span: Option<Span>,
244         projection: ty::PolyProjectionPredicate<'tcx>,
245     ) -> Option<ExpectedSig<'tcx>> {
246         let tcx = self.tcx;
247
248         debug!("deduce_sig_from_projection({:?})", projection);
249
250         let trait_ref = projection.to_poly_trait_ref(tcx);
251
252         let is_fn = tcx.fn_trait_kind_from_lang_item(trait_ref.def_id()).is_some();
253         let gen_trait = tcx.require_lang_item(GeneratorTraitLangItem, cause_span);
254         let is_gen = gen_trait == trait_ref.def_id();
255         if !is_fn && !is_gen {
256             debug!("deduce_sig_from_projection: not fn or generator");
257             return None;
258         }
259
260         if is_gen {
261             // Check that we deduce the signature from the `<_ as std::ops::Generator>::Return`
262             // associated item and not yield.
263             let return_assoc_item =
264                 self.tcx.associated_items(gen_trait).in_definition_order().nth(1).unwrap().def_id;
265             if return_assoc_item != projection.projection_def_id() {
266                 debug!("deduce_sig_from_projection: not return assoc item of generator");
267                 return None;
268             }
269         }
270
271         let input_tys = if is_fn {
272             let arg_param_ty = trait_ref.skip_binder().substs.type_at(1);
273             let arg_param_ty = self.resolve_vars_if_possible(&arg_param_ty);
274             debug!("deduce_sig_from_projection: arg_param_ty={:?}", arg_param_ty);
275
276             match arg_param_ty.kind {
277                 ty::Tuple(tys) => tys.into_iter().map(|k| k.expect_ty()).collect::<Vec<_>>(),
278                 _ => return None,
279             }
280         } else {
281             // Generators with a `()` resume type may be defined with 0 or 1 explicit arguments,
282             // else they must have exactly 1 argument. For now though, just give up in this case.
283             return None;
284         };
285
286         let ret_param_ty = projection.skip_binder().ty;
287         let ret_param_ty = self.resolve_vars_if_possible(&ret_param_ty);
288         debug!("deduce_sig_from_projection: ret_param_ty={:?}", ret_param_ty);
289
290         let sig = self.tcx.mk_fn_sig(
291             input_tys.iter(),
292             &ret_param_ty,
293             false,
294             hir::Unsafety::Normal,
295             Abi::Rust,
296         );
297         debug!("deduce_sig_from_projection: sig={:?}", sig);
298
299         Some(ExpectedSig { cause_span, sig })
300     }
301
302     fn sig_of_closure(
303         &self,
304         expr_def_id: DefId,
305         decl: &hir::FnDecl<'_>,
306         body: &hir::Body<'_>,
307         expected_sig: Option<ExpectedSig<'tcx>>,
308     ) -> ClosureSignatures<'tcx> {
309         if let Some(e) = expected_sig {
310             self.sig_of_closure_with_expectation(expr_def_id, decl, body, e)
311         } else {
312             self.sig_of_closure_no_expectation(expr_def_id, decl, body)
313         }
314     }
315
316     /// If there is no expected signature, then we will convert the
317     /// types that the user gave into a signature.
318     fn sig_of_closure_no_expectation(
319         &self,
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(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         expr_def_id: DefId,
381         decl: &hir::FnDecl<'_>,
382         body: &hir::Body<'_>,
383         expected_sig: ExpectedSig<'tcx>,
384     ) -> ClosureSignatures<'tcx> {
385         debug!("sig_of_closure_with_expectation(expected_sig={:?})", expected_sig);
386
387         // Watch out for some surprises and just ignore the
388         // expectation if things don't see to match up with what we
389         // expect.
390         if expected_sig.sig.c_variadic != decl.c_variadic {
391             return self.sig_of_closure_no_expectation(expr_def_id, decl, body);
392         } else if expected_sig.sig.inputs_and_output.len() != decl.inputs.len() + 1 {
393             return self.sig_of_closure_with_mismatched_number_of_arguments(
394                 expr_def_id,
395                 decl,
396                 body,
397                 expected_sig,
398             );
399         }
400
401         // Create a `PolyFnSig`. Note the oddity that late bound
402         // regions appearing free in `expected_sig` are now bound up
403         // in this binder we are creating.
404         assert!(!expected_sig.sig.has_vars_bound_above(ty::INNERMOST));
405         let bound_sig = ty::Binder::bind(self.tcx.mk_fn_sig(
406             expected_sig.sig.inputs().iter().cloned(),
407             expected_sig.sig.output(),
408             decl.c_variadic,
409             hir::Unsafety::Normal,
410             Abi::RustCall,
411         ));
412
413         // `deduce_expectations_from_expected_type` introduces
414         // late-bound lifetimes defined elsewhere, which we now
415         // anonymize away, so as not to confuse the user.
416         let bound_sig = self.tcx.anonymize_late_bound_regions(&bound_sig);
417
418         let closure_sigs = self.closure_sigs(expr_def_id, body, bound_sig);
419
420         // Up till this point, we have ignored the annotations that the user
421         // gave. This function will check that they unify successfully.
422         // Along the way, it also writes out entries for types that the user
423         // wrote into our typeck results, which are then later used by the privacy
424         // check.
425         match self.check_supplied_sig_against_expectation(expr_def_id, decl, body, &closure_sigs) {
426             Ok(infer_ok) => self.register_infer_ok_obligations(infer_ok),
427             Err(_) => return self.sig_of_closure_no_expectation(expr_def_id, decl, body),
428         }
429
430         closure_sigs
431     }
432
433     fn sig_of_closure_with_mismatched_number_of_arguments(
434         &self,
435         expr_def_id: DefId,
436         decl: &hir::FnDecl<'_>,
437         body: &hir::Body<'_>,
438         expected_sig: ExpectedSig<'tcx>,
439     ) -> ClosureSignatures<'tcx> {
440         let hir = self.tcx.hir();
441         let expr_map_node = hir.get_if_local(expr_def_id).unwrap();
442         let expected_args: Vec<_> = expected_sig
443             .sig
444             .inputs()
445             .iter()
446             .map(|ty| ArgKind::from_expected_ty(ty, None))
447             .collect();
448         let (closure_span, found_args) = match self.get_fn_like_arguments(expr_map_node) {
449             Some((sp, args)) => (Some(sp), args),
450             None => (None, Vec::new()),
451         };
452         let expected_span =
453             expected_sig.cause_span.unwrap_or_else(|| hir.span_if_local(expr_def_id).unwrap());
454         self.report_arg_count_mismatch(
455             expected_span,
456             closure_span,
457             expected_args,
458             found_args,
459             true,
460         )
461         .emit();
462
463         let error_sig = self.error_sig_of_closure(decl);
464
465         self.closure_sigs(expr_def_id, body, error_sig)
466     }
467
468     /// Enforce the user's types against the expectation. See
469     /// `sig_of_closure_with_expectation` for details on the overall
470     /// strategy.
471     fn check_supplied_sig_against_expectation(
472         &self,
473         expr_def_id: DefId,
474         decl: &hir::FnDecl<'_>,
475         body: &hir::Body<'_>,
476         expected_sigs: &ClosureSignatures<'tcx>,
477     ) -> InferResult<'tcx, ()> {
478         // Get the signature S that the user gave.
479         //
480         // (See comment on `sig_of_closure_with_expectation` for the
481         // meaning of these letters.)
482         let supplied_sig = self.supplied_sig_of_closure(expr_def_id, decl, body);
483
484         debug!("check_supplied_sig_against_expectation: supplied_sig={:?}", supplied_sig);
485
486         // FIXME(#45727): As discussed in [this comment][c1], naively
487         // forcing equality here actually results in suboptimal error
488         // messages in some cases.  For now, if there would have been
489         // an obvious error, we fallback to declaring the type of the
490         // closure to be the one the user gave, which allows other
491         // error message code to trigger.
492         //
493         // However, I think [there is potential to do even better
494         // here][c2], since in *this* code we have the precise span of
495         // the type parameter in question in hand when we report the
496         // error.
497         //
498         // [c1]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341089706
499         // [c2]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341096796
500         self.infcx.commit_if_ok(|_| {
501             let mut all_obligations = vec![];
502
503             // The liberated version of this signature should be a subtype
504             // of the liberated form of the expectation.
505             for ((hir_ty, &supplied_ty), expected_ty) in decl
506                 .inputs
507                 .iter()
508                 .zip(supplied_sig.inputs().skip_binder()) // binder moved to (*) below
509                 .zip(expected_sigs.liberated_sig.inputs())
510             // `liberated_sig` is E'.
511             {
512                 // Instantiate (this part of..) S to S', i.e., with fresh variables.
513                 let (supplied_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars(
514                     hir_ty.span,
515                     LateBoundRegionConversionTime::FnCall,
516                     &ty::Binder::bind(supplied_ty),
517                 ); // recreated from (*) above
518
519                 // Check that E' = S'.
520                 let cause = self.misc(hir_ty.span);
521                 let InferOk { value: (), obligations } =
522                     self.at(&cause, self.param_env).eq(*expected_ty, supplied_ty)?;
523                 all_obligations.extend(obligations);
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.typeck_results.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::PredicateKind::Projection(proj_predicate) =
635                 obligation.predicate.ignore_quantifiers().skip_binder().kind()
636             {
637                 self.deduce_future_output_from_projection(
638                     obligation.cause.span,
639                     ty::Binder::bind(proj_predicate),
640                 )
641             } else {
642                 None
643             }
644         });
645
646         debug!("deduce_future_output_from_obligations: output_ty={:?}", output_ty);
647         output_ty
648     }
649
650     /// Given a projection like
651     ///
652     /// `<X as Future>::Output = T`
653     ///
654     /// where `X` is some type that has no late-bound regions, returns
655     /// `Some(T)`. If the projection is for some other trait, returns
656     /// `None`.
657     fn deduce_future_output_from_projection(
658         &self,
659         cause_span: Span,
660         predicate: ty::PolyProjectionPredicate<'tcx>,
661     ) -> Option<Ty<'tcx>> {
662         debug!("deduce_future_output_from_projection(predicate={:?})", predicate);
663
664         // We do not expect any bound regions in our predicate, so
665         // skip past the bound vars.
666         let predicate = match predicate.no_bound_vars() {
667             Some(p) => p,
668             None => {
669                 debug!("deduce_future_output_from_projection: has late-bound regions");
670                 return None;
671             }
672         };
673
674         // Check that this is a projection from the `Future` trait.
675         let trait_ref = predicate.projection_ty.trait_ref(self.tcx);
676         let future_trait = self.tcx.require_lang_item(FutureTraitLangItem, Some(cause_span));
677         if trait_ref.def_id != future_trait {
678             debug!("deduce_future_output_from_projection: not a future");
679             return None;
680         }
681
682         // The `Future` trait has only one associted item, `Output`,
683         // so check that this is what we see.
684         let output_assoc_item =
685             self.tcx.associated_items(future_trait).in_definition_order().next().unwrap().def_id;
686         if output_assoc_item != predicate.projection_ty.item_def_id {
687             span_bug!(
688                 cause_span,
689                 "projecting associated item `{:?}` from future, which is not Output `{:?}`",
690                 predicate.projection_ty.item_def_id,
691                 output_assoc_item,
692             );
693         }
694
695         // Extract the type from the projection. Note that there can
696         // be no bound variables in this type because the "self type"
697         // does not have any regions in it.
698         let output_ty = self.resolve_vars_if_possible(&predicate.ty);
699         debug!("deduce_future_output_from_projection: output_ty={:?}", output_ty);
700         Some(output_ty)
701     }
702
703     /// Converts the types that the user supplied, in case that doing
704     /// so should yield an error, but returns back a signature where
705     /// all parameters are of type `TyErr`.
706     fn error_sig_of_closure(&self, decl: &hir::FnDecl<'_>) -> ty::PolyFnSig<'tcx> {
707         let astconv: &dyn AstConv<'_> = self;
708
709         let supplied_arguments = decl.inputs.iter().map(|a| {
710             // Convert the types that the user supplied (if any), but ignore them.
711             astconv.ast_ty_to_ty(a);
712             self.tcx.ty_error()
713         });
714
715         if let hir::FnRetTy::Return(ref output) = decl.output {
716             astconv.ast_ty_to_ty(&output);
717         }
718
719         let result = ty::Binder::bind(self.tcx.mk_fn_sig(
720             supplied_arguments,
721             self.tcx.ty_error(),
722             decl.c_variadic,
723             hir::Unsafety::Normal,
724             Abi::RustCall,
725         ));
726
727         debug!("supplied_sig_of_closure: result={:?}", result);
728
729         result
730     }
731
732     fn closure_sigs(
733         &self,
734         expr_def_id: DefId,
735         body: &hir::Body<'_>,
736         bound_sig: ty::PolyFnSig<'tcx>,
737     ) -> ClosureSignatures<'tcx> {
738         let liberated_sig = self.tcx().liberate_late_bound_regions(expr_def_id, &bound_sig);
739         let liberated_sig = self.inh.normalize_associated_types_in(
740             body.value.span,
741             body.value.hir_id,
742             self.param_env,
743             &liberated_sig,
744         );
745         ClosureSignatures { bound_sig, liberated_sig }
746     }
747 }