1use std::mem;
23use rustc_data_structures::sso::SsoHashMap;
4use rustc_data_structures::stack::ensure_sufficient_stack;
5use rustc_hir::def_id::DefId;
6use rustc_middle::bug;
7use rustc_middle::ty::error::TypeError;
8use rustc_middle::ty::{
9self, InferConst, Term, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt,
10TypeVisitor,
11};
12use rustc_span::Span;
13use tracing::{debug, instrument, warn};
1415use super::{
16PredicateEmittingRelation, Relate, RelateResult, StructurallyRelateAliases, TypeRelation,
17};
18use crate::infer::type_variable::TypeVariableValue;
19use crate::infer::unify_key::ConstVariableValue;
20use crate::infer::{InferCtxt, RegionVariableOrigin, relate};
2122#[derive(#[automatically_derived]
impl ::core::marker::Copy for TermVid { }Copy, #[automatically_derived]
impl ::core::clone::Clone for TermVid {
#[inline]
fn clone(&self) -> TermVid {
let _: ::core::clone::AssertParamIsClone<ty::TyVid>;
let _: ::core::clone::AssertParamIsClone<ty::ConstVid>;
*self
}
}Clone, #[automatically_derived]
impl ::core::cmp::Eq for TermVid {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<ty::TyVid>;
let _: ::core::cmp::AssertParamIsEq<ty::ConstVid>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for TermVid {
#[inline]
fn eq(&self, other: &TermVid) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(TermVid::Ty(__self_0), TermVid::Ty(__arg1_0)) =>
__self_0 == __arg1_0,
(TermVid::Const(__self_0), TermVid::Const(__arg1_0)) =>
__self_0 == __arg1_0,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for TermVid {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
TermVid::Ty(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Ty",
&__self_0),
TermVid::Const(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Const",
&__self_0),
}
}
}Debug)]
23enum TermVid {
24 Ty(ty::TyVid),
25 Const(ty::ConstVid),
26}
2728impl From<ty::TyVid> for TermVid {
29fn from(value: ty::TyVid) -> Self {
30 TermVid::Ty(value)
31 }
32}
3334impl From<ty::ConstVid> for TermVid {
35fn from(value: ty::ConstVid) -> Self {
36 TermVid::Const(value)
37 }
38}
3940impl<'tcx> InferCtxt<'tcx> {
41/// The idea is that we should ensure that the type variable `target_vid`
42 /// is equal to, a subtype of, or a supertype of `source_ty`.
43 ///
44 /// For this, we will instantiate `target_vid` with a *generalized* version
45 /// of `source_ty`. Generalization introduces other inference variables wherever
46 /// subtyping could occur. This also does the occurs checks, detecting whether
47 /// instantiating `target_vid` would result in a cyclic type. We eagerly error
48 /// in this case.
49 ///
50 /// This is *not* expected to be used anywhere except for an implementation of
51 /// `TypeRelation`. Do not use this, and instead please use `At::eq`, for all
52 /// other usecases (i.e. setting the value of a type var).
53#[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("instantiate_ty_var",
"rustc_infer::infer::relate::generalize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/relate/generalize.rs"),
::tracing_core::__macro_support::Option::Some(53u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer::relate::generalize"),
::tracing_core::field::FieldSet::new(&["target_is_expected",
"target_vid", "instantiation_variance", "source_ty"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&target_is_expected
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target_vid)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instantiation_variance)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source_ty)
as &dyn 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: RelateResult<'tcx, ()> = loop {};
return __tracing_attr_fake_return;
}
{
if true {
if !self.inner.borrow_mut().type_variables().probe(target_vid).is_unknown()
{
::core::panicking::panic("assertion failed: self.inner.borrow_mut().type_variables().probe(target_vid).is_unknown()")
};
};
self.instantiate_var(relation, target_is_expected,
target_vid.into(), instantiation_variance, source_ty.into())
}
}
}#[instrument(level = "debug", skip(self, relation))]54pub fn instantiate_ty_var<R: PredicateEmittingRelation<InferCtxt<'tcx>>>(
55&self,
56 relation: &mut R,
57 target_is_expected: bool,
58 target_vid: ty::TyVid,
59 instantiation_variance: ty::Variance,
60 source_ty: Ty<'tcx>,
61 ) -> RelateResult<'tcx, ()> {
62debug_assert!(self.inner.borrow_mut().type_variables().probe(target_vid).is_unknown());
6364self.instantiate_var(
65 relation,
66 target_is_expected,
67 target_vid.into(),
68 instantiation_variance,
69 source_ty.into(),
70 )
71 }
7273/// Instantiates the const variable `target_vid` with the given constant.
74 ///
75 /// This also tests if the given const `ct` contains an inference variable which was previously
76 /// unioned with `target_vid`. If this is the case, inferring `target_vid` to `ct`
77 /// would result in an infinite type as we continuously replace an inference variable
78 /// in `ct` with `ct` itself.
79 ///
80 /// This is especially important as alias consts use their parents generics.
81 /// They therefore often contain unused args, making these errors far more likely.
82 ///
83 /// A good example of this is the following:
84 ///
85 /// ```compile_fail,E0308
86 /// #![feature(generic_const_exprs)]
87 ///
88 /// fn bind<const N: usize>(value: [u8; N]) -> [u8; 3 + 4] {
89 /// todo!()
90 /// }
91 ///
92 /// fn main() {
93 /// let mut arr = Default::default();
94 /// arr = bind(arr);
95 /// }
96 /// ```
97 ///
98 /// Here `3 + 4` ends up as `ConstKind::Alias` which uses the generics
99 /// of `fn bind` (meaning that its args contain `N`).
100 ///
101 /// `bind(arr)` now infers that the type of `arr` must be `[u8; N]`.
102 /// The assignment `arr = bind(arr)` now tries to equate `N` with `3 + 4`.
103 ///
104 /// As `3 + 4` contains `N` in its args, this must not succeed.
105 ///
106 /// See `tests/ui/const-generics/occurs-check/` for more examples where this is relevant.
107#[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("instantiate_const_var",
"rustc_infer::infer::relate::generalize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/relate/generalize.rs"),
::tracing_core::__macro_support::Option::Some(107u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer::relate::generalize"),
::tracing_core::field::FieldSet::new(&["target_is_expected",
"target_vid", "source_ct"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&target_is_expected
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target_vid)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source_ct)
as &dyn 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: RelateResult<'tcx, ()> = loop {};
return __tracing_attr_fake_return;
}
{
if true {
if !self.inner.borrow_mut().const_unification_table().probe_value(target_vid).is_unknown()
{
::core::panicking::panic("assertion failed: self.inner.borrow_mut().const_unification_table().probe_value(target_vid).is_unknown()")
};
};
self.instantiate_var(relation, target_is_expected,
target_vid.into(), ty::Invariant, source_ct.into())
}
}
}#[instrument(level = "debug", skip(self, relation))]108pub(crate) fn instantiate_const_var<R: PredicateEmittingRelation<InferCtxt<'tcx>>>(
109&self,
110 relation: &mut R,
111 target_is_expected: bool,
112 target_vid: ty::ConstVid,
113 source_ct: ty::Const<'tcx>,
114 ) -> RelateResult<'tcx, ()> {
115// FIXME(generic_const_exprs): Occurs check failures for alias consts
116 // and generic expressions are not yet handled correctly.
117debug_assert!(
118self.inner.borrow_mut().const_unification_table().probe_value(target_vid).is_unknown()
119 );
120121self.instantiate_var(
122 relation,
123 target_is_expected,
124 target_vid.into(),
125 ty::Invariant,
126 source_ct.into(),
127 )
128 }
129130#[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("instantiate_var",
"rustc_infer::infer::relate::generalize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/relate/generalize.rs"),
::tracing_core::__macro_support::Option::Some(130u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer::relate::generalize"),
::tracing_core::field::FieldSet::new(&["target_is_expected",
"target_vid", "instantiation_variance", "source_term"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&target_is_expected
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target_vid)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instantiation_variance)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source_term)
as &dyn 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: RelateResult<'tcx, ()> = loop {};
return __tracing_attr_fake_return;
}
{
let Generalization { value_may_be_infer: generalized_term } =
self.generalize(relation.span(),
relation.structurally_relate_aliases(), target_vid,
instantiation_variance, source_term)?;
self.union_var_term(target_vid, generalized_term);
if generalized_term.is_infer() {
let Some(source_alias) =
source_term.to_alias_term() else {
::rustc_middle::util::bug::bug_fmt(format_args!("generalized `{0:?} to infer, not an alias",
source_term));
};
if self.next_trait_solver() {
if let Some(generalized_ty) = generalized_term.as_type() {
match instantiation_variance {
ty::Invariant =>
relation.register_predicates([ty::ProjectionPredicate {
projection_term: source_alias.into(),
term: generalized_ty.into(),
}]),
ty::Covariant => {
let new_var = self.next_ty_var(relation.span());
relation.register_predicates([ty::PredicateKind::Subtype(ty::SubtypePredicate {
a_is_expected: !target_is_expected,
a: new_var,
b: generalized_ty,
}),
ty::PredicateKind::Clause(ty::ClauseKind::Projection(ty::ProjectionPredicate {
projection_term: source_alias.into(),
term: new_var.into(),
}))]);
}
ty::Contravariant => {
let new_var = self.next_ty_var(relation.span());
relation.register_predicates([ty::PredicateKind::Subtype(ty::SubtypePredicate {
a_is_expected: target_is_expected,
a: generalized_ty,
b: new_var,
}),
ty::PredicateKind::Clause(ty::ClauseKind::Projection(ty::ProjectionPredicate {
projection_term: source_alias.into(),
term: new_var.into(),
}))]);
}
ty::Bivariant => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("bivariant generalization")));
}
}
} else {
if true {
{
match (&instantiation_variance, &ty::Variance::Invariant) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};
relation.register_predicates([ty::ProjectionPredicate {
projection_term: source_alias,
term: generalized_term,
}]);
}
} else {
match source_alias.kind {
ty::AliasTermKind::ProjectionTy { .. } |
ty::AliasTermKind::ProjectionConst { .. } => {
relation.register_predicates([ty::ProjectionPredicate {
projection_term: source_alias,
term: generalized_term,
}]);
}
ty::AliasTermKind::InherentTy { .. } |
ty::AliasTermKind::FreeTy { .. } |
ty::AliasTermKind::OpaqueTy { .. } => {
return Err(TypeError::CyclicTy(source_term.expect_type()));
}
ty::AliasTermKind::InherentConst { .. } |
ty::AliasTermKind::FreeConst { .. } |
ty::AliasTermKind::AnonConst { .. } => {
return Err(TypeError::CyclicConst(source_term.expect_const()));
}
}
}
} else {
match generalized_term.kind() {
ty::TermKind::Ty(_) => {
if target_is_expected {
relation.relate(generalized_term, source_term)?;
} else {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_infer/src/infer/relate/generalize.rs:274",
"rustc_infer::infer::relate::generalize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/relate/generalize.rs"),
::tracing_core::__macro_support::Option::Some(274u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer::relate::generalize"),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("flip relation")
as &dyn Value))])
});
} else { ; }
};
relation.relate(source_term, generalized_term)?;
}
}
ty::TermKind::Const(_) => {
if target_is_expected {
relation.relate_with_variance(ty::Invariant,
ty::VarianceDiagInfo::default(), generalized_term,
source_term)?;
} else {
relation.relate_with_variance(ty::Invariant,
ty::VarianceDiagInfo::default(), source_term,
generalized_term)?;
}
}
}
}
Ok(())
}
}
}#[instrument(level = "debug", skip(self, relation))]131fn instantiate_var<R: PredicateEmittingRelation<Self>>(
132&self,
133 relation: &mut R,
134 target_is_expected: bool,
135 target_vid: TermVid,
136 instantiation_variance: ty::Variance,
137 source_term: Term<'tcx>,
138 ) -> RelateResult<'tcx, ()> {
139// Generalize `source_term` depending on the current variance. As an example, assume
140 // `?target <: &'x ?1`, where `'x` is some free region and `?1` is an inference
141 // variable.
142 //
143 // Then the `generalized_term` would be `&'?2 ?3`, where `'?2` and `?3` are fresh
144 // region/type inference variables.
145 //
146 // We then relate `generalized_term <: source_term`, adding constraints like `'x: '?2` and
147 // `?1 <: ?3`.
148let Generalization { value_may_be_infer: generalized_term } = self.generalize(
149 relation.span(),
150 relation.structurally_relate_aliases(),
151 target_vid,
152 instantiation_variance,
153 source_term,
154 )?;
155156// Constrain `b_vid` to the generalized type `generalized_term`.
157self.union_var_term(target_vid, generalized_term);
158159// Finally, relate `generalized_term` to `source_term`, as described in previous comment.
160 //
161 // FIXME(#16847): This code is non-ideal because all these subtype
162 // relations wind up attributed to the same spans. We need
163 // to associate causes/spans with each of the relations in
164 // the stack to get this right.
165if generalized_term.is_infer() {
166// This happens for cases like `<?0 as Trait>::Assoc == ?0`.
167 // We can't instantiate `?0` here as that would result in a
168 // cyclic type. We instead delay the unification in case
169 // the alias can be normalized to something which does not
170 // mention `?0`.
171let Some(source_alias) = source_term.to_alias_term() else {
172bug!("generalized `{source_term:?} to infer, not an alias");
173 };
174if self.next_trait_solver() {
175if let Some(generalized_ty) = generalized_term.as_type() {
176match instantiation_variance {
177 ty::Invariant => relation.register_predicates([ty::ProjectionPredicate {
178 projection_term: source_alias.into(),
179 term: generalized_ty.into(),
180 }]),
181 ty::Covariant => {
182// Generate a new var, then do:
183 // `source_alias == ?A && ?A <: generalized_ty`
184let new_var = self.next_ty_var(relation.span());
185 relation.register_predicates([
186 ty::PredicateKind::Subtype(ty::SubtypePredicate {
187 a_is_expected: !target_is_expected,
188 a: new_var,
189 b: generalized_ty,
190 }),
191 ty::PredicateKind::Clause(ty::ClauseKind::Projection(
192 ty::ProjectionPredicate {
193 projection_term: source_alias.into(),
194 term: new_var.into(),
195 },
196 )),
197 ]);
198 }
199 ty::Contravariant => {
200// a :> b is b <: a
201let new_var = self.next_ty_var(relation.span());
202 relation.register_predicates([
203 ty::PredicateKind::Subtype(ty::SubtypePredicate {
204 a_is_expected: target_is_expected,
205 a: generalized_ty,
206 b: new_var,
207 }),
208 ty::PredicateKind::Clause(ty::ClauseKind::Projection(
209 ty::ProjectionPredicate {
210 projection_term: source_alias.into(),
211 term: new_var.into(),
212 },
213 )),
214 ]);
215 }
216 ty::Bivariant => unreachable!("bivariant generalization"),
217 }
218 } else {
219debug_assert_eq!(instantiation_variance, ty::Variance::Invariant);
220 relation.register_predicates([ty::ProjectionPredicate {
221 projection_term: source_alias,
222 term: generalized_term,
223 }]);
224 }
225 } else {
226match source_alias.kind {
227 ty::AliasTermKind::ProjectionTy { .. }
228 | ty::AliasTermKind::ProjectionConst { .. } => {
229// FIXME: This does not handle subtyping correctly, we could
230 // instead create a new inference variable `?normalized_source`, emitting
231 // `Projection(normalized_source, ?ty_normalized)` and
232 // `?normalized_source <: generalized_term`.
233relation.register_predicates([ty::ProjectionPredicate {
234 projection_term: source_alias,
235 term: generalized_term,
236 }]);
237 }
238// The old solver only accepts projection predicates for associated types.
239ty::AliasTermKind::InherentTy { .. }
240 | ty::AliasTermKind::FreeTy { .. }
241 | ty::AliasTermKind::OpaqueTy { .. } => {
242return Err(TypeError::CyclicTy(source_term.expect_type()));
243 }
244 ty::AliasTermKind::InherentConst { .. }
245 | ty::AliasTermKind::FreeConst { .. }
246 | ty::AliasTermKind::AnonConst { .. } => {
247return Err(TypeError::CyclicConst(source_term.expect_const()));
248 }
249 }
250 }
251 } else {
252// NOTE: The `instantiation_variance` is not the same variance as
253 // used by the relation. When instantiating `b`, `target_is_expected`
254 // is flipped and the `instantiation_variance` is also flipped. To
255 // constrain the `generalized_term` while using the original relation,
256 // we therefore only have to flip the arguments.
257 //
258 // ```ignore (not code)
259 // ?a rel B
260 // instantiate_ty_var(?a, B) # expected and variance not flipped
261 // B' rel B
262 // ```
263 // or
264 // ```ignore (not code)
265 // A rel ?b
266 // instantiate_ty_var(?b, A) # expected and variance flipped
267 // A rel A'
268 // ```
269match generalized_term.kind() {
270 ty::TermKind::Ty(_) => {
271if target_is_expected {
272 relation.relate(generalized_term, source_term)?;
273 } else {
274debug!("flip relation");
275 relation.relate(source_term, generalized_term)?;
276 }
277 }
278 ty::TermKind::Const(_) => {
279// Override consts to always be invariant
280if target_is_expected {
281 relation.relate_with_variance(
282 ty::Invariant,
283 ty::VarianceDiagInfo::default(),
284 generalized_term,
285 source_term,
286 )?;
287 } else {
288 relation.relate_with_variance(
289 ty::Invariant,
290 ty::VarianceDiagInfo::default(),
291 source_term,
292 generalized_term,
293 )?;
294 }
295 }
296 }
297 }
298299Ok(())
300 }
301302/// This is a thin wrapper around inserting into the var tables. You probably want
303 /// [`Self::instantiate_var`] instead, which calls this method.
304fn union_var_term(&self, l: TermVid, r: ty::Term<'tcx>) {
305match (l, r.kind()) {
306 (TermVid::Ty(l), ty::TermKind::Ty(r)) => {
307if let Some(r) = r.ty_vid() {
308self.inner.borrow_mut().type_variables().equate(l, r)
309 } else {
310self.inner.borrow_mut().type_variables().instantiate(l, r)
311 }
312 }
313 (TermVid::Const(l), ty::TermKind::Const(r)) => {
314if let Some(r) = r.ct_vid() {
315self.inner.borrow_mut().const_unification_table().union(l, r)
316 } else {
317self.inner
318 .borrow_mut()
319 .const_unification_table()
320 .union_value(l, ConstVariableValue::Known { value: r })
321 }
322 }
323_ => ::rustc_middle::util::bug::bug_fmt(format_args!("mismatched term kinds in generalize: {0:?}, {1:?}",
l, r))bug!("mismatched term kinds in generalize: {l:?}, {r:?}"),
324 }
325 }
326327/// Attempts to generalize `source_term` for the type variable `target_vid`.
328 /// This checks for cycles -- that is, whether `source_term` references `target_vid`.
329fn generalize(
330&self,
331 span: Span,
332 structurally_relate_aliases: StructurallyRelateAliases,
333 target_vid: TermVid,
334 ambient_variance: ty::Variance,
335 source_term: Term<'tcx>,
336 ) -> RelateResult<'tcx, Generalization<Term<'tcx>>> {
337if !!source_term.has_escaping_bound_vars() {
::core::panicking::panic("assertion failed: !source_term.has_escaping_bound_vars()")
};assert!(!source_term.has_escaping_bound_vars());
338let (for_universe, root_vid) = match target_vid {
339 TermVid::Ty(ty_vid) => {
340 (self.try_resolve_ty_var(ty_vid).unwrap_err(), TermVid::Ty(self.root_var(ty_vid)))
341 }
342 TermVid::Const(ct_vid) => (
343self.try_resolve_const_var(ct_vid).unwrap_err(),
344 TermVid::Const(self.inner.borrow_mut().const_unification_table().find(ct_vid).vid),
345 ),
346 };
347348let mut generalizer = Generalizer {
349 infcx: self,
350span,
351structurally_relate_aliases,
352root_vid,
353for_universe,
354 root_term: source_term,
355ambient_variance,
356 in_alias: false,
357 cache: Default::default(),
358 };
359360let value_may_be_infer = generalizer.relate(source_term, source_term)?;
361Ok(Generalization { value_may_be_infer })
362 }
363}
364365/// Finds the max universe present
366struct MaxUniverse {
367 max_universe: ty::UniverseIndex,
368}
369370impl MaxUniverse {
371fn new() -> Self {
372MaxUniverse { max_universe: ty::UniverseIndex::ROOT }
373 }
374375fn max_universe(self) -> ty::UniverseIndex {
376self.max_universe
377 }
378}
379380impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for MaxUniverse {
381fn visit_ty(&mut self, t: Ty<'tcx>) {
382if let ty::Placeholder(placeholder) = t.kind() {
383self.max_universe = self.max_universe.max(placeholder.universe);
384 }
385386t.super_visit_with(self)
387 }
388389fn visit_const(&mut self, c: ty::Const<'tcx>) {
390if let ty::ConstKind::Placeholder(placeholder) = c.kind() {
391self.max_universe = self.max_universe.max(placeholder.universe);
392 }
393394c.super_visit_with(self)
395 }
396397fn visit_region(&mut self, r: ty::Region<'tcx>) {
398if let ty::RePlaceholder(placeholder) = r.kind() {
399self.max_universe = self.max_universe.max(placeholder.universe);
400 }
401 }
402}
403404/// The "generalizer" is used when handling inference variables.
405///
406/// The basic strategy for handling a constraint like `?A <: B` is to
407/// apply a "generalization strategy" to the term `B` -- this replaces
408/// all the lifetimes in the term `B` with fresh inference variables.
409/// (You can read more about the strategy in this [blog post].)
410///
411/// As an example, if we had `?A <: &'x u32`, we would generalize `&'x
412/// u32` to `&'0 u32` where `'0` is a fresh variable. This becomes the
413/// value of `A`. Finally, we relate `&'0 u32 <: &'x u32`, which
414/// establishes `'0: 'x` as a constraint.
415///
416/// [blog post]: https://is.gd/0hKvIr
417struct Generalizer<'me, 'tcx> {
418 infcx: &'me InferCtxt<'tcx>,
419420 span: Span,
421422/// Whether aliases should be related structurally. If not, we have to
423 /// be careful when generalizing aliases.
424structurally_relate_aliases: StructurallyRelateAliases,
425426/// The vid of the type variable that is in the process of being
427 /// instantiated. If we find this within the value we are folding,
428 /// that means we would have created a cyclic value.
429root_vid: TermVid,
430431/// The universe of the type variable that is in the process of being
432 /// instantiated. If we find anything that this universe cannot name,
433 /// we reject the relation.
434for_universe: ty::UniverseIndex,
435436/// The root term (const or type) we're generalizing. Used for cycle errors.
437root_term: Term<'tcx>,
438439/// After we generalize this type, we are going to relate it to
440 /// some other type. What will be the variance at this point?
441ambient_variance: ty::Variance,
442443/// This is set once we're generalizing the arguments of an alias.
444 ///
445 /// This is necessary to correctly handle
446 /// `<T as Bar<<?0 as Foo>::Assoc>::Assoc == ?0`. This equality can
447 /// hold by either normalizing the outer or the inner associated type.
448in_alias: bool,
449450 cache: SsoHashMap<(Ty<'tcx>, ty::Variance, bool), Ty<'tcx>>,
451}
452453impl<'tcx> Generalizer<'_, 'tcx> {
454/// Create an error that corresponds to the term kind in `root_term`
455fn cyclic_term_error(&self) -> TypeError<'tcx> {
456match self.root_term.kind() {
457 ty::TermKind::Ty(ty) => TypeError::CyclicTy(ty),
458 ty::TermKind::Const(ct) => TypeError::CyclicConst(ct),
459 }
460 }
461462/// Create a new type variable in the universe of the target when
463 /// generalizing an alias.
464fn next_var_for_alias_of_kind(&self, alias: ty::AliasTerm<'tcx>) -> ty::Term<'tcx> {
465if alias.kind.is_type() {
466self.infcx.next_ty_var_in_universe(self.span, self.for_universe).into()
467 } else {
468self.infcx.next_const_var_in_universe(self.span, self.for_universe).into()
469 }
470 }
471472/// We only handle potentially normalizable aliases via this method. For rigid alias,
473 /// we always generalize structurally.
474 ///
475 /// An occurs check failure inside of an alias does not mean
476 /// that the types definitely don't unify. We may be able
477 /// to normalize the alias after all.
478 ///
479 /// We handle this by lazily equating the normalizable alias
480 /// and generalizing it to an inference variable. In the new solver,
481 /// we always generalize to an infer var unless the alias contains escaping
482 /// bound variables.
483 ///
484 /// Correctly handling aliases with escaping bound variables is
485 /// difficult and currently incomplete in two opposite ways:
486 /// - if we get an occurs check failure in the alias, replace it with a new infer var.
487 /// This causes us to later emit an alias-relate goal and is incomplete in case the
488 /// alias normalizes to type containing one of the bound variables.
489 /// - if the alias contains an inference variable not nameable by `for_universe`, we
490 /// continue generalizing the alias. This ends up pulling down the universe of the
491 /// inference variable and is incomplete in case the alias would normalize to a type
492 /// which does not mention that inference variable.
493fn generalize_alias_term(
494&mut self,
495 alias: ty::AliasTerm<'tcx>,
496 ) -> Result<Term<'tcx>, TypeError<'tcx>> {
497// We do not eagerly replace aliases with inference variables if they have
498 // escaping bound vars, see the method comment for details. However, when we
499 // are inside of an alias with escaping bound vars replacing nested aliases
500 // with inference variables can cause incorrect ambiguity.
501 //
502 // cc trait-system-refactor-initiative#110
503if self.infcx.next_trait_solver() && !alias.has_escaping_bound_vars() && !self.in_alias {
504return Ok(self.next_var_for_alias_of_kind(alias));
505 }
506507let is_nested_alias = mem::replace(&mut self.in_alias, true);
508let result = match self.relate(alias, alias) {
509Ok(alias) => Ok(alias.to_term(self.cx(), ty::IsRigid::No)),
510Err(e) => {
511if is_nested_alias {
512return Err(e);
513 } else {
514let mut visitor = MaxUniverse::new();
515alias.visit_with(&mut visitor);
516let infer_replacement_is_complete =
517self.for_universe.can_name(visitor.max_universe())
518 && !alias.has_escaping_bound_vars();
519if !infer_replacement_is_complete {
520{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_infer/src/infer/relate/generalize.rs:520",
"rustc_infer::infer::relate::generalize",
::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/relate/generalize.rs"),
::tracing_core::__macro_support::Option::Some(520u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer::relate::generalize"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::WARN <=
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("may incompletely handle alias type: {0:?}",
alias) as &dyn Value))])
});
} else { ; }
};warn!("may incompletely handle alias type: {alias:?}");
521 }
522523{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_infer/src/infer/relate/generalize.rs:523",
"rustc_infer::infer::relate::generalize",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/relate/generalize.rs"),
::tracing_core::__macro_support::Option::Some(523u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer::relate::generalize"),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("generalization failure in alias")
as &dyn Value))])
});
} else { ; }
};debug!("generalization failure in alias");
524Ok(self.next_var_for_alias_of_kind(alias))
525 }
526 }
527 };
528self.in_alias = is_nested_alias;
529result530 }
531}
532533impl<'tcx> TypeRelation<TyCtxt<'tcx>> for Generalizer<'_, 'tcx> {
534fn cx(&self) -> TyCtxt<'tcx> {
535self.infcx.tcx
536 }
537538fn relate_ty_args(
539&mut self,
540 a_ty: Ty<'tcx>,
541_: Ty<'tcx>,
542 def_id: DefId,
543 a_args: ty::GenericArgsRef<'tcx>,
544 b_args: ty::GenericArgsRef<'tcx>,
545 mk: impl FnOnce(ty::GenericArgsRef<'tcx>) -> Ty<'tcx>,
546 ) -> RelateResult<'tcx, Ty<'tcx>> {
547let args = if self.ambient_variance == ty::Invariant {
548// Avoid fetching the variance if we are in an invariant
549 // context; no need, and it can induce dependency cycles
550 // (e.g., #41849).
551relate::relate_args_invariantly(self, a_args, b_args)
552 } else {
553let tcx = self.cx();
554let variances = tcx.variances_of(def_id);
555 relate::relate_args_with_variances(self, variances, a_args, b_args)
556 }?;
557if args == a_args { Ok(a_ty) } else { Ok(mk(args)) }
558 }
559560x;#[instrument(level = "debug", skip(self, variance, b), ret)]561fn relate_with_variance<T: Relate<TyCtxt<'tcx>>>(
562&mut self,
563 variance: ty::Variance,
564 _info: ty::VarianceDiagInfo<TyCtxt<'tcx>>,
565 a: T,
566 b: T,
567 ) -> RelateResult<'tcx, T> {
568let old_ambient_variance = self.ambient_variance;
569self.ambient_variance = self.ambient_variance.xform(variance);
570debug!(?self.ambient_variance, "new ambient variance");
571// Recursive calls to `relate` can overflow the stack. For example a deeper version of
572 // `ui/associated-consts/issue-93775.rs`.
573let r = ensure_sufficient_stack(|| self.relate(a, b));
574self.ambient_variance = old_ambient_variance;
575 r
576 }
577578x;#[instrument(level = "debug", skip(self, t2), ret)]579fn tys(&mut self, t: Ty<'tcx>, t2: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
580assert_eq!(t, t2); // we are misusing TypeRelation here; both LHS and RHS ought to be ==
581582if let Some(&result) = self.cache.get(&(t, self.ambient_variance, self.in_alias)) {
583return Ok(result);
584 }
585586// Check to see whether the type we are generalizing references
587 // any other type variable related to `vid` via
588 // subtyping. This is basically our "occurs check", preventing
589 // us from creating infinitely sized types.
590let g = match *t.kind() {
591 ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
592bug!("unexpected infer type: {t}")
593 }
594595 ty::Infer(ty::TyVar(vid)) => {
596let mut inner = self.infcx.inner.borrow_mut();
597let vid = inner.type_variables().root_var(vid);
598if TermVid::Ty(vid) == self.root_vid {
599// If sub-roots are equal, then `root_vid` and
600 // `vid` are related via subtyping.
601Err(self.cyclic_term_error())
602 } else {
603let probe = inner.type_variables().probe(vid);
604match probe {
605 TypeVariableValue::Known { value: u } => {
606 drop(inner);
607self.relate(u, u)
608 }
609 TypeVariableValue::Unknown { universe } => {
610match self.ambient_variance {
611// Invariant: no need to make a fresh type variable
612 // if we can name the universe.
613ty::Invariant => {
614if self.for_universe.can_name(universe) {
615return Ok(t);
616 }
617 }
618619// We do need a fresh type variable otherwise.
620ty::Bivariant | ty::Covariant | ty::Contravariant => (),
621 }
622623let origin = inner.type_variables().var_origin(vid);
624let new_var_id =
625 inner.type_variables().new_var(self.for_universe, origin);
626// Record that `vid` and `new_var_id` have to be subtypes
627 // of each other. This is currently only used for diagnostics.
628 // To see why, see the docs in the `type_variables` module.
629inner.type_variables().sub_unify(vid, new_var_id);
630// If we're in the new solver and create a new inference
631 // variable inside of an alias we eagerly constrain that
632 // inference variable to prevent unexpected ambiguity errors.
633 //
634 // This is incomplete as it pulls down the universe of the
635 // original inference variable, even though the alias could
636 // normalize to a type which does not refer to that type at
637 // all. I don't expect this to cause unexpected errors in
638 // practice.
639 //
640 // We only need to do so for type and const variables, as
641 // region variables do not impact normalization, and will get
642 // correctly constrained by `AliasRelate` later on.
643 //
644 // cc trait-system-refactor-initiative#108
645if self.infcx.next_trait_solver()
646 && !self.infcx.typing_mode_raw().is_coherence()
647 && self.in_alias
648 {
649 inner.type_variables().equate(vid, new_var_id);
650 }
651652debug!("replacing original vid={:?} with new={:?}", vid, new_var_id);
653Ok(Ty::new_var(self.cx(), new_var_id))
654 }
655 }
656 }
657 }
658659 ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) => {
660// No matter what mode we are in,
661 // integer/floating-point types must be equal to be
662 // relatable.
663Ok(t)
664 }
665666 ty::Placeholder(placeholder) => {
667if self.for_universe.can_name(placeholder.universe) {
668Ok(t)
669 } else {
670debug!(
671"root universe {:?} cannot name placeholder in universe {:?}",
672self.for_universe, placeholder.universe
673 );
674Err(TypeError::Mismatch)
675 }
676 }
677678// We only need to be careful with potentially normalizeable
679 // aliases here. See `generalize_alias_term` for more information.
680ty::Alias(ty::IsRigid::No, data) => match self.structurally_relate_aliases {
681 StructurallyRelateAliases::No => {
682self.generalize_alias_term(data.into()).map(|v| v.expect_type())
683 }
684 StructurallyRelateAliases::Yes => relate::structurally_relate_tys(self, t, t),
685 },
686687_ => relate::structurally_relate_tys(self, t, t),
688 }?;
689690self.cache.insert((t, self.ambient_variance, self.in_alias), g);
691Ok(g)
692 }
693694x;#[instrument(level = "debug", skip(self, r2), ret)]695fn regions(
696&mut self,
697 r: ty::Region<'tcx>,
698 r2: ty::Region<'tcx>,
699 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
700assert_eq!(r, r2); // we are misusing TypeRelation here; both LHS and RHS ought to be ==
701702match r.kind() {
703// Never make variables for regions bound within the type itself,
704 // nor for erased regions.
705ty::ReBound(..) | ty::ReErased => {
706return Ok(r);
707 }
708709// It doesn't really matter for correctness if we generalize ReError,
710 // since we're already on a doomed compilation path.
711ty::ReError(_) => {
712return Ok(r);
713 }
714715 ty::RePlaceholder(..)
716 | ty::ReVar(..)
717 | ty::ReStatic
718 | ty::ReEarlyParam(..)
719 | ty::ReLateParam(..) => {
720// see common code below
721}
722 }
723724// If we are in an invariant context, we can re-use the region
725 // as is, unless it happens to be in some universe that we
726 // can't name.
727if let ty::Invariant = self.ambient_variance {
728let r_universe = self.infcx.universe_of_region(r);
729if self.for_universe.can_name(r_universe) {
730return Ok(r);
731 }
732 }
733734Ok(self
735.infcx
736 .next_region_var_in_universe(RegionVariableOrigin::Misc(self.span), self.for_universe))
737 }
738739x;#[instrument(level = "debug", skip(self, c2), ret)]740fn consts(
741&mut self,
742 c: ty::Const<'tcx>,
743 c2: ty::Const<'tcx>,
744 ) -> RelateResult<'tcx, ty::Const<'tcx>> {
745let tcx = self.cx();
746assert_eq!(c, c2); // we are misusing TypeRelation here; both LHS and RHS ought to be ==
747748match c.kind() {
749 ty::ConstKind::Infer(InferConst::Var(vid)) => {
750// If root const vids are equal, then `root_vid` and
751 // `vid` are related and we'd be inferring an infinitely
752 // deep const.
753if TermVid::Const(
754self.infcx.inner.borrow_mut().const_unification_table().find(vid).vid,
755 ) == self.root_vid
756 {
757return Err(self.cyclic_term_error());
758 }
759760let mut inner = self.infcx.inner.borrow_mut();
761let variable_table = &mut inner.const_unification_table();
762match variable_table.probe_value(vid) {
763 ConstVariableValue::Known { value: u } => {
764 drop(inner);
765self.relate(u, u)
766 }
767 ConstVariableValue::Unknown { origin, universe } => {
768if self.for_universe.can_name(universe) {
769Ok(c)
770 } else {
771let new_var_id = variable_table
772 .new_key(ConstVariableValue::Unknown {
773 origin,
774 universe: self.for_universe,
775 })
776 .vid;
777778// See the comment for type inference variables
779 // for more details.
780if self.infcx.next_trait_solver()
781 && !self.infcx.typing_mode_raw().is_coherence()
782 && self.in_alias
783 {
784 variable_table.union(vid, new_var_id);
785 }
786Ok(ty::Const::new_var(tcx, new_var_id))
787 }
788 }
789 }
790 }
791// FIXME: Alias consts are also not rigid, so the current
792 // approach of always relating them structurally is incomplete.
793 //
794 // FIXME: replace the StructurallyRelateAliases::Yes branch with
795 // `structurally_relate_consts` once it is fully structural.
796 //
797 // We only need to be careful with potentially normalizeable
798 // aliases here. See `generalize_alias_term` for more information.
799ty::ConstKind::Alias(ty::IsRigid::No, alias_const) => {
800match self.structurally_relate_aliases {
801// Hack: Fall back to old behavior if GCE is enabled (it used to just be the Yes
802 // path), as doing this new No path breaks some GCE things. I expect GCE to be
803 // ripped out soon so this shouldn't matter soon.
804StructurallyRelateAliases::No if !tcx.features().generic_const_exprs() => {
805self.generalize_alias_term(alias_const.into()).map(|v| v.expect_const())
806 }
807_ => {
808let ty::AliasConst { kind, args, .. } = alias_const;
809let args = self.relate_with_variance(
810 ty::Invariant,
811 ty::VarianceDiagInfo::default(),
812 args,
813 args,
814 )?;
815Ok(ty::Const::new_alias(
816 tcx,
817 ty::IsRigid::No,
818 ty::AliasConst::new(tcx, kind, args),
819 ))
820 }
821 }
822 }
823 ty::ConstKind::Placeholder(placeholder) => {
824if self.for_universe.can_name(placeholder.universe) {
825Ok(c)
826 } else {
827debug!(
828"root universe {:?} cannot name placeholder in universe {:?}",
829self.for_universe, placeholder.universe
830 );
831Err(TypeError::Mismatch)
832 }
833 }
834_ => relate::structurally_relate_consts(self, c, c),
835 }
836 }
837838x;#[instrument(level = "debug", skip(self), ret)]839fn binders<T>(
840&mut self,
841 a: ty::Binder<'tcx, T>,
842_: ty::Binder<'tcx, T>,
843 ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
844where
845T: Relate<TyCtxt<'tcx>>,
846 {
847let result = self.relate(a.skip_binder(), a.skip_binder())?;
848Ok(a.rebind(result))
849 }
850}
851852/// Result from a generalization operation. This includes
853/// not only the generalized type, but also a bool flag
854/// indicating whether further WF checks are needed.
855#[derive(#[automatically_derived]
impl<T: ::core::fmt::Debug> ::core::fmt::Debug for Generalization<T> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Generalization", "value_may_be_infer", &&self.value_may_be_infer)
}
}Debug)]
856struct Generalization<T> {
857/// When generalizing `<?0 as Trait>::Assoc` or
858 /// `<T as Bar<<?0 as Foo>::Assoc>>::Assoc`
859 /// for `?0` generalization returns an inference
860 /// variable.
861 ///
862 /// This has to be handled with care as it can
863 /// otherwise very easily result in infinite
864 /// recursion.
865pub value_may_be_infer: T,
866}