1//! Code for type-checking closure expressions.
23use std::iter;
4use std::ops::ControlFlow;
56use rustc_abi::ExternAbi;
7use rustc_errors::ErrorGuaranteed;
8use rustc_hiras hir;
9use rustc_hir::attrs::lang_items::LangItem;
10use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;
11use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferOk, InferResult};
12use rustc_infer::traits::{ObligationCauseCode, PredicateObligations};
13use rustc_macros::{TypeFoldable, TypeVisitable};
14use rustc_middle::span_bug;
15use rustc_middle::ty::{
16self, ClosureKind, FnSigKind, GenericArgs, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable,
17TypeVisitableExt, TypeVisitor, Unnormalized,
18};
19use rustc_span::def_id::LocalDefId;
20use rustc_span::{DUMMY_SP, Span};
21use rustc_trait_selection::error_reporting::traits::ArgKind;
22use rustc_trait_selection::traits;
23use tracing::{debug, instrument, trace};
2425use super::{CoroutineTypes, Expectation, FnCtxt, check_fn};
26use crate::fn_ctxt::UseSubtyping;
2728/// What signature do we *expect* the closure to have from context?
29#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ExpectedSig<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "ExpectedSig",
"cause_span", &self.cause_span, "sig", &&self.sig)
}
}Debug, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for ExpectedSig<'tcx> {
#[inline]
fn clone(&self) -> ExpectedSig<'tcx> {
ExpectedSig {
cause_span: ::core::clone::Clone::clone(&self.cause_span),
sig: ::core::clone::Clone::clone(&self.sig),
}
}
}Clone, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
for ExpectedSig<'tcx> {
fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Result<Self, __F::Error> {
Ok(match self {
ExpectedSig { cause_span: __binding_0, sig: __binding_1 } =>
{
ExpectedSig {
cause_span: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?,
sig: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
__folder)?,
}
}
})
}
fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Self {
match self {
ExpectedSig { cause_span: __binding_0, sig: __binding_1 } =>
{
ExpectedSig {
cause_span: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder),
sig: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
__folder),
}
}
}
}
}
};TypeFoldable, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
for ExpectedSig<'tcx> {
fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
__visitor: &mut __V) -> __V::Result {
match *self {
ExpectedSig {
cause_span: ref __binding_0, sig: ref __binding_1 } => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
}
<__V::Result as ::rustc_middle::ty::VisitorResult>::output()
}
}
};TypeVisitable)]
30struct ExpectedSig<'tcx> {
31/// Span that gave us this expectation, if we know that.
32cause_span: Option<Span>,
33 sig: ty::PolyFnSig<'tcx>,
34}
3536#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ClosureSignatures<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"ClosureSignatures", "bound_sig", &self.bound_sig,
"liberated_sig", &&self.liberated_sig)
}
}Debug)]
37struct ClosureSignatures<'tcx> {
38/// The signature users of the closure see.
39bound_sig: ty::PolyFnSig<'tcx>,
40/// The signature within the function body.
41 /// This mostly differs in the sense that lifetimes are now early bound and any
42 /// opaque types from the signature expectation are overridden in case there are
43 /// explicit hidden types written by the user in the closure signature.
44liberated_sig: ty::FnSig<'tcx>,
45}
4647impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
48#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_expr_closure",
"rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/closure.rs"),
::tracing_core::__macro_support::Option::Some(48u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("expr_span")
}> =
::tracing::__macro_support::FieldName::new("expr_span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("expected")
}> =
::tracing::__macro_support::FieldName::new("expected");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr_span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Ty<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = self.tcx;
let body = tcx.hir_body(closure.body);
let expr_def_id = closure.def_id;
let (expected_sig, expected_kind) =
match expected.to_option(self) {
Some(ty) => {
self.deduce_closure_signature(self.resolve_vars_with_obligations(ty),
closure.kind)
}
None => (None, None),
};
let ClosureSignatures { bound_sig, mut liberated_sig } =
self.sig_of_closure(expr_def_id, closure.fn_decl,
closure.kind, expected_sig);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/closure.rs:72",
"rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/closure.rs"),
::tracing_core::__macro_support::Option::Some(72u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("bound_sig")
}> =
::tracing::__macro_support::FieldName::new("bound_sig");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("liberated_sig")
}> =
::tracing::__macro_support::FieldName::new("liberated_sig");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bound_sig)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&liberated_sig)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let parent_args =
GenericArgs::identity_for_item(tcx,
tcx.typeck_root_def_id_local(expr_def_id));
let tupled_upvars_ty = self.next_ty_var(expr_span);
let (closure_ty, coroutine_types) =
match closure.kind {
hir::ClosureKind::Closure => {
let sig =
bound_sig.map_bound(|sig|
{
tcx.mk_fn_sig([Ty::new_tup(tcx, sig.inputs())],
sig.output(), sig.fn_sig_kind)
});
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/closure.rs:91",
"rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/closure.rs"),
::tracing_core::__macro_support::Option::Some(91u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("sig")
}> =
::tracing::__macro_support::FieldName::new("sig");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("expected_kind")
}> =
::tracing::__macro_support::FieldName::new("expected_kind");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sig)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected_kind)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let closure_kind_ty =
match expected_kind {
Some(kind) => Ty::from_closure_kind(tcx, kind),
None => self.next_ty_var(expr_span),
};
let closure_args =
ty::ClosureArgs::new(tcx,
ty::ClosureArgsParts {
parent_args,
closure_kind_ty,
closure_sig_as_fn_ptr_ty: Ty::new_fn_ptr(tcx, sig),
tupled_upvars_ty,
});
(Ty::new_closure(tcx, expr_def_id.to_def_id(),
closure_args.args), None)
}
hir::ClosureKind::Coroutine(kind) => {
let yield_ty =
match kind {
hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen,
_) | hir::CoroutineKind::Coroutine(_) => {
let yield_ty = self.next_ty_var(expr_span);
self.require_type_is_sized(yield_ty, expr_span,
ObligationCauseCode::SizedYieldType);
yield_ty
}
hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen,
_) => {
let yield_ty = self.next_ty_var(expr_span);
self.require_type_is_sized(yield_ty, expr_span,
ObligationCauseCode::SizedYieldType);
Ty::new_adt(tcx,
tcx.adt_def(tcx.require_lang_item(LangItem::Poll,
expr_span)),
tcx.mk_args(&[Ty::new_adt(tcx,
tcx.adt_def(tcx.require_lang_item(LangItem::Option,
expr_span)), tcx.mk_args(&[yield_ty.into()])).into()]))
}
hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async,
_) => {
tcx.types.unit
}
};
let resume_ty =
liberated_sig.inputs().get(0).copied().unwrap_or(tcx.types.unit);
let kind_ty =
match kind {
hir::CoroutineKind::Desugared(_,
hir::CoroutineSource::Closure) => {
self.next_ty_var(expr_span)
}
_ => tcx.types.unit,
};
let coroutine_args =
ty::CoroutineArgs::new(tcx,
ty::CoroutineArgsParts {
parent_args,
kind_ty,
resume_ty,
yield_ty,
return_ty: liberated_sig.output(),
tupled_upvars_ty,
});
(Ty::new_coroutine(tcx, expr_def_id.to_def_id(),
coroutine_args.args),
Some(CoroutineTypes { resume_ty, yield_ty }))
}
hir::ClosureKind::CoroutineClosure(kind) => {
let (bound_return_ty, bound_yield_ty) =
match kind {
hir::CoroutineDesugaring::Gen => {
(tcx.types.unit, self.infcx.next_ty_var(expr_span))
}
hir::CoroutineDesugaring::Async => {
(bound_sig.skip_binder().output(), tcx.types.unit)
}
hir::CoroutineDesugaring::AsyncGen => {
{
::core::panicking::panic_fmt(format_args!("not implemented: {0}",
format_args!("`async gen` closures not supported yet")));
}
}
};
let resume_ty = self.next_ty_var(expr_span);
let closure_kind_ty =
match expected_kind {
Some(kind) => Ty::from_closure_kind(tcx, kind),
None => self.next_ty_var(expr_span),
};
let coroutine_captures_by_ref_ty =
self.next_ty_var(expr_span);
let closure_args =
ty::CoroutineClosureArgs::new(tcx,
ty::CoroutineClosureArgsParts {
parent_args,
closure_kind_ty,
signature_parts_ty: Ty::new_fn_ptr(tcx,
bound_sig.map_bound(|sig|
{
tcx.mk_fn_sig([resume_ty,
Ty::new_tup_from_iter(tcx, sig.inputs().iter().copied())],
Ty::new_tup(tcx, &[bound_yield_ty, bound_return_ty]),
sig.fn_sig_kind)
})),
tupled_upvars_ty,
coroutine_captures_by_ref_ty,
});
let coroutine_kind_ty =
match expected_kind {
Some(kind) => Ty::from_coroutine_closure_kind(tcx, kind),
None => self.next_ty_var(expr_span),
};
let coroutine_upvars_ty = self.next_ty_var(expr_span);
let coroutine_output_ty =
tcx.liberate_late_bound_regions(expr_def_id.to_def_id(),
closure_args.coroutine_closure_sig().map_bound(|sig|
{
sig.to_coroutine(tcx, parent_args, coroutine_kind_ty,
tcx.coroutine_for_closure(expr_def_id), coroutine_upvars_ty)
}));
liberated_sig =
tcx.mk_fn_sig(liberated_sig.inputs().iter().copied(),
coroutine_output_ty, liberated_sig.fn_sig_kind);
(Ty::new_coroutine_closure(tcx, expr_def_id.to_def_id(),
closure_args.args), None)
}
};
check_fn(&mut FnCtxt::new(self, self.param_env, closure.def_id),
liberated_sig, coroutine_types, closure.fn_decl, expr_def_id,
body, false);
closure_ty
}
}
}#[instrument(skip(self, closure), level = "debug")]49pub(crate) fn check_expr_closure(
50&self,
51 closure: &hir::Closure<'tcx>,
52 expr_span: Span,
53 expected: Expectation<'tcx>,
54 ) -> Ty<'tcx> {
55let tcx = self.tcx;
56let body = tcx.hir_body(closure.body);
57let expr_def_id = closure.def_id;
5859// It's always helpful for inference if we know the kind of
60 // closure sooner rather than later, so first examine the expected
61 // type, and see if can glean a closure kind from there.
62let (expected_sig, expected_kind) = match expected.to_option(self) {
63Some(ty) => {
64self.deduce_closure_signature(self.resolve_vars_with_obligations(ty), closure.kind)
65 }
66None => (None, None),
67 };
6869let ClosureSignatures { bound_sig, mut liberated_sig } =
70self.sig_of_closure(expr_def_id, closure.fn_decl, closure.kind, expected_sig);
7172debug!(?bound_sig, ?liberated_sig);
7374let parent_args =
75 GenericArgs::identity_for_item(tcx, tcx.typeck_root_def_id_local(expr_def_id));
7677let tupled_upvars_ty = self.next_ty_var(expr_span);
7879// FIXME: We could probably actually just unify this further --
80 // instead of having a `FnSig` and a `Option<CoroutineTypes>`,
81 // we can have a `ClosureSignature { Coroutine { .. }, Closure { .. } }`,
82 // similar to how `ty::GenSig` is a distinct data structure.
83let (closure_ty, coroutine_types) = match closure.kind {
84 hir::ClosureKind::Closure => {
85// Tuple up the arguments and insert the resulting function type into
86 // the `closures` table.
87let sig = bound_sig.map_bound(|sig| {
88 tcx.mk_fn_sig([Ty::new_tup(tcx, sig.inputs())], sig.output(), sig.fn_sig_kind)
89 });
9091debug!(?sig, ?expected_kind);
9293let closure_kind_ty = match expected_kind {
94Some(kind) => Ty::from_closure_kind(tcx, kind),
9596// Create a type variable (for now) to represent the closure kind.
97 // It will be unified during the upvar inference phase (`upvar.rs`)
98None => self.next_ty_var(expr_span),
99 };
100101let closure_args = ty::ClosureArgs::new(
102 tcx,
103 ty::ClosureArgsParts {
104 parent_args,
105 closure_kind_ty,
106 closure_sig_as_fn_ptr_ty: Ty::new_fn_ptr(tcx, sig),
107 tupled_upvars_ty,
108 },
109 );
110111 (Ty::new_closure(tcx, expr_def_id.to_def_id(), closure_args.args), None)
112 }
113 hir::ClosureKind::Coroutine(kind) => {
114let yield_ty = match kind {
115 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)
116 | hir::CoroutineKind::Coroutine(_) => {
117let yield_ty = self.next_ty_var(expr_span);
118self.require_type_is_sized(
119 yield_ty,
120 expr_span,
121 ObligationCauseCode::SizedYieldType,
122 );
123 yield_ty
124 }
125// HACK(-Ztrait-solver=next): In the *old* trait solver, we must eagerly
126 // guide inference on the yield type so that we can handle `AsyncIterator`
127 // in this block in projection correctly. In the new trait solver, it is
128 // not a problem.
129hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _) => {
130let yield_ty = self.next_ty_var(expr_span);
131self.require_type_is_sized(
132 yield_ty,
133 expr_span,
134 ObligationCauseCode::SizedYieldType,
135 );
136137 Ty::new_adt(
138 tcx,
139 tcx.adt_def(tcx.require_lang_item(LangItem::Poll, expr_span)),
140 tcx.mk_args(&[Ty::new_adt(
141 tcx,
142 tcx.adt_def(tcx.require_lang_item(LangItem::Option, expr_span)),
143 tcx.mk_args(&[yield_ty.into()]),
144 )
145 .into()]),
146 )
147 }
148 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _) => {
149 tcx.types.unit
150 }
151 };
152153// Resume type defaults to `()` if the coroutine has no argument.
154let resume_ty = liberated_sig.inputs().get(0).copied().unwrap_or(tcx.types.unit);
155156// Coroutines that come from coroutine closures have not yet determined
157 // their kind ty, so make a fresh infer var which will be constrained
158 // later during upvar analysis. Regular coroutines always have the kind
159 // ty of `().`
160let kind_ty = match kind {
161 hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Closure) => {
162self.next_ty_var(expr_span)
163 }
164_ => tcx.types.unit,
165 };
166167let coroutine_args = ty::CoroutineArgs::new(
168 tcx,
169 ty::CoroutineArgsParts {
170 parent_args,
171 kind_ty,
172 resume_ty,
173 yield_ty,
174 return_ty: liberated_sig.output(),
175 tupled_upvars_ty,
176 },
177 );
178179 (
180 Ty::new_coroutine(tcx, expr_def_id.to_def_id(), coroutine_args.args),
181Some(CoroutineTypes { resume_ty, yield_ty }),
182 )
183 }
184 hir::ClosureKind::CoroutineClosure(kind) => {
185let (bound_return_ty, bound_yield_ty) = match kind {
186 hir::CoroutineDesugaring::Gen => {
187// `iter!` closures always return unit and yield the `Iterator::Item` type
188 // that we have to infer.
189(tcx.types.unit, self.infcx.next_ty_var(expr_span))
190 }
191 hir::CoroutineDesugaring::Async => {
192// async closures always return the type ascribed after the `->` (if present),
193 // and yield `()`.
194(bound_sig.skip_binder().output(), tcx.types.unit)
195 }
196 hir::CoroutineDesugaring::AsyncGen => {
197unimplemented!("`async gen` closures not supported yet")
198 }
199 };
200// Compute all of the variables that will be used to populate the coroutine.
201let resume_ty = self.next_ty_var(expr_span);
202203let closure_kind_ty = match expected_kind {
204Some(kind) => Ty::from_closure_kind(tcx, kind),
205206// Create a type variable (for now) to represent the closure kind.
207 // It will be unified during the upvar inference phase (`upvar.rs`)
208None => self.next_ty_var(expr_span),
209 };
210211let coroutine_captures_by_ref_ty = self.next_ty_var(expr_span);
212let closure_args = ty::CoroutineClosureArgs::new(
213 tcx,
214 ty::CoroutineClosureArgsParts {
215 parent_args,
216 closure_kind_ty,
217 signature_parts_ty: Ty::new_fn_ptr(
218 tcx,
219 bound_sig.map_bound(|sig| {
220 tcx.mk_fn_sig(
221 [
222 resume_ty,
223 Ty::new_tup_from_iter(tcx, sig.inputs().iter().copied()),
224 ],
225 Ty::new_tup(tcx, &[bound_yield_ty, bound_return_ty]),
226 sig.fn_sig_kind,
227 )
228 }),
229 ),
230 tupled_upvars_ty,
231 coroutine_captures_by_ref_ty,
232 },
233 );
234235let coroutine_kind_ty = match expected_kind {
236Some(kind) => Ty::from_coroutine_closure_kind(tcx, kind),
237238// Create a type variable (for now) to represent the closure kind.
239 // It will be unified during the upvar inference phase (`upvar.rs`)
240None => self.next_ty_var(expr_span),
241 };
242243let coroutine_upvars_ty = self.next_ty_var(expr_span);
244245// We need to turn the liberated signature that we got from HIR, which
246 // looks something like `|Args...| -> T`, into a signature that is suitable
247 // for type checking the inner body of the closure, which always returns a
248 // coroutine. To do so, we use the `CoroutineClosureSignature` to compute
249 // the coroutine type, filling in the tupled_upvars_ty and kind_ty with infer
250 // vars which will get constrained during upvar analysis.
251let coroutine_output_ty = tcx.liberate_late_bound_regions(
252 expr_def_id.to_def_id(),
253 closure_args.coroutine_closure_sig().map_bound(|sig| {
254 sig.to_coroutine(
255 tcx,
256 parent_args,
257 coroutine_kind_ty,
258 tcx.coroutine_for_closure(expr_def_id),
259 coroutine_upvars_ty,
260 )
261 }),
262 );
263 liberated_sig = tcx.mk_fn_sig(
264 liberated_sig.inputs().iter().copied(),
265 coroutine_output_ty,
266 liberated_sig.fn_sig_kind,
267 );
268269 (Ty::new_coroutine_closure(tcx, expr_def_id.to_def_id(), closure_args.args), None)
270 }
271 };
272273 check_fn(
274&mut FnCtxt::new(self, self.param_env, closure.def_id),
275 liberated_sig,
276 coroutine_types,
277 closure.fn_decl,
278 expr_def_id,
279 body,
280// Closure "rust-call" ABI doesn't support unsized params
281false,
282 );
283284 closure_ty
285 }
286287/// Given the expected type, figures out what it can about this closure we
288 /// are about to type check:
289x;#[instrument(skip(self), level = "debug", ret)]290fn deduce_closure_signature(
291&self,
292 expected_ty: Ty<'tcx>,
293 closure_kind: hir::ClosureKind,
294 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
295match *expected_ty.kind() {
296 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => self
297.deduce_closure_signature_from_predicates(
298 expected_ty,
299 closure_kind,
300self.tcx
301 .explicit_item_self_bounds(def_id)
302 .iter_instantiated_copied(self.tcx, args)
303 .map(Unnormalized::skip_norm_wip),
304 ),
305 ty::Dynamic(object_type, ..) => {
306let sig = object_type.projection_bounds().find_map(|pb| {
307let pb = pb.with_self_ty(self.tcx, self.tcx.types.trait_object_dummy_self);
308self.deduce_sig_from_projection(None, closure_kind, pb)
309 });
310let kind = object_type
311 .principal_def_id()
312 .and_then(|did| self.tcx.fn_trait_kind_from_def_id(did));
313 (sig, kind)
314 }
315 ty::Infer(ty::TyVar(vid)) => self.deduce_closure_signature_from_predicates(
316 Ty::new_var(self.tcx, self.root_var(vid)),
317 closure_kind,
318self.obligations_for_self_ty(vid, UseSubtyping::No)
319 .into_iter()
320 .filter_map(|obl| Some((obl.predicate.as_clause()?, obl.cause.span))),
321 ),
322 ty::FnPtr(sig_tys, hdr) => match closure_kind {
323 hir::ClosureKind::Closure => {
324let expected_sig = ExpectedSig { cause_span: None, sig: sig_tys.with(hdr) };
325 (Some(expected_sig), Some(ty::ClosureKind::Fn))
326 }
327 hir::ClosureKind::Coroutine(_) | hir::ClosureKind::CoroutineClosure(_) => {
328 (None, None)
329 }
330 },
331_ => (None, None),
332 }
333 }
334335fn deduce_closure_signature_from_predicates(
336&self,
337 expected_ty: Ty<'tcx>,
338 closure_kind: hir::ClosureKind,
339 clauses: impl DoubleEndedIterator<Item = (ty::Clause<'tcx>, Span)>,
340 ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
341let mut expected_sig = None;
342let mut expected_kind = None;
343344for (clause, span) in traits::elaborate(
345self.tcx,
346// Reverse the obligations here, since `elaborate_*` uses a stack,
347 // and we want to keep inference generally in the same order of
348 // the registered obligations.
349clauses.rev(),
350 )
351// We only care about self bounds
352.filter_only_self()
353 {
354{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/closure.rs:354",
"rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/closure.rs"),
::tracing_core::__macro_support::Option::Some(354u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("clause")
}> =
::tracing::__macro_support::FieldName::new("clause");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&clause)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?clause);
355let bound_clause = clause.kind();
356357// Given a Projection clause, we can potentially infer the complete signature.
358if expected_sig.is_none()
359 && let ty::ClauseKind::Projection(proj_clause) = bound_clause.skip_binder()
360 {
361let inferred_sig = self.normalize(
362 span,
363 Unnormalized::new_wip(self.deduce_sig_from_projection(
364Some(span),
365 closure_kind,
366 bound_clause.rebind(proj_clause),
367 )),
368 );
369370// Make sure that we didn't infer a signature that mentions itself.
371 // This can happen when we elaborate certain supertrait bounds that
372 // mention projections containing the `Self` type. See #105401.
373struct MentionsTy<'tcx> {
374 expected_ty: Ty<'tcx>,
375 }
376impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for MentionsTy<'tcx> {
377type Result = ControlFlow<()>;
378379fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
380if t == self.expected_ty {
381 ControlFlow::Break(())
382 } else {
383 t.super_visit_with(self)
384 }
385 }
386 }
387388// Don't infer a closure signature from a goal that names the closure type as this will
389 // (almost always) lead to occurs check errors later in type checking.
390if self.next_trait_solver()
391 && let Some(inferred_sig) = inferred_sig
392 {
393// In the new solver it is difficult to explicitly normalize the inferred signature as we
394 // would have to manually handle universes and rewriting bound vars and placeholders back
395 // and forth.
396 //
397 // Instead we take advantage of the fact that we relating an inference variable with an alias
398 // will only instantiate the variable if the alias is rigid(*not quite). Concretely we:
399 // - Create some new variable `?sig`
400 // - Equate `?sig` with the unnormalized signature, e.g. `fn(<Foo<?x> as Trait>::Assoc)`
401 // - Depending on whether `<Foo<?x> as Trait>::Assoc` is rigid, ambiguous or normalizeable,
402 // we will either wind up with `?sig=<Foo<?x> as Trait>::Assoc/?y/ConcreteTy` respectively.
403 //
404 // *: In cases where there are ambiguous aliases in the signature that make use of bound vars
405 // they will wind up present in `?sig` even though they are non-rigid.
406 //
407 // This is a bit weird and means we may wind up discarding the goal due to it naming `expected_ty`
408 // even though the normalized form may not name `expected_ty`. However, this matches the existing
409 // behaviour of the old solver and would be technically a breaking change to fix.
410let generalized_fnptr_sig = self.next_ty_var(span);
411let inferred_fnptr_sig = Ty::new_fn_ptr(self.tcx, inferred_sig.sig);
412self.demand_eqtype(span, inferred_fnptr_sig, generalized_fnptr_sig);
413414let resolved_sig = self.resolve_vars_if_possible(generalized_fnptr_sig);
415416if resolved_sig.visit_with(&mut MentionsTy { expected_ty }).is_continue() {
417 expected_sig = Some(ExpectedSig {
418 cause_span: inferred_sig.cause_span,
419 sig: resolved_sig.fn_sig(self.tcx),
420 });
421 }
422 } else {
423if inferred_sig.visit_with(&mut MentionsTy { expected_ty }).is_continue() {
424 expected_sig = inferred_sig;
425 }
426 }
427 }
428429// Even if we can't infer the full signature, we may be able to
430 // infer the kind. This can occur when we elaborate a predicate
431 // like `F : Fn<A>`. Note that due to subtyping we could encounter
432 // many viable options, so pick the most restrictive.
433let trait_def_id = match bound_clause.skip_binder() {
434 ty::ClauseKind::Projection(data) => {
435Some(data.projection_term.trait_def_id(self.tcx))
436 }
437 ty::ClauseKind::Trait(data) => Some(data.def_id()),
438_ => None,
439 };
440441if let Some(trait_def_id) = trait_def_id {
442let found_kind = match closure_kind {
443 hir::ClosureKind::Closure
444// FIXME(iter_macro): Someday we'll probably want iterator closures instead of
445 // just using Fn* for iterators.
446| hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Gen) => {
447self.tcx.fn_trait_kind_from_def_id(trait_def_id)
448 }
449 hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) => self
450.tcx
451 .async_fn_trait_kind_from_def_id(trait_def_id)
452 .or_else(|| self.tcx.fn_trait_kind_from_def_id(trait_def_id)),
453_ => None,
454 };
455456if let Some(found_kind) = found_kind {
457// always use the closure kind that is more permissive.
458match (expected_kind, found_kind) {
459 (None, _) => expected_kind = Some(found_kind),
460 (Some(ClosureKind::FnMut), ClosureKind::Fn) => {
461 expected_kind = Some(ClosureKind::Fn)
462 }
463 (Some(ClosureKind::FnOnce), ClosureKind::Fn | ClosureKind::FnMut) => {
464 expected_kind = Some(found_kind)
465 }
466_ => {}
467 }
468 }
469 }
470 }
471472 (expected_sig, expected_kind)
473 }
474475/// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce
476 /// everything we need to know about a closure or coroutine.
477 ///
478 /// The `cause_span` should be the span that caused us to
479 /// have this expected signature, or `None` if we can't readily
480 /// know that.
481x;#[instrument(level = "debug", skip(self, cause_span), ret)]482fn deduce_sig_from_projection(
483&self,
484 cause_span: Option<Span>,
485 closure_kind: hir::ClosureKind,
486 projection: ty::PolyProjectionPredicate<'tcx>,
487 ) -> Option<ExpectedSig<'tcx>> {
488let def_id = projection.item_def_id();
489490// For now, we only do signature deduction based off of the `Fn` and `AsyncFn` traits,
491 // for closures and async closures, respectively.
492match closure_kind {
493 hir::ClosureKind::Closure if self.tcx.is_lang_item(def_id, LangItem::FnOnceOutput) => {
494self.extract_sig_from_projection(cause_span, projection)
495 }
496 hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async)
497if self.tcx.is_lang_item(def_id, LangItem::AsyncFnOnceOutput) =>
498 {
499self.extract_sig_from_projection(cause_span, projection)
500 }
501// It's possible we've passed the closure to a (somewhat out-of-fashion)
502 // `F: FnOnce() -> Fut, Fut: Future<Output = T>` style bound. Let's still
503 // guide inference here, since it's beneficial for the user.
504hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async)
505if self.tcx.is_lang_item(def_id, LangItem::FnOnceOutput) =>
506 {
507self.extract_sig_from_projection_and_future_bound(cause_span, projection)
508 }
509_ => None,
510 }
511 }
512513/// Given an `FnOnce::Output` or `AsyncFn::Output` projection, extract the args
514 /// and return type to infer a [`ty::PolyFnSig`] for the closure.
515fn extract_sig_from_projection(
516&self,
517 cause_span: Option<Span>,
518 projection: ty::PolyProjectionPredicate<'tcx>,
519 ) -> Option<ExpectedSig<'tcx>> {
520let projection = self.resolve_vars_if_possible(projection);
521522let arg_param_ty = projection.skip_binder().projection_term.args.type_at(1);
523{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/closure.rs:523",
"rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/closure.rs"),
::tracing_core::__macro_support::Option::Some(523u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("arg_param_ty")
}> =
::tracing::__macro_support::FieldName::new("arg_param_ty");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&arg_param_ty)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?arg_param_ty);
524525let ty::Tuple(input_tys) = *arg_param_ty.kind() else {
526return None;
527 };
528529// Since this is a return parameter type it is safe to unwrap.
530let ret_param_ty = projection.skip_binder().term.expect_type();
531{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/closure.rs:531",
"rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/closure.rs"),
::tracing_core::__macro_support::Option::Some(531u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ret_param_ty")
}> =
::tracing::__macro_support::FieldName::new("ret_param_ty");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ret_param_ty)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?ret_param_ty);
532533let sig = projection.rebind(self.tcx.mk_fn_sig_safe_rust_abi(input_tys, ret_param_ty));
534535Some(ExpectedSig { cause_span, sig })
536 }
537538/// When an async closure is passed to a function that has a "two-part" `Fn`
539 /// and `Future` trait bound, like:
540 ///
541 /// ```rust
542 /// use std::future::Future;
543 ///
544 /// fn not_exactly_an_async_closure<F, Fut>(_f: F)
545 /// where
546 /// F: FnOnce(String, u32) -> Fut,
547 /// Fut: Future<Output = i32>,
548 /// {}
549 /// ```
550 ///
551 /// The we want to be able to extract the signature to guide inference in the async
552 /// closure. We will have two projection predicates registered in this case. First,
553 /// we identify the `FnOnce<Args, Output = ?Fut>` bound, and if the output type is
554 /// an inference variable `?Fut`, we check if that is bounded by a `Future<Output = Ty>`
555 /// projection.
556 ///
557 /// This function is actually best-effort with the return type; if we don't find a
558 /// `Future` projection, we still will return arguments that we extracted from the `FnOnce`
559 /// projection, and the output will be an unconstrained type variable instead.
560fn extract_sig_from_projection_and_future_bound(
561&self,
562 cause_span: Option<Span>,
563 projection: ty::PolyProjectionPredicate<'tcx>,
564 ) -> Option<ExpectedSig<'tcx>> {
565let projection = self.resolve_vars_if_possible(projection);
566567let arg_param_ty = projection.skip_binder().projection_term.args.type_at(1);
568{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/closure.rs:568",
"rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/closure.rs"),
::tracing_core::__macro_support::Option::Some(568u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("arg_param_ty")
}> =
::tracing::__macro_support::FieldName::new("arg_param_ty");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&arg_param_ty)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?arg_param_ty);
569570let ty::Tuple(input_tys) = *arg_param_ty.kind() else {
571return None;
572 };
573574// If the return type is a type variable, look for bounds on it.
575 // We could theoretically support other kinds of return types here,
576 // but none of them would be useful, since async closures return
577 // concrete anonymous future types, and their futures are not coerced
578 // into any other type within the body of the async closure.
579let ty::Infer(ty::TyVar(return_vid)) = *projection.skip_binder().term.expect_type().kind()
580else {
581return None;
582 };
583584// FIXME: We may want to elaborate here, though I assume this will be exceedingly rare.
585let mut return_ty = None;
586for bound in self.obligations_for_self_ty(return_vid, UseSubtyping::No) {
587if let Some(ret_projection) = bound.predicate.as_projection_clause()
588 && let Some(ret_projection) = ret_projection.no_bound_vars()
589 && self.tcx.is_lang_item(ret_projection.def_id(), LangItem::FutureOutput)
590 {
591 return_ty = Some(ret_projection.term.expect_type());
592break;
593 }
594 }
595596// SUBTLE: If we didn't find a `Future<Output = ...>` bound for the return
597 // vid, we still want to attempt to provide inference guidance for the async
598 // closure's arguments. Instantiate a new vid to plug into the output type.
599 //
600 // You may be wondering, what if it's higher-ranked? Well, given that we
601 // found a type variable for the `FnOnce::Output` projection above, we know
602 // that the output can't mention any of the vars.
603 //
604 // Also note that we use a fresh var here for the signature since the signature
605 // records the output of the *future*, and `return_vid` above is the type
606 // variable of the future, not its output.
607 //
608 // FIXME: We probably should store this signature inference output in a way
609 // that does not misuse a `FnSig` type, but that can be done separately.
610let return_ty =
611return_ty.unwrap_or_else(|| self.next_ty_var(cause_span.unwrap_or(DUMMY_SP)));
612613let sig = projection.rebind(self.tcx.mk_fn_sig_safe_rust_abi(input_tys, return_ty));
614615Some(ExpectedSig { cause_span, sig })
616 }
617618fn sig_of_closure(
619&self,
620 expr_def_id: LocalDefId,
621 decl: &hir::FnDecl<'tcx>,
622 closure_kind: hir::ClosureKind,
623 expected_sig: Option<ExpectedSig<'tcx>>,
624 ) -> ClosureSignatures<'tcx> {
625if let Some(e) = expected_sig {
626self.sig_of_closure_with_expectation(expr_def_id, decl, closure_kind, e)
627 } else {
628self.sig_of_closure_no_expectation(expr_def_id, decl, closure_kind)
629 }
630 }
631632/// If there is no expected signature, then we will convert the
633 /// types that the user gave into a signature.
634#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("sig_of_closure_no_expectation",
"rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/closure.rs"),
::tracing_core::__macro_support::Option::Some(634u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("closure_kind")
}> =
::tracing::__macro_support::FieldName::new("closure_kind");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_kind)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: ClosureSignatures<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let bound_sig =
self.supplied_sig_of_closure(expr_def_id, decl, closure_kind);
self.closure_sigs(expr_def_id, bound_sig)
}
}
}#[instrument(skip(self, expr_def_id, decl), level = "debug")]635fn sig_of_closure_no_expectation(
636&self,
637 expr_def_id: LocalDefId,
638 decl: &hir::FnDecl<'tcx>,
639 closure_kind: hir::ClosureKind,
640 ) -> ClosureSignatures<'tcx> {
641let bound_sig = self.supplied_sig_of_closure(expr_def_id, decl, closure_kind);
642643self.closure_sigs(expr_def_id, bound_sig)
644 }
645646/// Invoked to compute the signature of a closure expression. This
647 /// combines any user-provided type annotations (e.g., `|x: u32|
648 /// -> u32 { .. }`) with the expected signature.
649 ///
650 /// The approach is as follows:
651 ///
652 /// - Let `S` be the (higher-ranked) signature that we derive from the user's annotations.
653 /// - Let `E` be the (higher-ranked) signature that we derive from the expectations, if any.
654 /// - If we have no expectation `E`, then the signature of the closure is `S`.
655 /// - Otherwise, the signature of the closure is E. Moreover:
656 /// - Skolemize the late-bound regions in `E`, yielding `E'`.
657 /// - Instantiate all the late-bound regions bound in the closure within `S`
658 /// with fresh (existential) variables, yielding `S'`
659 /// - Require that `E' = S'`
660 /// - We could use some kind of subtyping relationship here,
661 /// I imagine, but equality is easier and works fine for
662 /// our purposes.
663 ///
664 /// The key intuition here is that the user's types must be valid
665 /// from "the inside" of the closure, but the expectation
666 /// ultimately drives the overall signature.
667 ///
668 /// # Examples
669 ///
670 /// ```ignore (illustrative)
671 /// fn with_closure<F>(_: F)
672 /// where F: Fn(&u32) -> &u32 { .. }
673 ///
674 /// with_closure(|x: &u32| { ... })
675 /// ```
676 ///
677 /// Here:
678 /// - E would be `fn(&u32) -> &u32`.
679 /// - S would be `fn(&u32) -> ?T`
680 /// - E' is `&'!0 u32 -> &'!0 u32`
681 /// - S' is `&'?0 u32 -> ?T`
682 ///
683 /// S' can be unified with E' with `['?0 = '!0, ?T = &'!10 u32]`.
684 ///
685 /// # Arguments
686 ///
687 /// - `expr_def_id`: the `LocalDefId` of the closure expression
688 /// - `decl`: the HIR declaration of the closure
689 /// - `body`: the body of the closure
690 /// - `expected_sig`: the expected signature (if any). Note that
691 /// this is missing a binder: that is, there may be late-bound
692 /// regions with depth 1, which are bound then by the closure.
693#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("sig_of_closure_with_expectation",
"rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/closure.rs"),
::tracing_core::__macro_support::Option::Some(693u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("closure_kind")
}> =
::tracing::__macro_support::FieldName::new("closure_kind");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("expected_sig")
}> =
::tracing::__macro_support::FieldName::new("expected_sig");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_kind)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected_sig)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: ClosureSignatures<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
if expected_sig.sig.c_variadic() != decl.c_variadic() {
return self.sig_of_closure_no_expectation(expr_def_id, decl,
closure_kind);
} else if expected_sig.sig.skip_binder().inputs_and_output.len()
!= decl.inputs.len() + 1 {
return self.sig_of_closure_with_mismatched_number_of_arguments(expr_def_id,
decl, expected_sig);
}
if !!expected_sig.sig.skip_binder().has_vars_bound_above(ty::INNERMOST)
{
::core::panicking::panic("assertion failed: !expected_sig.sig.skip_binder().has_vars_bound_above(ty::INNERMOST)")
};
let bound_sig =
expected_sig.sig.map_bound(|sig|
{
let fn_sig_kind =
FnSigKind::default().set_abi(ExternAbi::RustCall).set_safety(hir::Safety::Safe).set_c_variadic(sig.c_variadic());
self.tcx.mk_fn_sig(sig.inputs().iter().cloned(),
sig.output(), fn_sig_kind)
});
let bound_sig = self.tcx.anonymize_bound_vars(bound_sig);
let closure_sigs = self.closure_sigs(expr_def_id, bound_sig);
match self.merge_supplied_sig_with_expectation(expr_def_id, decl,
closure_kind, closure_sigs) {
Ok(infer_ok) => self.register_infer_ok_obligations(infer_ok),
Err(_) =>
self.sig_of_closure_no_expectation(expr_def_id, decl,
closure_kind),
}
}
}
}#[instrument(skip(self, expr_def_id, decl), level = "debug")]694fn sig_of_closure_with_expectation(
695&self,
696 expr_def_id: LocalDefId,
697 decl: &hir::FnDecl<'tcx>,
698 closure_kind: hir::ClosureKind,
699 expected_sig: ExpectedSig<'tcx>,
700 ) -> ClosureSignatures<'tcx> {
701// Watch out for some surprises and just ignore the
702 // expectation if things don't see to match up with what we
703 // expect.
704if expected_sig.sig.c_variadic() != decl.c_variadic() {
705return self.sig_of_closure_no_expectation(expr_def_id, decl, closure_kind);
706 } else if expected_sig.sig.skip_binder().inputs_and_output.len() != decl.inputs.len() + 1 {
707return self.sig_of_closure_with_mismatched_number_of_arguments(
708 expr_def_id,
709 decl,
710 expected_sig,
711 );
712 }
713714// Create a `PolyFnSig`. Note the oddity that late bound
715 // regions appearing free in `expected_sig` are now bound up
716 // in this binder we are creating.
717assert!(!expected_sig.sig.skip_binder().has_vars_bound_above(ty::INNERMOST));
718let bound_sig = expected_sig.sig.map_bound(|sig| {
719// Ignore splatting, it is unsupported on closures.
720let fn_sig_kind = FnSigKind::default()
721 .set_abi(ExternAbi::RustCall)
722 .set_safety(hir::Safety::Safe)
723 .set_c_variadic(sig.c_variadic());
724self.tcx.mk_fn_sig(sig.inputs().iter().cloned(), sig.output(), fn_sig_kind)
725 });
726727// `deduce_expectations_from_expected_type` introduces
728 // late-bound lifetimes defined elsewhere, which we now
729 // anonymize away, so as not to confuse the user.
730let bound_sig = self.tcx.anonymize_bound_vars(bound_sig);
731732let closure_sigs = self.closure_sigs(expr_def_id, bound_sig);
733734// Up till this point, we have ignored the annotations that the user
735 // gave. This function will check that they unify successfully.
736 // Along the way, it also writes out entries for types that the user
737 // wrote into our typeck results, which are then later used by the privacy
738 // check.
739match self.merge_supplied_sig_with_expectation(
740 expr_def_id,
741 decl,
742 closure_kind,
743 closure_sigs,
744 ) {
745Ok(infer_ok) => self.register_infer_ok_obligations(infer_ok),
746Err(_) => self.sig_of_closure_no_expectation(expr_def_id, decl, closure_kind),
747 }
748 }
749750fn sig_of_closure_with_mismatched_number_of_arguments(
751&self,
752 expr_def_id: LocalDefId,
753 decl: &hir::FnDecl<'tcx>,
754 expected_sig: ExpectedSig<'tcx>,
755 ) -> ClosureSignatures<'tcx> {
756let expr_map_node = self.tcx.hir_node_by_def_id(expr_def_id);
757let expected_args: Vec<_> = expected_sig758 .sig
759 .skip_binder()
760 .inputs()
761 .iter()
762 .map(|ty| ArgKind::from_expected_ty(*ty, None))
763 .collect();
764let (closure_span, closure_arg_span, found_args) =
765match self.err_ctxt().get_fn_like_arguments(expr_map_node) {
766Some((sp, arg_sp, args)) => (Some(sp), arg_sp, args),
767None => (None, None, Vec::new()),
768 };
769let expected_span =
770expected_sig.cause_span.unwrap_or_else(|| self.tcx.def_span(expr_def_id));
771let guar = self772 .err_ctxt()
773 .report_arg_count_mismatch(
774expected_span,
775closure_span,
776expected_args,
777found_args,
778true,
779closure_arg_span,
780 )
781 .emit();
782783let error_sig = self.error_sig_of_closure(decl, guar);
784785self.closure_sigs(expr_def_id, error_sig)
786 }
787788/// Enforce the user's types against the expectation. See
789 /// `sig_of_closure_with_expectation` for details on the overall
790 /// strategy.
791#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("merge_supplied_sig_with_expectation",
"rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/closure.rs"),
::tracing_core::__macro_support::Option::Some(791u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("closure_kind")
}> =
::tracing::__macro_support::FieldName::new("closure_kind");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_kind)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
InferResult<'tcx, ClosureSignatures<'tcx>> = loop {};
return __tracing_attr_fake_return;
}
{
let supplied_sig =
self.supplied_sig_of_closure(expr_def_id, decl, closure_kind);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/closure.rs:805",
"rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/closure.rs"),
::tracing_core::__macro_support::Option::Some(805u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("supplied_sig")
}> =
::tracing::__macro_support::FieldName::new("supplied_sig");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&supplied_sig)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
self.commit_if_ok(|_|
{
let mut all_obligations = PredicateObligations::new();
let supplied_sig =
self.instantiate_binder_with_fresh_vars(self.tcx.def_span(expr_def_id),
BoundRegionConversionTime::FnCall, supplied_sig);
for ((hir_ty, &supplied_ty), expected_ty) in
iter::zip(iter::zip(decl.inputs, supplied_sig.inputs()),
expected_sigs.liberated_sig.inputs()) {
let cause = self.misc(hir_ty.span);
let InferOk { value: (), obligations } =
self.at(&cause,
self.param_env).eq(DefineOpaqueTypes::Yes, *expected_ty,
supplied_ty)?;
all_obligations.extend(obligations);
}
let supplied_output_ty = supplied_sig.output();
let cause = &self.misc(decl.output.span());
let InferOk { value: (), obligations } =
self.at(cause,
self.param_env).eq(DefineOpaqueTypes::Yes,
expected_sigs.liberated_sig.output(), supplied_output_ty)?;
all_obligations.extend(obligations);
let inputs =
supplied_sig.inputs().into_iter().map(|&ty|
self.resolve_vars_if_possible(ty));
let fn_sig_kind =
FnSigKind::default().set_abi(ExternAbi::RustCall).set_safety(hir::Safety::Safe).set_c_variadic(expected_sigs.liberated_sig.c_variadic());
expected_sigs.liberated_sig =
self.tcx.mk_fn_sig(inputs, supplied_output_ty, fn_sig_kind);
Ok(InferOk {
value: expected_sigs,
obligations: all_obligations,
})
})
}
}
}#[instrument(level = "debug", skip(self, expr_def_id, decl, expected_sigs))]792fn merge_supplied_sig_with_expectation(
793&self,
794 expr_def_id: LocalDefId,
795 decl: &hir::FnDecl<'tcx>,
796 closure_kind: hir::ClosureKind,
797mut expected_sigs: ClosureSignatures<'tcx>,
798 ) -> InferResult<'tcx, ClosureSignatures<'tcx>> {
799// Get the signature S that the user gave.
800 //
801 // (See comment on `sig_of_closure_with_expectation` for the
802 // meaning of these letters.)
803let supplied_sig = self.supplied_sig_of_closure(expr_def_id, decl, closure_kind);
804805debug!(?supplied_sig);
806807// FIXME(#45727): As discussed in [this comment][c1], naively
808 // forcing equality here actually results in suboptimal error
809 // messages in some cases. For now, if there would have been
810 // an obvious error, we fallback to declaring the type of the
811 // closure to be the one the user gave, which allows other
812 // error message code to trigger.
813 //
814 // However, I think [there is potential to do even better
815 // here][c2], since in *this* code we have the precise span of
816 // the type parameter in question in hand when we report the
817 // error.
818 //
819 // [c1]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341089706
820 // [c2]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341096796
821self.commit_if_ok(|_| {
822let mut all_obligations = PredicateObligations::new();
823let supplied_sig = self.instantiate_binder_with_fresh_vars(
824self.tcx.def_span(expr_def_id),
825 BoundRegionConversionTime::FnCall,
826 supplied_sig,
827 );
828829// The liberated version of this signature should be a subtype
830 // of the liberated form of the expectation.
831for ((hir_ty, &supplied_ty), expected_ty) in iter::zip(
832 iter::zip(decl.inputs, supplied_sig.inputs()),
833 expected_sigs.liberated_sig.inputs(), // `liberated_sig` is E'.
834) {
835// Check that E' = S'.
836let cause = self.misc(hir_ty.span);
837let InferOk { value: (), obligations } = self.at(&cause, self.param_env).eq(
838 DefineOpaqueTypes::Yes,
839*expected_ty,
840 supplied_ty,
841 )?;
842 all_obligations.extend(obligations);
843 }
844845let supplied_output_ty = supplied_sig.output();
846let cause = &self.misc(decl.output.span());
847let InferOk { value: (), obligations } = self.at(cause, self.param_env).eq(
848 DefineOpaqueTypes::Yes,
849 expected_sigs.liberated_sig.output(),
850 supplied_output_ty,
851 )?;
852 all_obligations.extend(obligations);
853854let inputs =
855 supplied_sig.inputs().into_iter().map(|&ty| self.resolve_vars_if_possible(ty));
856857let fn_sig_kind = FnSigKind::default()
858 .set_abi(ExternAbi::RustCall)
859 .set_safety(hir::Safety::Safe)
860 .set_c_variadic(expected_sigs.liberated_sig.c_variadic());
861 expected_sigs.liberated_sig =
862self.tcx.mk_fn_sig(inputs, supplied_output_ty, fn_sig_kind);
863864Ok(InferOk { value: expected_sigs, obligations: all_obligations })
865 })
866 }
867868/// If there is no expected signature, then we will convert the
869 /// types that the user gave into a signature.
870 ///
871 /// Also, record this closure signature for later.
872x;#[instrument(skip(self, decl), level = "debug", ret)]873fn supplied_sig_of_closure(
874&self,
875 expr_def_id: LocalDefId,
876 decl: &hir::FnDecl<'tcx>,
877 closure_kind: hir::ClosureKind,
878 ) -> ty::PolyFnSig<'tcx> {
879let lowerer = self.lowerer();
880881trace!("decl = {:#?}", decl);
882debug!(?closure_kind);
883884let hir_id = self.tcx.local_def_id_to_hir_id(expr_def_id);
885let bound_vars = self.tcx.late_bound_vars(hir_id);
886887// First, convert the types that the user supplied (if any).
888let supplied_arguments = decl.inputs.iter().map(|a| lowerer.lower_ty(a));
889let supplied_return = match decl.output {
890 hir::FnRetTy::Return(ref output) => lowerer.lower_ty(output),
891 hir::FnRetTy::DefaultReturn(_) => match closure_kind {
892// In the case of the async block that we create for a function body,
893 // we expect the return type of the block to match that of the enclosing
894 // function.
895hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
896 hir::CoroutineDesugaring::Async,
897 hir::CoroutineSource::Fn,
898 )) => {
899debug!("closure is async fn body");
900self.deduce_future_output_from_obligations(expr_def_id).unwrap_or_else(|| {
901// AFAIK, deducing the future output
902 // always succeeds *except* in error cases
903 // like #65159. I'd like to return Error
904 // here, but I can't because I can't
905 // easily (and locally) prove that we
906 // *have* reported an
907 // error. --nikomatsakis
908lowerer.ty_infer(None, decl.output.span())
909 })
910 }
911// All `gen {}` and `async gen {}` must return unit.
912hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
913 hir::CoroutineDesugaring::Gen | hir::CoroutineDesugaring::AsyncGen,
914_,
915 )) => self.tcx.types.unit,
916917// For async blocks, we just fall back to `_` here.
918 // For closures/coroutines, we know nothing about the return
919 // type unless it was supplied.
920hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
921 hir::CoroutineDesugaring::Async,
922_,
923 ))
924 | hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(_))
925 | hir::ClosureKind::Closure
926 | hir::ClosureKind::CoroutineClosure(_) => {
927 lowerer.ty_infer(None, decl.output.span())
928 }
929 },
930 };
931932let fn_sig_kind = FnSigKind::default()
933 .set_abi(ExternAbi::RustCall)
934 .set_safety(hir::Safety::Safe)
935 .set_c_variadic(decl.c_variadic());
936let result = ty::Binder::bind_with_vars(
937self.tcx.mk_fn_sig(supplied_arguments, supplied_return, fn_sig_kind),
938 bound_vars,
939 );
940941let c_result = self.infcx.canonicalize_response(result);
942self.typeck_results.borrow_mut().user_provided_sigs.insert(expr_def_id, c_result);
943944// Normalize only after registering in `user_provided_sigs`.
945self.normalize(self.tcx.def_span(expr_def_id), Unnormalized::new_wip(result))
946 }
947948/// Invoked when we are translating the coroutine that results
949 /// from desugaring an `async fn`. Returns the "sugared" return
950 /// type of the `async fn` -- that is, the return type that the
951 /// user specified. The "desugared" return type is an `impl
952 /// Future<Output = T>`, so we do this by searching through the
953 /// obligations to extract the `T`.
954x;#[instrument(skip(self), level = "debug", ret)]955fn deduce_future_output_from_obligations(&self, body_def_id: LocalDefId) -> Option<Ty<'tcx>> {
956let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
957span_bug!(self.tcx.def_span(body_def_id), "async fn coroutine outside of a fn")
958 });
959960let closure_span = self.tcx.def_span(body_def_id);
961let ret_ty = ret_coercion.borrow().expected_ty();
962let ret_ty = self.resolve_vars_with_obligations(ret_ty);
963964let get_future_output = |clause: ty::Clause<'tcx>, span| {
965// Search for a pending obligation like
966 //
967 // `<R as Future>::Output = T`
968 //
969 // where R is the return type we are expecting. This type `T`
970 // will be our output.
971let bound_clause = clause.kind();
972if let ty::ClauseKind::Projection(proj_clause) = bound_clause.skip_binder() {
973self.deduce_future_output_from_projection(span, bound_clause.rebind(proj_clause))
974 } else {
975None
976}
977 };
978979let output_ty = match *ret_ty.kind() {
980 ty::Infer(ty::TyVar(ret_vid)) => self
981.obligations_for_self_ty(ret_vid, UseSubtyping::No)
982 .into_iter()
983 .find_map(|obligation| {
984 obligation
985 .predicate
986 .as_clause()
987 .and_then(|clause| get_future_output(clause, obligation.cause.span))
988 })?,
989 ty::Alias(_, ty::AliasTy { kind: ty::Projection { .. }, .. }) => {
990return Some(Ty::new_error_with_message(
991self.tcx,
992 closure_span,
993"this projection should have been projected to an opaque type",
994 ));
995 }
996 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => self
997.tcx
998 .explicit_item_self_bounds(def_id)
999 .iter_instantiated_copied(self.tcx, args)
1000 .map(Unnormalized::skip_norm_wip)
1001 .find_map(|(c, s)| get_future_output(c, s))?,
1002 ty::Error(_) => return Some(ret_ty),
1003_ => {
1004span_bug!(closure_span, "invalid async fn coroutine return type: {ret_ty:?}")
1005 }
1006 };
10071008let output_ty = self.normalize(closure_span, Unnormalized::new_wip(output_ty));
10091010// async fn that have opaque types in their return type need to redo the conversion to inference variables
1011 // as they fetch the still opaque version from the signature.
1012let InferOk { value: output_ty, obligations } = self
1013.replace_opaque_types_with_inference_vars(
1014 output_ty,
1015 body_def_id,
1016 closure_span,
1017self.param_env,
1018 );
1019self.register_predicates(obligations);
10201021Some(output_ty)
1022 }
10231024/// Given a projection like
1025 ///
1026 /// `<X as Future>::Output = T`
1027 ///
1028 /// where `X` is some type that has no late-bound regions, returns
1029 /// `Some(T)`. If the projection is for some other trait, returns
1030 /// `None`.
1031fn deduce_future_output_from_projection(
1032&self,
1033 cause_span: Span,
1034 predicate: ty::PolyProjectionPredicate<'tcx>,
1035 ) -> Option<Ty<'tcx>> {
1036{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/closure.rs:1036",
"rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/closure.rs"),
::tracing_core::__macro_support::Option::Some(1036u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("deduce_future_output_from_projection(predicate={0:?})",
predicate) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("deduce_future_output_from_projection(predicate={:?})", predicate);
10371038// We do not expect any bound regions in our predicate, so
1039 // skip past the bound vars.
1040let Some(predicate) = predicate.no_bound_vars() else {
1041{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/closure.rs:1041",
"rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/closure.rs"),
::tracing_core::__macro_support::Option::Some(1041u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("deduce_future_output_from_projection: has late-bound regions")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("deduce_future_output_from_projection: has late-bound regions");
1042return None;
1043 };
10441045// Check that this is a projection from the `Future` trait.
1046let trait_def_id = predicate.projection_term.trait_def_id(self.tcx);
1047if !self.tcx.is_lang_item(trait_def_id, LangItem::Future) {
1048{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/closure.rs:1048",
"rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/closure.rs"),
::tracing_core::__macro_support::Option::Some(1048u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("deduce_future_output_from_projection: not a future")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("deduce_future_output_from_projection: not a future");
1049return None;
1050 }
10511052// The `Future` trait has only one associated item, `Output`,
1053 // so check that this is what we see.
1054let output_assoc_item = self.tcx.associated_item_def_ids(trait_def_id)[0];
1055if output_assoc_item != predicate.def_id() {
1056::rustc_middle::util::bug::span_bug_fmt(cause_span,
format_args!("projecting associated item `{0:?}` from future, which is not Output `{1:?}`",
predicate.projection_term.kind, output_assoc_item));span_bug!(
1057 cause_span,
1058"projecting associated item `{:?}` from future, which is not Output `{:?}`",
1059 predicate.projection_term.kind,
1060 output_assoc_item,
1061 );
1062 }
10631064// Extract the type from the projection. Note that there can
1065 // be no bound variables in this type because the "self type"
1066 // does not have any regions in it.
1067let output_ty = self.resolve_vars_if_possible(predicate.term);
1068{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/closure.rs:1068",
"rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/closure.rs"),
::tracing_core::__macro_support::Option::Some(1068u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("deduce_future_output_from_projection: output_ty={0:?}",
output_ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("deduce_future_output_from_projection: output_ty={:?}", output_ty);
1069// This is a projection on a Fn trait so will always be a type.
1070Some(output_ty.expect_type())
1071 }
10721073/// Converts the types that the user supplied, in case that doing
1074 /// so should yield an error, but returns back a signature where
1075 /// all parameters are of type `ty::Error`.
1076fn error_sig_of_closure(
1077&self,
1078 decl: &hir::FnDecl<'tcx>,
1079 guar: ErrorGuaranteed,
1080 ) -> ty::PolyFnSig<'tcx> {
1081let lowerer = self.lowerer();
1082let err_ty = Ty::new_error(self.tcx, guar);
10831084let supplied_arguments = decl.inputs.iter().map(|a| {
1085// Convert the types that the user supplied (if any), but ignore them.
1086lowerer.lower_ty(a);
1087err_ty1088 });
10891090if let hir::FnRetTy::Return(ref output) = decl.output {
1091lowerer.lower_ty(output);
1092 }
10931094let fn_sig_kind = FnSigKind::default()
1095 .set_abi(ExternAbi::RustCall)
1096 .set_safety(hir::Safety::Safe)
1097 .set_c_variadic(decl.c_variadic());
1098let result = ty::Binder::dummy(self.tcx.mk_fn_sig(supplied_arguments, err_ty, fn_sig_kind));
10991100{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/closure.rs:1100",
"rustc_hir_typeck::closure", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/closure.rs"),
::tracing_core::__macro_support::Option::Some(1100u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::closure"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("supplied_sig_of_closure: result={0:?}",
result) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("supplied_sig_of_closure: result={:?}", result);
11011102result1103 }
11041105x;#[instrument(level = "debug", skip(self), ret)]1106fn closure_sigs(
1107&self,
1108 expr_def_id: LocalDefId,
1109 bound_sig: ty::PolyFnSig<'tcx>,
1110 ) -> ClosureSignatures<'tcx> {
1111let liberated_sig =
1112self.tcx().liberate_late_bound_regions(expr_def_id.to_def_id(), bound_sig);
1113let liberated_sig =
1114self.normalize(self.tcx.def_span(expr_def_id), Unnormalized::new_wip(liberated_sig));
1115 ClosureSignatures { bound_sig, liberated_sig }
1116 }
1117}