1 //! Code for type-checking closure expressions.
3 use super::{check_fn, Expectation, FnCtxt, GeneratorTypes};
7 use rustc_hir::def_id::DefId;
8 use rustc_hir::lang_items::LangItem;
9 use rustc_hir_analysis::astconv::AstConv;
10 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
11 use rustc_infer::infer::LateBoundRegionConversionTime;
12 use rustc_infer::infer::{InferOk, InferResult};
13 use rustc_middle::ty::subst::InternalSubsts;
14 use rustc_middle::ty::visit::TypeVisitable;
15 use rustc_middle::ty::{self, Ty};
16 use rustc_span::source_map::Span;
17 use rustc_target::spec::abi::Abi;
18 use rustc_trait_selection::traits;
19 use rustc_trait_selection::traits::error_reporting::ArgKind;
20 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
24 /// What signature do we *expect* the closure to have from context?
26 struct ExpectedSig<'tcx> {
27 /// Span that gave us this expectation, if we know that.
28 cause_span: Option<Span>,
29 sig: ty::PolyFnSig<'tcx>,
32 struct ClosureSignatures<'tcx> {
33 /// The signature users of the closure see.
34 bound_sig: ty::PolyFnSig<'tcx>,
35 /// The signature within the function body.
36 /// This mostly differs in the sense that lifetimes are now early bound and any
37 /// opaque types from the signature expectation are overriden in case there are
38 /// explicit hidden types written by the user in the closure signature.
39 liberated_sig: ty::FnSig<'tcx>,
42 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
43 #[instrument(skip(self, expr, _capture, decl, body_id), level = "debug")]
44 pub fn check_expr_closure(
47 _capture: hir::CaptureBy,
48 decl: &'tcx hir::FnDecl<'tcx>,
50 gen: Option<hir::Movability>,
51 expected: Expectation<'tcx>,
53 trace!("decl = {:#?}", decl);
54 trace!("expr = {:#?}", expr);
56 // It's always helpful for inference if we know the kind of
57 // closure sooner rather than later, so first examine the expected
58 // type, and see if can glean a closure kind from there.
59 let (expected_sig, expected_kind) = match expected.to_option(self) {
60 Some(ty) => self.deduce_expectations_from_expected_type(ty),
63 let body = self.tcx.hir().body(body_id);
64 self.check_closure(expr, expected_kind, decl, body, gen, expected_sig)
67 #[instrument(skip(self, expr, body, decl), level = "debug", ret)]
71 opt_kind: Option<ty::ClosureKind>,
72 decl: &'tcx hir::FnDecl<'tcx>,
73 body: &'tcx hir::Body<'tcx>,
74 gen: Option<hir::Movability>,
75 expected_sig: Option<ExpectedSig<'tcx>>,
77 trace!("decl = {:#?}", decl);
78 let expr_def_id = self.tcx.hir().local_def_id(expr.hir_id);
81 let ClosureSignatures { bound_sig, liberated_sig } =
82 self.sig_of_closure(expr.hir_id, expr_def_id.to_def_id(), decl, body, expected_sig);
84 debug!(?bound_sig, ?liberated_sig);
86 let return_type_pre_known = !liberated_sig.output().is_ty_infer();
88 let generator_types = check_fn(
90 self.param_env.without_const(),
96 return_type_pre_known,
100 let parent_substs = InternalSubsts::identity_for_item(
102 self.tcx.typeck_root_def_id(expr_def_id.to_def_id()),
105 let tupled_upvars_ty = self.next_ty_var(TypeVariableOrigin {
106 kind: TypeVariableOriginKind::ClosureSynthetic,
107 span: self.tcx.hir().span(expr.hir_id),
110 if let Some(GeneratorTypes { resume_ty, yield_ty, interior, movability }) = generator_types
112 let generator_substs = ty::GeneratorSubsts::new(
114 ty::GeneratorSubstsParts {
118 return_ty: liberated_sig.output(),
124 return self.tcx.mk_generator(
125 expr_def_id.to_def_id(),
126 generator_substs.substs,
131 // Tuple up the arguments and insert the resulting function type into
132 // the `closures` table.
133 let sig = bound_sig.map_bound(|sig| {
135 iter::once(self.tcx.intern_tup(sig.inputs())),
143 debug!(?sig, ?opt_kind);
145 let closure_kind_ty = match opt_kind {
146 Some(kind) => kind.to_ty(self.tcx),
148 // Create a type variable (for now) to represent the closure kind.
149 // It will be unified during the upvar inference phase (`upvar.rs`)
150 None => self.next_ty_var(TypeVariableOrigin {
151 // FIXME(eddyb) distinguish closure kind inference variables from the rest.
152 kind: TypeVariableOriginKind::ClosureSynthetic,
157 let closure_substs = ty::ClosureSubsts::new(
159 ty::ClosureSubstsParts {
162 closure_sig_as_fn_ptr_ty: self.tcx.mk_fn_ptr(sig),
167 self.tcx.mk_closure(expr_def_id.to_def_id(), closure_substs.substs)
170 /// Given the expected type, figures out what it can about this closure we
171 /// are about to type check:
172 #[instrument(skip(self), level = "debug")]
173 fn deduce_expectations_from_expected_type(
175 expected_ty: Ty<'tcx>,
176 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
177 match *expected_ty.kind() {
178 ty::Opaque(def_id, substs) => {
179 let bounds = self.tcx.bound_explicit_item_bounds(def_id);
181 bounds.subst_iter_copied(self.tcx, substs).find_map(|(pred, span)| match pred
185 ty::PredicateKind::Projection(proj_predicate) => self
186 .deduce_sig_from_projection(
188 pred.kind().rebind(proj_predicate),
196 .filter_map(|(pred, _)| match pred.kind().skip_binder() {
197 ty::PredicateKind::Trait(tp) => {
198 self.tcx.fn_trait_kind_from_lang_item(tp.def_id())
202 .fold(None, |best, cur| Some(best.map_or(cur, |best| cmp::min(best, cur))));
206 ty::Dynamic(ref object_type, ..) => {
207 let sig = object_type.projection_bounds().find_map(|pb| {
208 let pb = pb.with_self_ty(self.tcx, self.tcx.types.trait_object_dummy_self);
209 self.deduce_sig_from_projection(None, pb)
211 let kind = object_type
213 .and_then(|did| self.tcx.fn_trait_kind_from_lang_item(did));
216 ty::Infer(ty::TyVar(vid)) => self.deduce_expectations_from_obligations(vid),
218 let expected_sig = ExpectedSig { cause_span: None, sig };
219 (Some(expected_sig), Some(ty::ClosureKind::Fn))
225 fn deduce_expectations_from_obligations(
227 expected_vid: ty::TyVid,
228 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
229 let mut expected_sig = None;
230 let mut expected_kind = None;
232 for obligation in traits::elaborate_obligations(
234 // Reverse the obligations here, since `elaborate_*` uses a stack,
235 // and we want to keep inference generally in the same order of
236 // the registered obligations.
237 self.obligations_for_self_ty(expected_vid).rev().collect(),
239 debug!(?obligation.predicate);
240 let bound_predicate = obligation.predicate.kind();
242 // Given a Projection predicate, we can potentially infer
243 // the complete signature.
244 if expected_sig.is_none()
245 && let ty::PredicateKind::Projection(proj_predicate) = bound_predicate.skip_binder()
247 expected_sig = self.deduce_sig_from_projection(
248 Some(obligation.cause.span),
249 bound_predicate.rebind(proj_predicate),
253 // Even if we can't infer the full signature, we may be able to
254 // infer the kind. This can occur when we elaborate a predicate
255 // like `F : Fn<A>`. Note that due to subtyping we could encounter
256 // many viable options, so pick the most restrictive.
257 let trait_def_id = match bound_predicate.skip_binder() {
258 ty::PredicateKind::Projection(data) => {
259 Some(data.projection_ty.trait_def_id(self.tcx))
261 ty::PredicateKind::Trait(data) => Some(data.def_id()),
264 if let Some(closure_kind) =
265 trait_def_id.and_then(|def_id| self.tcx.fn_trait_kind_from_lang_item(def_id))
267 expected_kind = Some(
269 .map_or_else(|| closure_kind, |current| cmp::min(current, closure_kind)),
274 (expected_sig, expected_kind)
277 /// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce
278 /// everything we need to know about a closure or generator.
280 /// The `cause_span` should be the span that caused us to
281 /// have this expected signature, or `None` if we can't readily
283 #[instrument(level = "debug", skip(self, cause_span), ret)]
284 fn deduce_sig_from_projection(
286 cause_span: Option<Span>,
287 projection: ty::PolyProjectionPredicate<'tcx>,
288 ) -> Option<ExpectedSig<'tcx>> {
291 let trait_def_id = projection.trait_def_id(tcx);
293 let is_fn = tcx.fn_trait_kind_from_lang_item(trait_def_id).is_some();
294 let gen_trait = tcx.require_lang_item(LangItem::Generator, cause_span);
295 let is_gen = gen_trait == trait_def_id;
296 if !is_fn && !is_gen {
297 debug!("not fn or generator");
302 // Check that we deduce the signature from the `<_ as std::ops::Generator>::Return`
303 // associated item and not yield.
304 let return_assoc_item = self.tcx.associated_item_def_ids(gen_trait)[1];
305 if return_assoc_item != projection.projection_def_id() {
306 debug!("not return assoc item of generator");
311 let input_tys = if is_fn {
312 let arg_param_ty = projection.skip_binder().projection_ty.substs.type_at(1);
313 let arg_param_ty = self.resolve_vars_if_possible(arg_param_ty);
314 debug!(?arg_param_ty);
316 match arg_param_ty.kind() {
317 &ty::Tuple(tys) => tys,
321 // Generators with a `()` resume type may be defined with 0 or 1 explicit arguments,
322 // else they must have exactly 1 argument. For now though, just give up in this case.
326 // Since this is a return parameter type it is safe to unwrap.
327 let ret_param_ty = projection.skip_binder().term.ty().unwrap();
328 let ret_param_ty = self.resolve_vars_if_possible(ret_param_ty);
329 debug!(?ret_param_ty);
331 let sig = projection.rebind(self.tcx.mk_fn_sig(
335 hir::Unsafety::Normal,
339 Some(ExpectedSig { cause_span, sig })
346 decl: &hir::FnDecl<'_>,
347 body: &hir::Body<'_>,
348 expected_sig: Option<ExpectedSig<'tcx>>,
349 ) -> ClosureSignatures<'tcx> {
350 if let Some(e) = expected_sig {
351 self.sig_of_closure_with_expectation(hir_id, expr_def_id, decl, body, e)
353 self.sig_of_closure_no_expectation(hir_id, expr_def_id, decl, body)
357 /// If there is no expected signature, then we will convert the
358 /// types that the user gave into a signature.
359 #[instrument(skip(self, hir_id, expr_def_id, decl, body), level = "debug")]
360 fn sig_of_closure_no_expectation(
364 decl: &hir::FnDecl<'_>,
365 body: &hir::Body<'_>,
366 ) -> ClosureSignatures<'tcx> {
367 let bound_sig = self.supplied_sig_of_closure(hir_id, expr_def_id, decl, body);
369 self.closure_sigs(expr_def_id, body, bound_sig)
372 /// Invoked to compute the signature of a closure expression. This
373 /// combines any user-provided type annotations (e.g., `|x: u32|
374 /// -> u32 { .. }`) with the expected signature.
376 /// The approach is as follows:
378 /// - Let `S` be the (higher-ranked) signature that we derive from the user's annotations.
379 /// - Let `E` be the (higher-ranked) signature that we derive from the expectations, if any.
380 /// - If we have no expectation `E`, then the signature of the closure is `S`.
381 /// - Otherwise, the signature of the closure is E. Moreover:
382 /// - Skolemize the late-bound regions in `E`, yielding `E'`.
383 /// - Instantiate all the late-bound regions bound in the closure within `S`
384 /// with fresh (existential) variables, yielding `S'`
385 /// - Require that `E' = S'`
386 /// - We could use some kind of subtyping relationship here,
387 /// I imagine, but equality is easier and works fine for
390 /// The key intuition here is that the user's types must be valid
391 /// from "the inside" of the closure, but the expectation
392 /// ultimately drives the overall signature.
396 /// ```ignore (illustrative)
397 /// fn with_closure<F>(_: F)
398 /// where F: Fn(&u32) -> &u32 { .. }
400 /// with_closure(|x: &u32| { ... })
404 /// - E would be `fn(&u32) -> &u32`.
405 /// - S would be `fn(&u32) ->
406 /// - E' is `&'!0 u32 -> &'!0 u32`
407 /// - S' is `&'?0 u32 -> ?T`
409 /// S' can be unified with E' with `['?0 = '!0, ?T = &'!10 u32]`.
413 /// - `expr_def_id`: the `DefId` of the closure expression
414 /// - `decl`: the HIR declaration of the closure
415 /// - `body`: the body of the closure
416 /// - `expected_sig`: the expected signature (if any). Note that
417 /// this is missing a binder: that is, there may be late-bound
418 /// regions with depth 1, which are bound then by the closure.
419 #[instrument(skip(self, hir_id, expr_def_id, decl, body), level = "debug")]
420 fn sig_of_closure_with_expectation(
424 decl: &hir::FnDecl<'_>,
425 body: &hir::Body<'_>,
426 expected_sig: ExpectedSig<'tcx>,
427 ) -> ClosureSignatures<'tcx> {
428 // Watch out for some surprises and just ignore the
429 // expectation if things don't see to match up with what we
431 if expected_sig.sig.c_variadic() != decl.c_variadic {
432 return self.sig_of_closure_no_expectation(hir_id, expr_def_id, decl, body);
433 } else if expected_sig.sig.skip_binder().inputs_and_output.len() != decl.inputs.len() + 1 {
434 return self.sig_of_closure_with_mismatched_number_of_arguments(
442 // Create a `PolyFnSig`. Note the oddity that late bound
443 // regions appearing free in `expected_sig` are now bound up
444 // in this binder we are creating.
445 assert!(!expected_sig.sig.skip_binder().has_vars_bound_above(ty::INNERMOST));
446 let bound_sig = expected_sig.sig.map_bound(|sig| {
448 sig.inputs().iter().cloned(),
451 hir::Unsafety::Normal,
456 // `deduce_expectations_from_expected_type` introduces
457 // late-bound lifetimes defined elsewhere, which we now
458 // anonymize away, so as not to confuse the user.
459 let bound_sig = self.tcx.anonymize_late_bound_regions(bound_sig);
461 let closure_sigs = self.closure_sigs(expr_def_id, body, bound_sig);
463 // Up till this point, we have ignored the annotations that the user
464 // gave. This function will check that they unify successfully.
465 // Along the way, it also writes out entries for types that the user
466 // wrote into our typeck results, which are then later used by the privacy
468 match self.merge_supplied_sig_with_expectation(
475 Ok(infer_ok) => self.register_infer_ok_obligations(infer_ok),
476 Err(_) => self.sig_of_closure_no_expectation(hir_id, expr_def_id, decl, body),
480 fn sig_of_closure_with_mismatched_number_of_arguments(
483 decl: &hir::FnDecl<'_>,
484 body: &hir::Body<'_>,
485 expected_sig: ExpectedSig<'tcx>,
486 ) -> ClosureSignatures<'tcx> {
487 let hir = self.tcx.hir();
488 let expr_map_node = hir.get_if_local(expr_def_id).unwrap();
489 let expected_args: Vec<_> = expected_sig
494 .map(|ty| ArgKind::from_expected_ty(*ty, None))
496 let (closure_span, found_args) = match self.get_fn_like_arguments(expr_map_node) {
497 Some((sp, args)) => (Some(sp), args),
498 None => (None, Vec::new()),
501 expected_sig.cause_span.unwrap_or_else(|| hir.span_if_local(expr_def_id).unwrap());
502 self.report_arg_count_mismatch(
511 let error_sig = self.error_sig_of_closure(decl);
513 self.closure_sigs(expr_def_id, body, error_sig)
516 /// Enforce the user's types against the expectation. See
517 /// `sig_of_closure_with_expectation` for details on the overall
519 #[instrument(level = "debug", skip(self, hir_id, expr_def_id, decl, body, expected_sigs))]
520 fn merge_supplied_sig_with_expectation(
524 decl: &hir::FnDecl<'_>,
525 body: &hir::Body<'_>,
526 mut expected_sigs: ClosureSignatures<'tcx>,
527 ) -> InferResult<'tcx, ClosureSignatures<'tcx>> {
528 // Get the signature S that the user gave.
530 // (See comment on `sig_of_closure_with_expectation` for the
531 // meaning of these letters.)
532 let supplied_sig = self.supplied_sig_of_closure(hir_id, expr_def_id, decl, body);
534 debug!(?supplied_sig);
536 // FIXME(#45727): As discussed in [this comment][c1], naively
537 // forcing equality here actually results in suboptimal error
538 // messages in some cases. For now, if there would have been
539 // an obvious error, we fallback to declaring the type of the
540 // closure to be the one the user gave, which allows other
541 // error message code to trigger.
543 // However, I think [there is potential to do even better
544 // here][c2], since in *this* code we have the precise span of
545 // the type parameter in question in hand when we report the
548 // [c1]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341089706
549 // [c2]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341096796
550 self.commit_if_ok(|_| {
551 let mut all_obligations = vec![];
552 let inputs: Vec<_> = iter::zip(
554 supplied_sig.inputs().skip_binder(), // binder moved to (*) below
556 .map(|(hir_ty, &supplied_ty)| {
557 // Instantiate (this part of..) S to S', i.e., with fresh variables.
558 self.replace_bound_vars_with_fresh_vars(
560 LateBoundRegionConversionTime::FnCall,
561 // (*) binder moved to here
562 supplied_sig.inputs().rebind(supplied_ty),
567 // The liberated version of this signature should be a subtype
568 // of the liberated form of the expectation.
569 for ((hir_ty, &supplied_ty), expected_ty) in iter::zip(
570 iter::zip(decl.inputs, &inputs),
571 expected_sigs.liberated_sig.inputs(), // `liberated_sig` is E'.
573 // Check that E' = S'.
574 let cause = self.misc(hir_ty.span);
575 let InferOk { value: (), obligations } =
576 self.at(&cause, self.param_env).eq(*expected_ty, supplied_ty)?;
577 all_obligations.extend(obligations);
580 let supplied_output_ty = self.replace_bound_vars_with_fresh_vars(
582 LateBoundRegionConversionTime::FnCall,
583 supplied_sig.output(),
585 let cause = &self.misc(decl.output.span());
586 let InferOk { value: (), obligations } = self
587 .at(cause, self.param_env)
588 .eq(expected_sigs.liberated_sig.output(), supplied_output_ty)?;
589 all_obligations.extend(obligations);
591 let inputs = inputs.into_iter().map(|ty| self.resolve_vars_if_possible(ty));
593 expected_sigs.liberated_sig = self.tcx.mk_fn_sig(
596 expected_sigs.liberated_sig.c_variadic,
597 hir::Unsafety::Normal,
601 Ok(InferOk { value: expected_sigs, obligations: all_obligations })
605 /// If there is no expected signature, then we will convert the
606 /// types that the user gave into a signature.
608 /// Also, record this closure signature for later.
609 #[instrument(skip(self, decl, body), level = "debug", ret)]
610 fn supplied_sig_of_closure(
614 decl: &hir::FnDecl<'_>,
615 body: &hir::Body<'_>,
616 ) -> ty::PolyFnSig<'tcx> {
617 let astconv: &dyn AstConv<'_> = self;
619 trace!("decl = {:#?}", decl);
620 debug!(?body.generator_kind);
622 let bound_vars = self.tcx.late_bound_vars(hir_id);
624 // First, convert the types that the user supplied (if any).
625 let supplied_arguments = decl.inputs.iter().map(|a| astconv.ast_ty_to_ty(a));
626 let supplied_return = match decl.output {
627 hir::FnRetTy::Return(ref output) => astconv.ast_ty_to_ty(&output),
628 hir::FnRetTy::DefaultReturn(_) => match body.generator_kind {
629 // In the case of the async block that we create for a function body,
630 // we expect the return type of the block to match that of the enclosing
632 Some(hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn)) => {
633 debug!("closure is async fn body");
634 self.deduce_future_output_from_obligations(expr_def_id, body.id().hir_id)
636 // AFAIK, deducing the future output
637 // always succeeds *except* in error cases
638 // like #65159. I'd like to return Error
639 // here, but I can't because I can't
640 // easily (and locally) prove that we
641 // *have* reported an
642 // error. --nikomatsakis
643 astconv.ty_infer(None, decl.output.span())
647 _ => astconv.ty_infer(None, decl.output.span()),
651 let result = ty::Binder::bind_with_vars(
656 hir::Unsafety::Normal,
661 // Astconv can't normalize inputs or outputs with escaping bound vars,
662 // so normalize them here, after we've wrapped them in a binder.
663 let result = self.normalize_associated_types_in(self.tcx.hir().span(hir_id), result);
665 let c_result = self.inh.infcx.canonicalize_response(result);
666 self.typeck_results.borrow_mut().user_provided_sigs.insert(expr_def_id, c_result);
671 /// Invoked when we are translating the generator that results
672 /// from desugaring an `async fn`. Returns the "sugared" return
673 /// type of the `async fn` -- that is, the return type that the
674 /// user specified. The "desugared" return type is an `impl
675 /// Future<Output = T>`, so we do this by searching through the
676 /// obligations to extract the `T`.
677 #[instrument(skip(self), level = "debug", ret)]
678 fn deduce_future_output_from_obligations(
682 ) -> Option<Ty<'tcx>> {
683 let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
684 span_bug!(self.tcx.def_span(expr_def_id), "async fn generator outside of a fn")
687 let ret_ty = ret_coercion.borrow().expected_ty();
688 let ret_ty = self.inh.infcx.shallow_resolve(ret_ty);
690 let get_future_output = |predicate: ty::Predicate<'tcx>, span| {
691 // Search for a pending obligation like
693 // `<R as Future>::Output = T`
695 // where R is the return type we are expecting. This type `T`
696 // will be our output.
697 let bound_predicate = predicate.kind();
698 if let ty::PredicateKind::Projection(proj_predicate) = bound_predicate.skip_binder() {
699 self.deduce_future_output_from_projection(
701 bound_predicate.rebind(proj_predicate),
708 let output_ty = match *ret_ty.kind() {
709 ty::Infer(ty::TyVar(ret_vid)) => {
710 self.obligations_for_self_ty(ret_vid).find_map(|obligation| {
711 get_future_output(obligation.predicate, obligation.cause.span)
714 ty::Opaque(def_id, substs) => self
716 .bound_explicit_item_bounds(def_id)
717 .subst_iter_copied(self.tcx, substs)
718 .find_map(|(p, s)| get_future_output(p, s))?,
719 ty::Error(_) => return None,
721 if self.tcx.def_kind(proj.item_def_id) == DefKind::ImplTraitPlaceholder =>
724 .bound_explicit_item_bounds(proj.item_def_id)
725 .subst_iter_copied(self.tcx, proj.substs)
726 .find_map(|(p, s)| get_future_output(p, s))?
729 self.tcx.def_span(expr_def_id),
730 "async fn generator return type not an inference variable: {ret_ty}"
734 // async fn that have opaque types in their return type need to redo the conversion to inference variables
735 // as they fetch the still opaque version from the signature.
736 let InferOk { value: output_ty, obligations } = self
737 .replace_opaque_types_with_inference_vars(
740 self.tcx.def_span(expr_def_id),
743 self.register_predicates(obligations);
748 /// Given a projection like
750 /// `<X as Future>::Output = T`
752 /// where `X` is some type that has no late-bound regions, returns
753 /// `Some(T)`. If the projection is for some other trait, returns
755 fn deduce_future_output_from_projection(
758 predicate: ty::PolyProjectionPredicate<'tcx>,
759 ) -> Option<Ty<'tcx>> {
760 debug!("deduce_future_output_from_projection(predicate={:?})", predicate);
762 // We do not expect any bound regions in our predicate, so
763 // skip past the bound vars.
764 let Some(predicate) = predicate.no_bound_vars() else {
765 debug!("deduce_future_output_from_projection: has late-bound regions");
769 // Check that this is a projection from the `Future` trait.
770 let trait_def_id = predicate.projection_ty.trait_def_id(self.tcx);
771 let future_trait = self.tcx.require_lang_item(LangItem::Future, Some(cause_span));
772 if trait_def_id != future_trait {
773 debug!("deduce_future_output_from_projection: not a future");
777 // The `Future` trait has only one associated item, `Output`,
778 // so check that this is what we see.
779 let output_assoc_item = self.tcx.associated_item_def_ids(future_trait)[0];
780 if output_assoc_item != predicate.projection_ty.item_def_id {
783 "projecting associated item `{:?}` from future, which is not Output `{:?}`",
784 predicate.projection_ty.item_def_id,
789 // Extract the type from the projection. Note that there can
790 // be no bound variables in this type because the "self type"
791 // does not have any regions in it.
792 let output_ty = self.resolve_vars_if_possible(predicate.term);
793 debug!("deduce_future_output_from_projection: output_ty={:?}", output_ty);
794 // This is a projection on a Fn trait so will always be a type.
795 Some(output_ty.ty().unwrap())
798 /// Converts the types that the user supplied, in case that doing
799 /// so should yield an error, but returns back a signature where
800 /// all parameters are of type `TyErr`.
801 fn error_sig_of_closure(&self, decl: &hir::FnDecl<'_>) -> ty::PolyFnSig<'tcx> {
802 let astconv: &dyn AstConv<'_> = self;
804 let supplied_arguments = decl.inputs.iter().map(|a| {
805 // Convert the types that the user supplied (if any), but ignore them.
806 astconv.ast_ty_to_ty(a);
810 if let hir::FnRetTy::Return(ref output) = decl.output {
811 astconv.ast_ty_to_ty(&output);
814 let result = ty::Binder::dummy(self.tcx.mk_fn_sig(
818 hir::Unsafety::Normal,
822 debug!("supplied_sig_of_closure: result={:?}", result);
830 body: &hir::Body<'_>,
831 bound_sig: ty::PolyFnSig<'tcx>,
832 ) -> ClosureSignatures<'tcx> {
833 let liberated_sig = self.tcx().liberate_late_bound_regions(expr_def_id, bound_sig);
834 let liberated_sig = self.inh.normalize_associated_types_in(
840 ClosureSignatures { bound_sig, liberated_sig }