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