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_macros::{TypeFoldable, TypeVisitable};
14 use rustc_middle::ty::subst::InternalSubsts;
15 use rustc_middle::ty::visit::TypeVisitable;
16 use rustc_middle::ty::{self, Ty};
17 use rustc_span::source_map::Span;
18 use rustc_target::spec::abi::Abi;
19 use rustc_trait_selection::traits;
20 use rustc_trait_selection::traits::error_reporting::ArgKind;
21 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
25 /// What signature do we *expect* the closure to have from context?
26 #[derive(Debug, Clone, TypeFoldable, TypeVisitable)]
27 struct ExpectedSig<'tcx> {
28 /// Span that gave us this expectation, if we know that.
29 cause_span: Option<Span>,
30 sig: ty::PolyFnSig<'tcx>,
33 struct ClosureSignatures<'tcx> {
34 /// The signature users of the closure see.
35 bound_sig: ty::PolyFnSig<'tcx>,
36 /// The signature within the function body.
37 /// This mostly differs in the sense that lifetimes are now early bound and any
38 /// opaque types from the signature expectation are overriden in case there are
39 /// explicit hidden types written by the user in the closure signature.
40 liberated_sig: ty::FnSig<'tcx>,
43 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
44 #[instrument(skip(self, expr, _capture, decl, body_id), level = "debug")]
45 pub fn check_expr_closure(
48 _capture: hir::CaptureBy,
49 decl: &'tcx hir::FnDecl<'tcx>,
51 gen: Option<hir::Movability>,
52 expected: Expectation<'tcx>,
54 trace!("decl = {:#?}", decl);
55 trace!("expr = {:#?}", expr);
57 // It's always helpful for inference if we know the kind of
58 // closure sooner rather than later, so first examine the expected
59 // type, and see if can glean a closure kind from there.
60 let (expected_sig, expected_kind) = match expected.to_option(self) {
61 Some(ty) => self.deduce_expectations_from_expected_type(ty),
64 let body = self.tcx.hir().body(body_id);
65 self.check_closure(expr, expected_kind, decl, body, gen, expected_sig)
68 #[instrument(skip(self, expr, body, decl), level = "debug", ret)]
72 opt_kind: Option<ty::ClosureKind>,
73 decl: &'tcx hir::FnDecl<'tcx>,
74 body: &'tcx hir::Body<'tcx>,
75 gen: Option<hir::Movability>,
76 expected_sig: Option<ExpectedSig<'tcx>>,
78 trace!("decl = {:#?}", decl);
79 let expr_def_id = self.tcx.hir().local_def_id(expr.hir_id);
82 let ClosureSignatures { bound_sig, liberated_sig } =
83 self.sig_of_closure(expr.hir_id, expr_def_id.to_def_id(), decl, body, expected_sig);
85 debug!(?bound_sig, ?liberated_sig);
87 let generator_types = check_fn(
89 self.param_env.without_const(),
98 let parent_substs = InternalSubsts::identity_for_item(
100 self.tcx.typeck_root_def_id(expr_def_id.to_def_id()),
103 let tupled_upvars_ty = self.next_ty_var(TypeVariableOrigin {
104 kind: TypeVariableOriginKind::ClosureSynthetic,
105 span: self.tcx.hir().span(expr.hir_id),
108 if let Some(GeneratorTypes { resume_ty, yield_ty, interior, movability }) = generator_types
110 let generator_substs = ty::GeneratorSubsts::new(
112 ty::GeneratorSubstsParts {
116 return_ty: liberated_sig.output(),
122 return self.tcx.mk_generator(
123 expr_def_id.to_def_id(),
124 generator_substs.substs,
129 // Tuple up the arguments and insert the resulting function type into
130 // the `closures` table.
131 let sig = bound_sig.map_bound(|sig| {
133 iter::once(self.tcx.intern_tup(sig.inputs())),
141 debug!(?sig, ?opt_kind);
143 let closure_kind_ty = match opt_kind {
144 Some(kind) => kind.to_ty(self.tcx),
146 // Create a type variable (for now) to represent the closure kind.
147 // It will be unified during the upvar inference phase (`upvar.rs`)
148 None => self.next_ty_var(TypeVariableOrigin {
149 // FIXME(eddyb) distinguish closure kind inference variables from the rest.
150 kind: TypeVariableOriginKind::ClosureSynthetic,
155 let closure_substs = ty::ClosureSubsts::new(
157 ty::ClosureSubstsParts {
160 closure_sig_as_fn_ptr_ty: self.tcx.mk_fn_ptr(sig),
165 self.tcx.mk_closure(expr_def_id.to_def_id(), closure_substs.substs)
168 /// Given the expected type, figures out what it can about this closure we
169 /// are about to type check:
170 #[instrument(skip(self), level = "debug")]
171 fn deduce_expectations_from_expected_type(
173 expected_ty: Ty<'tcx>,
174 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
175 match *expected_ty.kind() {
176 ty::Opaque(def_id, substs) => {
177 let bounds = self.tcx.bound_explicit_item_bounds(def_id);
179 bounds.subst_iter_copied(self.tcx, substs).find_map(|(pred, span)| match pred
183 ty::PredicateKind::Projection(proj_predicate) => self
184 .deduce_sig_from_projection(
186 pred.kind().rebind(proj_predicate),
194 .filter_map(|(pred, _)| match pred.kind().skip_binder() {
195 ty::PredicateKind::Trait(tp) => {
196 self.tcx.fn_trait_kind_from_lang_item(tp.def_id())
200 .fold(None, |best, cur| Some(best.map_or(cur, |best| cmp::min(best, cur))));
204 ty::Dynamic(ref object_type, ..) => {
205 let sig = object_type.projection_bounds().find_map(|pb| {
206 let pb = pb.with_self_ty(self.tcx, self.tcx.types.trait_object_dummy_self);
207 self.deduce_sig_from_projection(None, pb)
209 let kind = object_type
211 .and_then(|did| self.tcx.fn_trait_kind_from_lang_item(did));
214 ty::Infer(ty::TyVar(vid)) => self.deduce_expectations_from_obligations(vid),
216 let expected_sig = ExpectedSig { cause_span: None, sig };
217 (Some(expected_sig), Some(ty::ClosureKind::Fn))
223 fn deduce_expectations_from_obligations(
225 expected_vid: ty::TyVid,
226 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
227 let mut expected_sig = None;
228 let mut expected_kind = None;
230 for obligation in traits::elaborate_obligations(
232 // Reverse the obligations here, since `elaborate_*` uses a stack,
233 // and we want to keep inference generally in the same order of
234 // the registered obligations.
235 self.obligations_for_self_ty(expected_vid).rev().collect(),
237 debug!(?obligation.predicate);
238 let bound_predicate = obligation.predicate.kind();
240 // Given a Projection predicate, we can potentially infer
241 // the complete signature.
242 if expected_sig.is_none()
243 && let ty::PredicateKind::Projection(proj_predicate) = bound_predicate.skip_binder()
245 expected_sig = self.normalize_associated_types_in(
246 obligation.cause.span,
247 self.deduce_sig_from_projection(
248 Some(obligation.cause.span),
249 bound_predicate.rebind(proj_predicate),
254 // Even if we can't infer the full signature, we may be able to
255 // infer the kind. This can occur when we elaborate a predicate
256 // like `F : Fn<A>`. Note that due to subtyping we could encounter
257 // many viable options, so pick the most restrictive.
258 let trait_def_id = match bound_predicate.skip_binder() {
259 ty::PredicateKind::Projection(data) => {
260 Some(data.projection_ty.trait_def_id(self.tcx))
262 ty::PredicateKind::Trait(data) => Some(data.def_id()),
265 if let Some(closure_kind) =
266 trait_def_id.and_then(|def_id| self.tcx.fn_trait_kind_from_lang_item(def_id))
268 expected_kind = Some(
270 .map_or_else(|| closure_kind, |current| cmp::min(current, closure_kind)),
275 (expected_sig, expected_kind)
278 /// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce
279 /// everything we need to know about a closure or generator.
281 /// The `cause_span` should be the span that caused us to
282 /// have this expected signature, or `None` if we can't readily
284 #[instrument(level = "debug", skip(self, cause_span), ret)]
285 fn deduce_sig_from_projection(
287 cause_span: Option<Span>,
288 projection: ty::PolyProjectionPredicate<'tcx>,
289 ) -> Option<ExpectedSig<'tcx>> {
292 let trait_def_id = projection.trait_def_id(tcx);
294 let is_fn = tcx.fn_trait_kind_from_lang_item(trait_def_id).is_some();
295 let gen_trait = tcx.require_lang_item(LangItem::Generator, cause_span);
296 let is_gen = gen_trait == trait_def_id;
297 if !is_fn && !is_gen {
298 debug!("not fn or generator");
303 // Check that we deduce the signature from the `<_ as std::ops::Generator>::Return`
304 // associated item and not yield.
305 let return_assoc_item = self.tcx.associated_item_def_ids(gen_trait)[1];
306 if return_assoc_item != projection.projection_def_id() {
307 debug!("not return assoc item of generator");
312 let input_tys = if is_fn {
313 let arg_param_ty = projection.skip_binder().projection_ty.substs.type_at(1);
314 let arg_param_ty = self.resolve_vars_if_possible(arg_param_ty);
315 debug!(?arg_param_ty);
317 match arg_param_ty.kind() {
318 &ty::Tuple(tys) => tys,
322 // Generators with a `()` resume type may be defined with 0 or 1 explicit arguments,
323 // else they must have exactly 1 argument. For now though, just give up in this case.
327 // Since this is a return parameter type it is safe to unwrap.
328 let ret_param_ty = projection.skip_binder().term.ty().unwrap();
329 let ret_param_ty = self.resolve_vars_if_possible(ret_param_ty);
330 debug!(?ret_param_ty);
332 let sig = projection.rebind(self.tcx.mk_fn_sig(
336 hir::Unsafety::Normal,
340 Some(ExpectedSig { cause_span, sig })
347 decl: &hir::FnDecl<'_>,
348 body: &hir::Body<'_>,
349 expected_sig: Option<ExpectedSig<'tcx>>,
350 ) -> ClosureSignatures<'tcx> {
351 if let Some(e) = expected_sig {
352 self.sig_of_closure_with_expectation(hir_id, expr_def_id, decl, body, e)
354 self.sig_of_closure_no_expectation(hir_id, expr_def_id, decl, body)
358 /// If there is no expected signature, then we will convert the
359 /// types that the user gave into a signature.
360 #[instrument(skip(self, hir_id, expr_def_id, decl, body), level = "debug")]
361 fn sig_of_closure_no_expectation(
365 decl: &hir::FnDecl<'_>,
366 body: &hir::Body<'_>,
367 ) -> ClosureSignatures<'tcx> {
368 let bound_sig = self.supplied_sig_of_closure(hir_id, expr_def_id, decl, body);
370 self.closure_sigs(expr_def_id, body, bound_sig)
373 /// Invoked to compute the signature of a closure expression. This
374 /// combines any user-provided type annotations (e.g., `|x: u32|
375 /// -> u32 { .. }`) with the expected signature.
377 /// The approach is as follows:
379 /// - Let `S` be the (higher-ranked) signature that we derive from the user's annotations.
380 /// - Let `E` be the (higher-ranked) signature that we derive from the expectations, if any.
381 /// - If we have no expectation `E`, then the signature of the closure is `S`.
382 /// - Otherwise, the signature of the closure is E. Moreover:
383 /// - Skolemize the late-bound regions in `E`, yielding `E'`.
384 /// - Instantiate all the late-bound regions bound in the closure within `S`
385 /// with fresh (existential) variables, yielding `S'`
386 /// - Require that `E' = S'`
387 /// - We could use some kind of subtyping relationship here,
388 /// I imagine, but equality is easier and works fine for
391 /// The key intuition here is that the user's types must be valid
392 /// from "the inside" of the closure, but the expectation
393 /// ultimately drives the overall signature.
397 /// ```ignore (illustrative)
398 /// fn with_closure<F>(_: F)
399 /// where F: Fn(&u32) -> &u32 { .. }
401 /// with_closure(|x: &u32| { ... })
405 /// - E would be `fn(&u32) -> &u32`.
406 /// - S would be `fn(&u32) ->
407 /// - E' is `&'!0 u32 -> &'!0 u32`
408 /// - S' is `&'?0 u32 -> ?T`
410 /// S' can be unified with E' with `['?0 = '!0, ?T = &'!10 u32]`.
414 /// - `expr_def_id`: the `DefId` of the closure expression
415 /// - `decl`: the HIR declaration of the closure
416 /// - `body`: the body of the closure
417 /// - `expected_sig`: the expected signature (if any). Note that
418 /// this is missing a binder: that is, there may be late-bound
419 /// regions with depth 1, which are bound then by the closure.
420 #[instrument(skip(self, hir_id, expr_def_id, decl, body), level = "debug")]
421 fn sig_of_closure_with_expectation(
425 decl: &hir::FnDecl<'_>,
426 body: &hir::Body<'_>,
427 expected_sig: ExpectedSig<'tcx>,
428 ) -> ClosureSignatures<'tcx> {
429 // Watch out for some surprises and just ignore the
430 // expectation if things don't see to match up with what we
432 if expected_sig.sig.c_variadic() != decl.c_variadic {
433 return self.sig_of_closure_no_expectation(hir_id, expr_def_id, decl, body);
434 } else if expected_sig.sig.skip_binder().inputs_and_output.len() != decl.inputs.len() + 1 {
435 return self.sig_of_closure_with_mismatched_number_of_arguments(
443 // Create a `PolyFnSig`. Note the oddity that late bound
444 // regions appearing free in `expected_sig` are now bound up
445 // in this binder we are creating.
446 assert!(!expected_sig.sig.skip_binder().has_vars_bound_above(ty::INNERMOST));
447 let bound_sig = expected_sig.sig.map_bound(|sig| {
449 sig.inputs().iter().cloned(),
452 hir::Unsafety::Normal,
457 // `deduce_expectations_from_expected_type` introduces
458 // late-bound lifetimes defined elsewhere, which we now
459 // anonymize away, so as not to confuse the user.
460 let bound_sig = self.tcx.anonymize_late_bound_regions(bound_sig);
462 let closure_sigs = self.closure_sigs(expr_def_id, body, bound_sig);
464 // Up till this point, we have ignored the annotations that the user
465 // gave. This function will check that they unify successfully.
466 // Along the way, it also writes out entries for types that the user
467 // wrote into our typeck results, which are then later used by the privacy
469 match self.merge_supplied_sig_with_expectation(
476 Ok(infer_ok) => self.register_infer_ok_obligations(infer_ok),
477 Err(_) => self.sig_of_closure_no_expectation(hir_id, expr_def_id, decl, body),
481 fn sig_of_closure_with_mismatched_number_of_arguments(
484 decl: &hir::FnDecl<'_>,
485 body: &hir::Body<'_>,
486 expected_sig: ExpectedSig<'tcx>,
487 ) -> ClosureSignatures<'tcx> {
488 let hir = self.tcx.hir();
489 let expr_map_node = hir.get_if_local(expr_def_id).unwrap();
490 let expected_args: Vec<_> = expected_sig
495 .map(|ty| ArgKind::from_expected_ty(*ty, None))
497 let (closure_span, found_args) = match self.get_fn_like_arguments(expr_map_node) {
498 Some((sp, args)) => (Some(sp), args),
499 None => (None, Vec::new()),
502 expected_sig.cause_span.unwrap_or_else(|| hir.span_if_local(expr_def_id).unwrap());
503 self.report_arg_count_mismatch(
512 let error_sig = self.error_sig_of_closure(decl);
514 self.closure_sigs(expr_def_id, body, error_sig)
517 /// Enforce the user's types against the expectation. See
518 /// `sig_of_closure_with_expectation` for details on the overall
520 #[instrument(level = "debug", skip(self, hir_id, expr_def_id, decl, body, expected_sigs))]
521 fn merge_supplied_sig_with_expectation(
525 decl: &hir::FnDecl<'_>,
526 body: &hir::Body<'_>,
527 mut expected_sigs: ClosureSignatures<'tcx>,
528 ) -> InferResult<'tcx, ClosureSignatures<'tcx>> {
529 // Get the signature S that the user gave.
531 // (See comment on `sig_of_closure_with_expectation` for the
532 // meaning of these letters.)
533 let supplied_sig = self.supplied_sig_of_closure(hir_id, expr_def_id, decl, body);
535 debug!(?supplied_sig);
537 // FIXME(#45727): As discussed in [this comment][c1], naively
538 // forcing equality here actually results in suboptimal error
539 // messages in some cases. For now, if there would have been
540 // an obvious error, we fallback to declaring the type of the
541 // closure to be the one the user gave, which allows other
542 // error message code to trigger.
544 // However, I think [there is potential to do even better
545 // here][c2], since in *this* code we have the precise span of
546 // the type parameter in question in hand when we report the
549 // [c1]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341089706
550 // [c2]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341096796
551 self.commit_if_ok(|_| {
552 let mut all_obligations = vec![];
553 let inputs: Vec<_> = iter::zip(
555 supplied_sig.inputs().skip_binder(), // binder moved to (*) below
557 .map(|(hir_ty, &supplied_ty)| {
558 // Instantiate (this part of..) S to S', i.e., with fresh variables.
559 self.replace_bound_vars_with_fresh_vars(
561 LateBoundRegionConversionTime::FnCall,
562 // (*) binder moved to here
563 supplied_sig.inputs().rebind(supplied_ty),
568 // The liberated version of this signature should be a subtype
569 // of the liberated form of the expectation.
570 for ((hir_ty, &supplied_ty), expected_ty) in iter::zip(
571 iter::zip(decl.inputs, &inputs),
572 expected_sigs.liberated_sig.inputs(), // `liberated_sig` is E'.
574 // Check that E' = S'.
575 let cause = self.misc(hir_ty.span);
576 let InferOk { value: (), obligations } =
577 self.at(&cause, self.param_env).eq(*expected_ty, supplied_ty)?;
578 all_obligations.extend(obligations);
581 let supplied_output_ty = self.replace_bound_vars_with_fresh_vars(
583 LateBoundRegionConversionTime::FnCall,
584 supplied_sig.output(),
586 let cause = &self.misc(decl.output.span());
587 let InferOk { value: (), obligations } = self
588 .at(cause, self.param_env)
589 .eq(expected_sigs.liberated_sig.output(), supplied_output_ty)?;
590 all_obligations.extend(obligations);
592 let inputs = inputs.into_iter().map(|ty| self.resolve_vars_if_possible(ty));
594 expected_sigs.liberated_sig = self.tcx.mk_fn_sig(
597 expected_sigs.liberated_sig.c_variadic,
598 hir::Unsafety::Normal,
602 Ok(InferOk { value: expected_sigs, obligations: all_obligations })
606 /// If there is no expected signature, then we will convert the
607 /// types that the user gave into a signature.
609 /// Also, record this closure signature for later.
610 #[instrument(skip(self, decl, body), level = "debug", ret)]
611 fn supplied_sig_of_closure(
615 decl: &hir::FnDecl<'_>,
616 body: &hir::Body<'_>,
617 ) -> ty::PolyFnSig<'tcx> {
618 let astconv: &dyn AstConv<'_> = self;
620 trace!("decl = {:#?}", decl);
621 debug!(?body.generator_kind);
623 let bound_vars = self.tcx.late_bound_vars(hir_id);
625 // First, convert the types that the user supplied (if any).
626 let supplied_arguments = decl.inputs.iter().map(|a| astconv.ast_ty_to_ty(a));
627 let supplied_return = match decl.output {
628 hir::FnRetTy::Return(ref output) => astconv.ast_ty_to_ty(&output),
629 hir::FnRetTy::DefaultReturn(_) => match body.generator_kind {
630 // In the case of the async block that we create for a function body,
631 // we expect the return type of the block to match that of the enclosing
633 Some(hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn)) => {
634 debug!("closure is async fn body");
635 self.deduce_future_output_from_obligations(expr_def_id, body.id().hir_id)
637 // AFAIK, deducing the future output
638 // always succeeds *except* in error cases
639 // like #65159. I'd like to return Error
640 // here, but I can't because I can't
641 // easily (and locally) prove that we
642 // *have* reported an
643 // error. --nikomatsakis
644 astconv.ty_infer(None, decl.output.span())
648 _ => astconv.ty_infer(None, decl.output.span()),
652 let result = ty::Binder::bind_with_vars(
657 hir::Unsafety::Normal,
662 // Astconv can't normalize inputs or outputs with escaping bound vars,
663 // so normalize them here, after we've wrapped them in a binder.
664 let result = self.normalize_associated_types_in(self.tcx.hir().span(hir_id), result);
666 let c_result = self.inh.infcx.canonicalize_response(result);
667 self.typeck_results.borrow_mut().user_provided_sigs.insert(expr_def_id, c_result);
672 /// Invoked when we are translating the generator that results
673 /// from desugaring an `async fn`. Returns the "sugared" return
674 /// type of the `async fn` -- that is, the return type that the
675 /// user specified. The "desugared" return type is an `impl
676 /// Future<Output = T>`, so we do this by searching through the
677 /// obligations to extract the `T`.
678 #[instrument(skip(self), level = "debug", ret)]
679 fn deduce_future_output_from_obligations(
683 ) -> Option<Ty<'tcx>> {
684 let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
685 span_bug!(self.tcx.def_span(expr_def_id), "async fn generator outside of a fn")
688 let ret_ty = ret_coercion.borrow().expected_ty();
689 let ret_ty = self.inh.infcx.shallow_resolve(ret_ty);
691 let get_future_output = |predicate: ty::Predicate<'tcx>, span| {
692 // Search for a pending obligation like
694 // `<R as Future>::Output = T`
696 // where R is the return type we are expecting. This type `T`
697 // will be our output.
698 let bound_predicate = predicate.kind();
699 if let ty::PredicateKind::Projection(proj_predicate) = bound_predicate.skip_binder() {
700 self.deduce_future_output_from_projection(
702 bound_predicate.rebind(proj_predicate),
709 let output_ty = match *ret_ty.kind() {
710 ty::Infer(ty::TyVar(ret_vid)) => {
711 self.obligations_for_self_ty(ret_vid).find_map(|obligation| {
712 get_future_output(obligation.predicate, obligation.cause.span)
715 ty::Opaque(def_id, substs) => self
717 .bound_explicit_item_bounds(def_id)
718 .subst_iter_copied(self.tcx, substs)
719 .find_map(|(p, s)| get_future_output(p, s))?,
720 ty::Error(_) => return None,
722 if self.tcx.def_kind(proj.item_def_id) == DefKind::ImplTraitPlaceholder =>
725 .bound_explicit_item_bounds(proj.item_def_id)
726 .subst_iter_copied(self.tcx, proj.substs)
727 .find_map(|(p, s)| get_future_output(p, s))?
730 self.tcx.def_span(expr_def_id),
731 "async fn generator return type not an inference variable: {ret_ty}"
735 // async fn that have opaque types in their return type need to redo the conversion to inference variables
736 // as they fetch the still opaque version from the signature.
737 let InferOk { value: output_ty, obligations } = self
738 .replace_opaque_types_with_inference_vars(
741 self.tcx.def_span(expr_def_id),
744 self.register_predicates(obligations);
749 /// Given a projection like
751 /// `<X as Future>::Output = T`
753 /// where `X` is some type that has no late-bound regions, returns
754 /// `Some(T)`. If the projection is for some other trait, returns
756 fn deduce_future_output_from_projection(
759 predicate: ty::PolyProjectionPredicate<'tcx>,
760 ) -> Option<Ty<'tcx>> {
761 debug!("deduce_future_output_from_projection(predicate={:?})", predicate);
763 // We do not expect any bound regions in our predicate, so
764 // skip past the bound vars.
765 let Some(predicate) = predicate.no_bound_vars() else {
766 debug!("deduce_future_output_from_projection: has late-bound regions");
770 // Check that this is a projection from the `Future` trait.
771 let trait_def_id = predicate.projection_ty.trait_def_id(self.tcx);
772 let future_trait = self.tcx.require_lang_item(LangItem::Future, Some(cause_span));
773 if trait_def_id != future_trait {
774 debug!("deduce_future_output_from_projection: not a future");
778 // The `Future` trait has only one associated item, `Output`,
779 // so check that this is what we see.
780 let output_assoc_item = self.tcx.associated_item_def_ids(future_trait)[0];
781 if output_assoc_item != predicate.projection_ty.item_def_id {
784 "projecting associated item `{:?}` from future, which is not Output `{:?}`",
785 predicate.projection_ty.item_def_id,
790 // Extract the type from the projection. Note that there can
791 // be no bound variables in this type because the "self type"
792 // does not have any regions in it.
793 let output_ty = self.resolve_vars_if_possible(predicate.term);
794 debug!("deduce_future_output_from_projection: output_ty={:?}", output_ty);
795 // This is a projection on a Fn trait so will always be a type.
796 Some(output_ty.ty().unwrap())
799 /// Converts the types that the user supplied, in case that doing
800 /// so should yield an error, but returns back a signature where
801 /// all parameters are of type `TyErr`.
802 fn error_sig_of_closure(&self, decl: &hir::FnDecl<'_>) -> ty::PolyFnSig<'tcx> {
803 let astconv: &dyn AstConv<'_> = self;
805 let supplied_arguments = decl.inputs.iter().map(|a| {
806 // Convert the types that the user supplied (if any), but ignore them.
807 astconv.ast_ty_to_ty(a);
811 if let hir::FnRetTy::Return(ref output) = decl.output {
812 astconv.ast_ty_to_ty(&output);
815 let result = ty::Binder::dummy(self.tcx.mk_fn_sig(
819 hir::Unsafety::Normal,
823 debug!("supplied_sig_of_closure: result={:?}", result);
831 body: &hir::Body<'_>,
832 bound_sig: ty::PolyFnSig<'tcx>,
833 ) -> ClosureSignatures<'tcx> {
834 let liberated_sig = self.tcx().liberate_late_bound_regions(expr_def_id, bound_sig);
835 let liberated_sig = self.inh.normalize_associated_types_in(
841 ClosureSignatures { bound_sig, liberated_sig }