]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/closure.rs
Rollup merge of #72414 - KodrAus:feat/stdlazy, r=Mark-Simulacrum
[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) = obligation.predicate.kind()
210                 {
211                     // Given a Projection predicate, we can potentially infer
212                     // the complete signature.
213                     self.deduce_sig_from_projection(Some(obligation.cause.span), proj_predicate)
214                 } else {
215                     None
216                 }
217             });
218
219         // Even if we can't infer the full signature, we may be able to
220         // infer the kind. This can occur if there is a trait-reference
221         // like `F : Fn<A>`. Note that due to subtyping we could encounter
222         // many viable options, so pick the most restrictive.
223         let expected_kind = self
224             .obligations_for_self_ty(expected_vid)
225             .filter_map(|(tr, _)| self.tcx.fn_trait_kind_from_lang_item(tr.def_id()))
226             .fold(None, |best, cur| Some(best.map_or(cur, |best| cmp::min(best, cur))));
227
228         (expected_sig, expected_kind)
229     }
230
231     /// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce
232     /// everything we need to know about a closure or generator.
233     ///
234     /// The `cause_span` should be the span that caused us to
235     /// have this expected signature, or `None` if we can't readily
236     /// know that.
237     fn deduce_sig_from_projection(
238         &self,
239         cause_span: Option<Span>,
240         projection: ty::PolyProjectionPredicate<'tcx>,
241     ) -> Option<ExpectedSig<'tcx>> {
242         let tcx = self.tcx;
243
244         debug!("deduce_sig_from_projection({:?})", projection);
245
246         let trait_ref = projection.to_poly_trait_ref(tcx);
247
248         let is_fn = tcx.fn_trait_kind_from_lang_item(trait_ref.def_id()).is_some();
249         let gen_trait = tcx.require_lang_item(GeneratorTraitLangItem, cause_span);
250         let is_gen = gen_trait == trait_ref.def_id();
251         if !is_fn && !is_gen {
252             debug!("deduce_sig_from_projection: not fn or generator");
253             return None;
254         }
255
256         if is_gen {
257             // Check that we deduce the signature from the `<_ as std::ops::Generator>::Return`
258             // associated item and not yield.
259             let return_assoc_item =
260                 self.tcx.associated_items(gen_trait).in_definition_order().nth(1).unwrap().def_id;
261             if return_assoc_item != projection.projection_def_id() {
262                 debug!("deduce_sig_from_projection: not return assoc item of generator");
263                 return None;
264             }
265         }
266
267         let input_tys = if is_fn {
268             let arg_param_ty = trait_ref.skip_binder().substs.type_at(1);
269             let arg_param_ty = self.resolve_vars_if_possible(&arg_param_ty);
270             debug!("deduce_sig_from_projection: arg_param_ty={:?}", arg_param_ty);
271
272             match arg_param_ty.kind {
273                 ty::Tuple(tys) => tys.into_iter().map(|k| k.expect_ty()).collect::<Vec<_>>(),
274                 _ => return None,
275             }
276         } else {
277             // Generators with a `()` resume type may be defined with 0 or 1 explicit arguments,
278             // else they must have exactly 1 argument. For now though, just give up in this case.
279             return None;
280         };
281
282         let ret_param_ty = projection.skip_binder().ty;
283         let ret_param_ty = self.resolve_vars_if_possible(&ret_param_ty);
284         debug!("deduce_sig_from_projection: ret_param_ty={:?}", ret_param_ty);
285
286         let sig = self.tcx.mk_fn_sig(
287             input_tys.iter(),
288             &ret_param_ty,
289             false,
290             hir::Unsafety::Normal,
291             Abi::Rust,
292         );
293         debug!("deduce_sig_from_projection: sig={:?}", sig);
294
295         Some(ExpectedSig { cause_span, sig })
296     }
297
298     fn sig_of_closure(
299         &self,
300         expr_def_id: DefId,
301         decl: &hir::FnDecl<'_>,
302         body: &hir::Body<'_>,
303         expected_sig: Option<ExpectedSig<'tcx>>,
304     ) -> ClosureSignatures<'tcx> {
305         if let Some(e) = expected_sig {
306             self.sig_of_closure_with_expectation(expr_def_id, decl, body, e)
307         } else {
308             self.sig_of_closure_no_expectation(expr_def_id, decl, body)
309         }
310     }
311
312     /// If there is no expected signature, then we will convert the
313     /// types that the user gave into a signature.
314     fn sig_of_closure_no_expectation(
315         &self,
316         expr_def_id: DefId,
317         decl: &hir::FnDecl<'_>,
318         body: &hir::Body<'_>,
319     ) -> ClosureSignatures<'tcx> {
320         debug!("sig_of_closure_no_expectation()");
321
322         let bound_sig = self.supplied_sig_of_closure(expr_def_id, decl, body);
323
324         self.closure_sigs(expr_def_id, body, bound_sig)
325     }
326
327     /// Invoked to compute the signature of a closure expression. This
328     /// combines any user-provided type annotations (e.g., `|x: u32|
329     /// -> u32 { .. }`) with the expected signature.
330     ///
331     /// The approach is as follows:
332     ///
333     /// - Let `S` be the (higher-ranked) signature that we derive from the user's annotations.
334     /// - Let `E` be the (higher-ranked) signature that we derive from the expectations, if any.
335     ///   - If we have no expectation `E`, then the signature of the closure is `S`.
336     ///   - Otherwise, the signature of the closure is E. Moreover:
337     ///     - Skolemize the late-bound regions in `E`, yielding `E'`.
338     ///     - Instantiate all the late-bound regions bound in the closure within `S`
339     ///       with fresh (existential) variables, yielding `S'`
340     ///     - Require that `E' = S'`
341     ///       - We could use some kind of subtyping relationship here,
342     ///         I imagine, but equality is easier and works fine for
343     ///         our purposes.
344     ///
345     /// The key intuition here is that the user's types must be valid
346     /// from "the inside" of the closure, but the expectation
347     /// ultimately drives the overall signature.
348     ///
349     /// # Examples
350     ///
351     /// ```
352     /// fn with_closure<F>(_: F)
353     ///   where F: Fn(&u32) -> &u32 { .. }
354     ///
355     /// with_closure(|x: &u32| { ... })
356     /// ```
357     ///
358     /// Here:
359     /// - E would be `fn(&u32) -> &u32`.
360     /// - S would be `fn(&u32) ->
361     /// - E' is `&'!0 u32 -> &'!0 u32`
362     /// - S' is `&'?0 u32 -> ?T`
363     ///
364     /// S' can be unified with E' with `['?0 = '!0, ?T = &'!10 u32]`.
365     ///
366     /// # Arguments
367     ///
368     /// - `expr_def_id`: the `DefId` of the closure expression
369     /// - `decl`: the HIR declaration of the closure
370     /// - `body`: the body of the closure
371     /// - `expected_sig`: the expected signature (if any). Note that
372     ///   this is missing a binder: that is, there may be late-bound
373     ///   regions with depth 1, which are bound then by the closure.
374     fn sig_of_closure_with_expectation(
375         &self,
376         expr_def_id: DefId,
377         decl: &hir::FnDecl<'_>,
378         body: &hir::Body<'_>,
379         expected_sig: ExpectedSig<'tcx>,
380     ) -> ClosureSignatures<'tcx> {
381         debug!("sig_of_closure_with_expectation(expected_sig={:?})", expected_sig);
382
383         // Watch out for some surprises and just ignore the
384         // expectation if things don't see to match up with what we
385         // expect.
386         if expected_sig.sig.c_variadic != decl.c_variadic {
387             return self.sig_of_closure_no_expectation(expr_def_id, decl, body);
388         } else if expected_sig.sig.inputs_and_output.len() != decl.inputs.len() + 1 {
389             return self.sig_of_closure_with_mismatched_number_of_arguments(
390                 expr_def_id,
391                 decl,
392                 body,
393                 expected_sig,
394             );
395         }
396
397         // Create a `PolyFnSig`. Note the oddity that late bound
398         // regions appearing free in `expected_sig` are now bound up
399         // in this binder we are creating.
400         assert!(!expected_sig.sig.has_vars_bound_above(ty::INNERMOST));
401         let bound_sig = ty::Binder::bind(self.tcx.mk_fn_sig(
402             expected_sig.sig.inputs().iter().cloned(),
403             expected_sig.sig.output(),
404             decl.c_variadic,
405             hir::Unsafety::Normal,
406             Abi::RustCall,
407         ));
408
409         // `deduce_expectations_from_expected_type` introduces
410         // late-bound lifetimes defined elsewhere, which we now
411         // anonymize away, so as not to confuse the user.
412         let bound_sig = self.tcx.anonymize_late_bound_regions(&bound_sig);
413
414         let closure_sigs = self.closure_sigs(expr_def_id, body, bound_sig);
415
416         // Up till this point, we have ignored the annotations that the user
417         // gave. This function will check that they unify successfully.
418         // Along the way, it also writes out entries for types that the user
419         // wrote into our typeck results, which are then later used by the privacy
420         // check.
421         match self.check_supplied_sig_against_expectation(expr_def_id, decl, body, &closure_sigs) {
422             Ok(infer_ok) => self.register_infer_ok_obligations(infer_ok),
423             Err(_) => return self.sig_of_closure_no_expectation(expr_def_id, decl, body),
424         }
425
426         closure_sigs
427     }
428
429     fn sig_of_closure_with_mismatched_number_of_arguments(
430         &self,
431         expr_def_id: DefId,
432         decl: &hir::FnDecl<'_>,
433         body: &hir::Body<'_>,
434         expected_sig: ExpectedSig<'tcx>,
435     ) -> ClosureSignatures<'tcx> {
436         let hir = self.tcx.hir();
437         let expr_map_node = hir.get_if_local(expr_def_id).unwrap();
438         let expected_args: Vec<_> = expected_sig
439             .sig
440             .inputs()
441             .iter()
442             .map(|ty| ArgKind::from_expected_ty(ty, None))
443             .collect();
444         let (closure_span, found_args) = match self.get_fn_like_arguments(expr_map_node) {
445             Some((sp, args)) => (Some(sp), args),
446             None => (None, Vec::new()),
447         };
448         let expected_span =
449             expected_sig.cause_span.unwrap_or_else(|| hir.span_if_local(expr_def_id).unwrap());
450         self.report_arg_count_mismatch(
451             expected_span,
452             closure_span,
453             expected_args,
454             found_args,
455             true,
456         )
457         .emit();
458
459         let error_sig = self.error_sig_of_closure(decl);
460
461         self.closure_sigs(expr_def_id, body, error_sig)
462     }
463
464     /// Enforce the user's types against the expectation. See
465     /// `sig_of_closure_with_expectation` for details on the overall
466     /// strategy.
467     fn check_supplied_sig_against_expectation(
468         &self,
469         expr_def_id: DefId,
470         decl: &hir::FnDecl<'_>,
471         body: &hir::Body<'_>,
472         expected_sigs: &ClosureSignatures<'tcx>,
473     ) -> InferResult<'tcx, ()> {
474         // Get the signature S that the user gave.
475         //
476         // (See comment on `sig_of_closure_with_expectation` for the
477         // meaning of these letters.)
478         let supplied_sig = self.supplied_sig_of_closure(expr_def_id, decl, body);
479
480         debug!("check_supplied_sig_against_expectation: supplied_sig={:?}", supplied_sig);
481
482         // FIXME(#45727): As discussed in [this comment][c1], naively
483         // forcing equality here actually results in suboptimal error
484         // messages in some cases.  For now, if there would have been
485         // an obvious error, we fallback to declaring the type of the
486         // closure to be the one the user gave, which allows other
487         // error message code to trigger.
488         //
489         // However, I think [there is potential to do even better
490         // here][c2], since in *this* code we have the precise span of
491         // the type parameter in question in hand when we report the
492         // error.
493         //
494         // [c1]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341089706
495         // [c2]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341096796
496         self.infcx.commit_if_ok(|_| {
497             let mut all_obligations = vec![];
498
499             // The liberated version of this signature should be a subtype
500             // of the liberated form of the expectation.
501             for ((hir_ty, &supplied_ty), expected_ty) in decl
502                 .inputs
503                 .iter()
504                 .zip(supplied_sig.inputs().skip_binder()) // binder moved to (*) below
505                 .zip(expected_sigs.liberated_sig.inputs())
506             // `liberated_sig` is E'.
507             {
508                 // Instantiate (this part of..) S to S', i.e., with fresh variables.
509                 let (supplied_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars(
510                     hir_ty.span,
511                     LateBoundRegionConversionTime::FnCall,
512                     &ty::Binder::bind(supplied_ty),
513                 ); // recreated from (*) above
514
515                 // Check that E' = S'.
516                 let cause = self.misc(hir_ty.span);
517                 let InferOk { value: (), obligations } =
518                     self.at(&cause, self.param_env).eq(*expected_ty, supplied_ty)?;
519                 all_obligations.extend(obligations);
520             }
521
522             let (supplied_output_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars(
523                 decl.output.span(),
524                 LateBoundRegionConversionTime::FnCall,
525                 &supplied_sig.output(),
526             );
527             let cause = &self.misc(decl.output.span());
528             let InferOk { value: (), obligations } = self
529                 .at(cause, self.param_env)
530                 .eq(expected_sigs.liberated_sig.output(), supplied_output_ty)?;
531             all_obligations.extend(obligations);
532
533             Ok(InferOk { value: (), obligations: all_obligations })
534         })
535     }
536
537     /// If there is no expected signature, then we will convert the
538     /// types that the user gave into a signature.
539     ///
540     /// Also, record this closure signature for later.
541     fn supplied_sig_of_closure(
542         &self,
543         expr_def_id: DefId,
544         decl: &hir::FnDecl<'_>,
545         body: &hir::Body<'_>,
546     ) -> ty::PolyFnSig<'tcx> {
547         let astconv: &dyn AstConv<'_> = self;
548
549         debug!(
550             "supplied_sig_of_closure(decl={:?}, body.generator_kind={:?})",
551             decl, body.generator_kind,
552         );
553
554         // First, convert the types that the user supplied (if any).
555         let supplied_arguments = decl.inputs.iter().map(|a| astconv.ast_ty_to_ty(a));
556         let supplied_return = match decl.output {
557             hir::FnRetTy::Return(ref output) => astconv.ast_ty_to_ty(&output),
558             hir::FnRetTy::DefaultReturn(_) => match body.generator_kind {
559                 // In the case of the async block that we create for a function body,
560                 // we expect the return type of the block to match that of the enclosing
561                 // function.
562                 Some(hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn)) => {
563                     debug!("supplied_sig_of_closure: closure is async fn body");
564                     self.deduce_future_output_from_obligations(expr_def_id).unwrap_or_else(|| {
565                         // AFAIK, deducing the future output
566                         // always succeeds *except* in error cases
567                         // like #65159. I'd like to return Error
568                         // here, but I can't because I can't
569                         // easily (and locally) prove that we
570                         // *have* reported an
571                         // error. --nikomatsakis
572                         astconv.ty_infer(None, decl.output.span())
573                     })
574                 }
575
576                 _ => astconv.ty_infer(None, decl.output.span()),
577             },
578         };
579
580         let result = ty::Binder::bind(self.tcx.mk_fn_sig(
581             supplied_arguments,
582             supplied_return,
583             decl.c_variadic,
584             hir::Unsafety::Normal,
585             Abi::RustCall,
586         ));
587
588         debug!("supplied_sig_of_closure: result={:?}", result);
589
590         let c_result = self.inh.infcx.canonicalize_response(&result);
591         self.typeck_results.borrow_mut().user_provided_sigs.insert(expr_def_id, c_result);
592
593         result
594     }
595
596     /// Invoked when we are translating the generator that results
597     /// from desugaring an `async fn`. Returns the "sugared" return
598     /// type of the `async fn` -- that is, the return type that the
599     /// user specified. The "desugared" return type is a `impl
600     /// Future<Output = T>`, so we do this by searching through the
601     /// obligations to extract the `T`.
602     fn deduce_future_output_from_obligations(&self, expr_def_id: DefId) -> Option<Ty<'tcx>> {
603         debug!("deduce_future_output_from_obligations(expr_def_id={:?})", expr_def_id);
604
605         let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
606             span_bug!(self.tcx.def_span(expr_def_id), "async fn generator outside of a fn")
607         });
608
609         // In practice, the return type of the surrounding function is
610         // always a (not yet resolved) inference variable, because it
611         // is the hidden type for an `impl Trait` that we are going to
612         // be inferring.
613         let ret_ty = ret_coercion.borrow().expected_ty();
614         let ret_ty = self.inh.infcx.shallow_resolve(ret_ty);
615         let ret_vid = match ret_ty.kind {
616             ty::Infer(ty::TyVar(ret_vid)) => ret_vid,
617             _ => span_bug!(
618                 self.tcx.def_span(expr_def_id),
619                 "async fn generator return type not an inference variable"
620             ),
621         };
622
623         // Search for a pending obligation like
624         //
625         // `<R as Future>::Output = T`
626         //
627         // where R is the return type we are expecting. This type `T`
628         // will be our output.
629         let output_ty = self.obligations_for_self_ty(ret_vid).find_map(|(_, obligation)| {
630             if let &ty::PredicateKind::Projection(proj_predicate) = obligation.predicate.kind() {
631                 self.deduce_future_output_from_projection(obligation.cause.span, proj_predicate)
632             } else {
633                 None
634             }
635         });
636
637         debug!("deduce_future_output_from_obligations: output_ty={:?}", output_ty);
638         output_ty
639     }
640
641     /// Given a projection like
642     ///
643     /// `<X as Future>::Output = T`
644     ///
645     /// where `X` is some type that has no late-bound regions, returns
646     /// `Some(T)`. If the projection is for some other trait, returns
647     /// `None`.
648     fn deduce_future_output_from_projection(
649         &self,
650         cause_span: Span,
651         predicate: ty::PolyProjectionPredicate<'tcx>,
652     ) -> Option<Ty<'tcx>> {
653         debug!("deduce_future_output_from_projection(predicate={:?})", predicate);
654
655         // We do not expect any bound regions in our predicate, so
656         // skip past the bound vars.
657         let predicate = match predicate.no_bound_vars() {
658             Some(p) => p,
659             None => {
660                 debug!("deduce_future_output_from_projection: has late-bound regions");
661                 return None;
662             }
663         };
664
665         // Check that this is a projection from the `Future` trait.
666         let trait_ref = predicate.projection_ty.trait_ref(self.tcx);
667         let future_trait = self.tcx.require_lang_item(FutureTraitLangItem, Some(cause_span));
668         if trait_ref.def_id != future_trait {
669             debug!("deduce_future_output_from_projection: not a future");
670             return None;
671         }
672
673         // The `Future` trait has only one associted item, `Output`,
674         // so check that this is what we see.
675         let output_assoc_item =
676             self.tcx.associated_items(future_trait).in_definition_order().next().unwrap().def_id;
677         if output_assoc_item != predicate.projection_ty.item_def_id {
678             span_bug!(
679                 cause_span,
680                 "projecting associated item `{:?}` from future, which is not Output `{:?}`",
681                 predicate.projection_ty.item_def_id,
682                 output_assoc_item,
683             );
684         }
685
686         // Extract the type from the projection. Note that there can
687         // be no bound variables in this type because the "self type"
688         // does not have any regions in it.
689         let output_ty = self.resolve_vars_if_possible(&predicate.ty);
690         debug!("deduce_future_output_from_projection: output_ty={:?}", output_ty);
691         Some(output_ty)
692     }
693
694     /// Converts the types that the user supplied, in case that doing
695     /// so should yield an error, but returns back a signature where
696     /// all parameters are of type `TyErr`.
697     fn error_sig_of_closure(&self, decl: &hir::FnDecl<'_>) -> ty::PolyFnSig<'tcx> {
698         let astconv: &dyn AstConv<'_> = self;
699
700         let supplied_arguments = decl.inputs.iter().map(|a| {
701             // Convert the types that the user supplied (if any), but ignore them.
702             astconv.ast_ty_to_ty(a);
703             self.tcx.ty_error()
704         });
705
706         if let hir::FnRetTy::Return(ref output) = decl.output {
707             astconv.ast_ty_to_ty(&output);
708         }
709
710         let result = ty::Binder::bind(self.tcx.mk_fn_sig(
711             supplied_arguments,
712             self.tcx.ty_error(),
713             decl.c_variadic,
714             hir::Unsafety::Normal,
715             Abi::RustCall,
716         ));
717
718         debug!("supplied_sig_of_closure: result={:?}", result);
719
720         result
721     }
722
723     fn closure_sigs(
724         &self,
725         expr_def_id: DefId,
726         body: &hir::Body<'_>,
727         bound_sig: ty::PolyFnSig<'tcx>,
728     ) -> ClosureSignatures<'tcx> {
729         let liberated_sig = self.tcx().liberate_late_bound_regions(expr_def_id, &bound_sig);
730         let liberated_sig = self.inh.normalize_associated_types_in(
731             body.value.span,
732             body.value.hir_id,
733             self.param_env,
734             &liberated_sig,
735         );
736         ClosureSignatures { bound_sig, liberated_sig }
737     }
738 }