Skip to main content

rustc_infer/infer/relate/
generalize.rs

1use std::mem;
2
3use 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::{
9    self, AliasRelationDirection, InferConst, Term, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable,
10    TypeVisitableExt, TypeVisitor,
11};
12use rustc_span::Span;
13use tracing::{debug, instrument, warn};
14
15use super::{
16    PredicateEmittingRelation, Relate, RelateResult, StructurallyRelateAliases, TypeRelation,
17};
18use crate::infer::type_variable::TypeVariableValue;
19use crate::infer::unify_key::ConstVariableValue;
20use crate::infer::{InferCtxt, RegionVariableOrigin, relate};
21
22#[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}
27
28impl From<ty::TyVid> for TermVid {
29    fn from(value: ty::TyVid) -> Self {
30        TermVid::Ty(value)
31    }
32}
33
34impl From<ty::ConstVid> for TermVid {
35    fn from(value: ty::ConstVid) -> Self {
36        TermVid::Const(value)
37    }
38}
39
40impl<'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))]
54    pub 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, ()> {
62        debug_assert!(self.inner.borrow_mut().type_variables().probe(target_vid).is_unknown());
63
64        self.instantiate_var(
65            relation,
66            target_is_expected,
67            target_vid.into(),
68            instantiation_variance,
69            source_ty.into(),
70        )
71    }
72
73    /// 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 unevaluated 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::Unevaluated` 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))]
108    pub(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 unevaluated
116        // constants and generic expressions are not yet handled correctly.
117        debug_assert!(
118            self.inner.borrow_mut().const_unification_table().probe_value(target_vid).is_unknown()
119        );
120
121        self.instantiate_var(
122            relation,
123            target_is_expected,
124            target_vid.into(),
125            ty::Invariant,
126            source_ct.into(),
127        )
128    }
129
130    #[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() {
                if self.next_trait_solver() {
                    let (lhs, rhs, direction) =
                        match instantiation_variance {
                            ty::Invariant => {
                                (generalized_term, source_term,
                                    AliasRelationDirection::Equate)
                            }
                            ty::Covariant => {
                                (generalized_term, source_term,
                                    AliasRelationDirection::Subtype)
                            }
                            ty::Contravariant => {
                                (source_term, generalized_term,
                                    AliasRelationDirection::Subtype)
                            }
                            ty::Bivariant => {
                                ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
                                        format_args!("bivariant generalization")));
                            }
                        };
                    relation.register_predicates([ty::PredicateKind::AliasRelate(lhs,
                                    rhs, direction)]);
                } else {
                    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));
                        };
                    match source_alias.kind(self.tcx) {
                        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::UnevaluatedConst => {
                            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:237",
                                                    "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(237u32),
                                                    ::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))]
131    fn 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`.
148        let 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        )?;
155
156        // Constrain `b_vid` to the generalized type `generalized_term`.
157        self.union_var_term(target_vid, generalized_term);
158
159        // 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.
165        if 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`.
171            if self.next_trait_solver() {
172                let (lhs, rhs, direction) = match instantiation_variance {
173                    ty::Invariant => {
174                        (generalized_term, source_term, AliasRelationDirection::Equate)
175                    }
176                    ty::Covariant => {
177                        (generalized_term, source_term, AliasRelationDirection::Subtype)
178                    }
179                    ty::Contravariant => {
180                        (source_term, generalized_term, AliasRelationDirection::Subtype)
181                    }
182                    ty::Bivariant => unreachable!("bivariant generalization"),
183                };
184
185                relation.register_predicates([ty::PredicateKind::AliasRelate(lhs, rhs, direction)]);
186            } else {
187                let Some(source_alias) = source_term.to_alias_term() else {
188                    bug!("generalized `{source_term:?} to infer, not an alias");
189                };
190                match source_alias.kind(self.tcx) {
191                    ty::AliasTermKind::ProjectionTy | ty::AliasTermKind::ProjectionConst => {
192                        // FIXME: This does not handle subtyping correctly, we could
193                        // instead create a new inference variable `?normalized_source`, emitting
194                        // `Projection(normalized_source, ?ty_normalized)` and
195                        // `?normalized_source <: generalized_term`.
196                        relation.register_predicates([ty::ProjectionPredicate {
197                            projection_term: source_alias,
198                            term: generalized_term,
199                        }]);
200                    }
201                    // The old solver only accepts projection predicates for associated types.
202                    ty::AliasTermKind::InherentTy
203                    | ty::AliasTermKind::FreeTy
204                    | ty::AliasTermKind::OpaqueTy => {
205                        return Err(TypeError::CyclicTy(source_term.expect_type()));
206                    }
207                    ty::AliasTermKind::InherentConst
208                    | ty::AliasTermKind::FreeConst
209                    | ty::AliasTermKind::UnevaluatedConst => {
210                        return Err(TypeError::CyclicConst(source_term.expect_const()));
211                    }
212                }
213            }
214        } else {
215            // NOTE: The `instantiation_variance` is not the same variance as
216            // used by the relation. When instantiating `b`, `target_is_expected`
217            // is flipped and the `instantiation_variance` is also flipped. To
218            // constrain the `generalized_term` while using the original relation,
219            // we therefore only have to flip the arguments.
220            //
221            // ```ignore (not code)
222            // ?a rel B
223            // instantiate_ty_var(?a, B) # expected and variance not flipped
224            // B' rel B
225            // ```
226            // or
227            // ```ignore (not code)
228            // A rel ?b
229            // instantiate_ty_var(?b, A) # expected and variance flipped
230            // A rel A'
231            // ```
232            match generalized_term.kind() {
233                ty::TermKind::Ty(_) => {
234                    if target_is_expected {
235                        relation.relate(generalized_term, source_term)?;
236                    } else {
237                        debug!("flip relation");
238                        relation.relate(source_term, generalized_term)?;
239                    }
240                }
241                ty::TermKind::Const(_) => {
242                    // Override consts to always be invariant
243                    if target_is_expected {
244                        relation.relate_with_variance(
245                            ty::Invariant,
246                            ty::VarianceDiagInfo::default(),
247                            generalized_term,
248                            source_term,
249                        )?;
250                    } else {
251                        relation.relate_with_variance(
252                            ty::Invariant,
253                            ty::VarianceDiagInfo::default(),
254                            source_term,
255                            generalized_term,
256                        )?;
257                    }
258                }
259            }
260        }
261
262        Ok(())
263    }
264
265    /// This is a thin wrapper around inserting into the var tables. You probably want
266    /// [`Self::instantiate_var`] instead, which calls this method.
267    fn union_var_term(&self, l: TermVid, r: ty::Term<'tcx>) {
268        match (l, r.kind()) {
269            (TermVid::Ty(l), ty::TermKind::Ty(r)) => {
270                if let Some(r) = r.ty_vid() {
271                    self.inner.borrow_mut().type_variables().equate(l, r)
272                } else {
273                    self.inner.borrow_mut().type_variables().instantiate(l, r)
274                }
275            }
276            (TermVid::Const(l), ty::TermKind::Const(r)) => {
277                if let Some(r) = r.ct_vid() {
278                    self.inner.borrow_mut().const_unification_table().union(l, r)
279                } else {
280                    self.inner
281                        .borrow_mut()
282                        .const_unification_table()
283                        .union_value(l, ConstVariableValue::Known { value: r })
284                }
285            }
286            _ => ::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:?}"),
287        }
288    }
289
290    /// Attempts to generalize `source_term` for the type variable `target_vid`.
291    /// This checks for cycles -- that is, whether `source_term` references `target_vid`.
292    fn generalize(
293        &self,
294        span: Span,
295        structurally_relate_aliases: StructurallyRelateAliases,
296        target_vid: TermVid,
297        ambient_variance: ty::Variance,
298        source_term: Term<'tcx>,
299    ) -> RelateResult<'tcx, Generalization<Term<'tcx>>> {
300        if !!source_term.has_escaping_bound_vars() {
    ::core::panicking::panic("assertion failed: !source_term.has_escaping_bound_vars()")
};assert!(!source_term.has_escaping_bound_vars());
301        let (for_universe, root_vid) = match target_vid {
302            TermVid::Ty(ty_vid) => {
303                (self.try_resolve_ty_var(ty_vid).unwrap_err(), TermVid::Ty(self.root_var(ty_vid)))
304            }
305            TermVid::Const(ct_vid) => (
306                self.try_resolve_const_var(ct_vid).unwrap_err(),
307                TermVid::Const(self.inner.borrow_mut().const_unification_table().find(ct_vid).vid),
308            ),
309        };
310
311        let mut generalizer = Generalizer {
312            infcx: self,
313            span,
314            structurally_relate_aliases,
315            root_vid,
316            for_universe,
317            root_term: source_term,
318            ambient_variance,
319            in_alias: false,
320            cache: Default::default(),
321        };
322
323        let value_may_be_infer = generalizer.relate(source_term, source_term)?;
324        Ok(Generalization { value_may_be_infer })
325    }
326}
327
328/// Finds the max universe present
329struct MaxUniverse {
330    max_universe: ty::UniverseIndex,
331}
332
333impl MaxUniverse {
334    fn new() -> Self {
335        MaxUniverse { max_universe: ty::UniverseIndex::ROOT }
336    }
337
338    fn max_universe(self) -> ty::UniverseIndex {
339        self.max_universe
340    }
341}
342
343impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for MaxUniverse {
344    fn visit_ty(&mut self, t: Ty<'tcx>) {
345        if let ty::Placeholder(placeholder) = t.kind() {
346            self.max_universe = self.max_universe.max(placeholder.universe);
347        }
348
349        t.super_visit_with(self)
350    }
351
352    fn visit_const(&mut self, c: ty::Const<'tcx>) {
353        if let ty::ConstKind::Placeholder(placeholder) = c.kind() {
354            self.max_universe = self.max_universe.max(placeholder.universe);
355        }
356
357        c.super_visit_with(self)
358    }
359
360    fn visit_region(&mut self, r: ty::Region<'tcx>) {
361        if let ty::RePlaceholder(placeholder) = r.kind() {
362            self.max_universe = self.max_universe.max(placeholder.universe);
363        }
364    }
365}
366
367/// The "generalizer" is used when handling inference variables.
368///
369/// The basic strategy for handling a constraint like `?A <: B` is to
370/// apply a "generalization strategy" to the term `B` -- this replaces
371/// all the lifetimes in the term `B` with fresh inference variables.
372/// (You can read more about the strategy in this [blog post].)
373///
374/// As an example, if we had `?A <: &'x u32`, we would generalize `&'x
375/// u32` to `&'0 u32` where `'0` is a fresh variable. This becomes the
376/// value of `A`. Finally, we relate `&'0 u32 <: &'x u32`, which
377/// establishes `'0: 'x` as a constraint.
378///
379/// [blog post]: https://is.gd/0hKvIr
380struct Generalizer<'me, 'tcx> {
381    infcx: &'me InferCtxt<'tcx>,
382
383    span: Span,
384
385    /// Whether aliases should be related structurally. If not, we have to
386    /// be careful when generalizing aliases.
387    structurally_relate_aliases: StructurallyRelateAliases,
388
389    /// The vid of the type variable that is in the process of being
390    /// instantiated. If we find this within the value we are folding,
391    /// that means we would have created a cyclic value.
392    root_vid: TermVid,
393
394    /// The universe of the type variable that is in the process of being
395    /// instantiated. If we find anything that this universe cannot name,
396    /// we reject the relation.
397    for_universe: ty::UniverseIndex,
398
399    /// The root term (const or type) we're generalizing. Used for cycle errors.
400    root_term: Term<'tcx>,
401
402    /// After we generalize this type, we are going to relate it to
403    /// some other type. What will be the variance at this point?
404    ambient_variance: ty::Variance,
405
406    /// This is set once we're generalizing the arguments of an alias.
407    ///
408    /// This is necessary to correctly handle
409    /// `<T as Bar<<?0 as Foo>::Assoc>::Assoc == ?0`. This equality can
410    /// hold by either normalizing the outer or the inner associated type.
411    in_alias: bool,
412
413    cache: SsoHashMap<(Ty<'tcx>, ty::Variance, bool), Ty<'tcx>>,
414}
415
416impl<'tcx> Generalizer<'_, 'tcx> {
417    /// Create an error that corresponds to the term kind in `root_term`
418    fn cyclic_term_error(&self) -> TypeError<'tcx> {
419        match self.root_term.kind() {
420            ty::TermKind::Ty(ty) => TypeError::CyclicTy(ty),
421            ty::TermKind::Const(ct) => TypeError::CyclicConst(ct),
422        }
423    }
424
425    /// Create a new type variable in the universe of the target when
426    /// generalizing an alias.
427    fn next_var_for_alias_of_kind(&self, alias: ty::AliasTerm<'tcx>) -> ty::Term<'tcx> {
428        if alias.kind(self.cx()).is_type() {
429            self.infcx.next_ty_var_in_universe(self.span, self.for_universe).into()
430        } else {
431            self.infcx.next_const_var_in_universe(self.span, self.for_universe).into()
432        }
433    }
434
435    /// An occurs check failure inside of an alias does not mean
436    /// that the types definitely don't unify. We may be able
437    /// to normalize the alias after all.
438    ///
439    /// We handle this by lazily equating the alias and generalizing
440    /// it to an inference variable. In the new solver, we always
441    /// generalize to an infer var unless the alias contains escaping
442    /// bound variables.
443    ///
444    /// Correctly handling aliases with escaping bound variables is
445    /// difficult and currently incomplete in two opposite ways:
446    /// - if we get an occurs check failure in the alias, replace it with a new infer var.
447    ///   This causes us to later emit an alias-relate goal and is incomplete in case the
448    ///   alias normalizes to type containing one of the bound variables.
449    /// - if the alias contains an inference variable not nameable by `for_universe`, we
450    ///   continue generalizing the alias. This ends up pulling down the universe of the
451    ///   inference variable and is incomplete in case the alias would normalize to a type
452    ///   which does not mention that inference variable.
453    fn generalize_alias_term(
454        &mut self,
455        alias: ty::AliasTerm<'tcx>,
456    ) -> Result<Term<'tcx>, TypeError<'tcx>> {
457        // We do not eagerly replace aliases with inference variables if they have
458        // escaping bound vars, see the method comment for details. However, when we
459        // are inside of an alias with escaping bound vars replacing nested aliases
460        // with inference variables can cause incorrect ambiguity.
461        //
462        // cc trait-system-refactor-initiative#110
463        if self.infcx.next_trait_solver() && !alias.has_escaping_bound_vars() && !self.in_alias {
464            return Ok(self.next_var_for_alias_of_kind(alias));
465        }
466
467        let is_nested_alias = mem::replace(&mut self.in_alias, true);
468        let result = match self.relate(alias, alias) {
469            Ok(alias) => Ok(alias.to_term(self.cx())),
470            Err(e) => {
471                if is_nested_alias {
472                    return Err(e);
473                } else {
474                    let mut visitor = MaxUniverse::new();
475                    alias.visit_with(&mut visitor);
476                    let infer_replacement_is_complete =
477                        self.for_universe.can_name(visitor.max_universe())
478                            && !alias.has_escaping_bound_vars();
479                    if !infer_replacement_is_complete {
480                        {
    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:480",
                        "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(480u32),
                        ::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:?}");
481                    }
482
483                    {
    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:483",
                        "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(483u32),
                        ::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");
484                    Ok(self.next_var_for_alias_of_kind(alias))
485                }
486            }
487        };
488        self.in_alias = is_nested_alias;
489        result
490    }
491}
492
493impl<'tcx> TypeRelation<TyCtxt<'tcx>> for Generalizer<'_, 'tcx> {
494    fn cx(&self) -> TyCtxt<'tcx> {
495        self.infcx.tcx
496    }
497
498    fn relate_ty_args(
499        &mut self,
500        a_ty: Ty<'tcx>,
501        _: Ty<'tcx>,
502        def_id: DefId,
503        a_args: ty::GenericArgsRef<'tcx>,
504        b_args: ty::GenericArgsRef<'tcx>,
505        mk: impl FnOnce(ty::GenericArgsRef<'tcx>) -> Ty<'tcx>,
506    ) -> RelateResult<'tcx, Ty<'tcx>> {
507        let args = if self.ambient_variance == ty::Invariant {
508            // Avoid fetching the variance if we are in an invariant
509            // context; no need, and it can induce dependency cycles
510            // (e.g., #41849).
511            relate::relate_args_invariantly(self, a_args, b_args)
512        } else {
513            let tcx = self.cx();
514            let variances = tcx.variances_of(def_id);
515            relate::relate_args_with_variances(self, variances, a_args, b_args)
516        }?;
517        if args == a_args { Ok(a_ty) } else { Ok(mk(args)) }
518    }
519
520    x;#[instrument(level = "debug", skip(self, variance, b), ret)]
521    fn relate_with_variance<T: Relate<TyCtxt<'tcx>>>(
522        &mut self,
523        variance: ty::Variance,
524        _info: ty::VarianceDiagInfo<TyCtxt<'tcx>>,
525        a: T,
526        b: T,
527    ) -> RelateResult<'tcx, T> {
528        let old_ambient_variance = self.ambient_variance;
529        self.ambient_variance = self.ambient_variance.xform(variance);
530        debug!(?self.ambient_variance, "new ambient variance");
531        // Recursive calls to `relate` can overflow the stack. For example a deeper version of
532        // `ui/associated-consts/issue-93775.rs`.
533        let r = ensure_sufficient_stack(|| self.relate(a, b));
534        self.ambient_variance = old_ambient_variance;
535        r
536    }
537
538    x;#[instrument(level = "debug", skip(self, t2), ret)]
539    fn tys(&mut self, t: Ty<'tcx>, t2: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
540        assert_eq!(t, t2); // we are misusing TypeRelation here; both LHS and RHS ought to be ==
541
542        if let Some(&result) = self.cache.get(&(t, self.ambient_variance, self.in_alias)) {
543            return Ok(result);
544        }
545
546        // Check to see whether the type we are generalizing references
547        // any other type variable related to `vid` via
548        // subtyping. This is basically our "occurs check", preventing
549        // us from creating infinitely sized types.
550        let g = match *t.kind() {
551            ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
552                bug!("unexpected infer type: {t}")
553            }
554
555            ty::Infer(ty::TyVar(vid)) => {
556                let mut inner = self.infcx.inner.borrow_mut();
557                let vid = inner.type_variables().root_var(vid);
558                if TermVid::Ty(vid) == self.root_vid {
559                    // If sub-roots are equal, then `root_vid` and
560                    // `vid` are related via subtyping.
561                    Err(self.cyclic_term_error())
562                } else {
563                    let probe = inner.type_variables().probe(vid);
564                    match probe {
565                        TypeVariableValue::Known { value: u } => {
566                            drop(inner);
567                            self.relate(u, u)
568                        }
569                        TypeVariableValue::Unknown { universe } => {
570                            match self.ambient_variance {
571                                // Invariant: no need to make a fresh type variable
572                                // if we can name the universe.
573                                ty::Invariant => {
574                                    if self.for_universe.can_name(universe) {
575                                        return Ok(t);
576                                    }
577                                }
578
579                                // We do need a fresh type variable otherwise.
580                                ty::Bivariant | ty::Covariant | ty::Contravariant => (),
581                            }
582
583                            let origin = inner.type_variables().var_origin(vid);
584                            let new_var_id =
585                                inner.type_variables().new_var(self.for_universe, origin);
586                            // Record that `vid` and `new_var_id` have to be subtypes
587                            // of each other. This is currently only used for diagnostics.
588                            // To see why, see the docs in the `type_variables` module.
589                            inner.type_variables().sub_unify(vid, new_var_id);
590                            // If we're in the new solver and create a new inference
591                            // variable inside of an alias we eagerly constrain that
592                            // inference variable to prevent unexpected ambiguity errors.
593                            //
594                            // This is incomplete as it pulls down the universe of the
595                            // original inference variable, even though the alias could
596                            // normalize to a type which does not refer to that type at
597                            // all. I don't expect this to cause unexpected errors in
598                            // practice.
599                            //
600                            // We only need to do so for type and const variables, as
601                            // region variables do not impact normalization, and will get
602                            // correctly constrained by `AliasRelate` later on.
603                            //
604                            // cc trait-system-refactor-initiative#108
605                            if self.infcx.next_trait_solver()
606                                && !self.infcx.typing_mode().is_coherence()
607                                && self.in_alias
608                            {
609                                inner.type_variables().equate(vid, new_var_id);
610                            }
611
612                            debug!("replacing original vid={:?} with new={:?}", vid, new_var_id);
613                            Ok(Ty::new_var(self.cx(), new_var_id))
614                        }
615                    }
616                }
617            }
618
619            ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) => {
620                // No matter what mode we are in,
621                // integer/floating-point types must be equal to be
622                // relatable.
623                Ok(t)
624            }
625
626            ty::Placeholder(placeholder) => {
627                if self.for_universe.can_name(placeholder.universe) {
628                    Ok(t)
629                } else {
630                    debug!(
631                        "root universe {:?} cannot name placeholder in universe {:?}",
632                        self.for_universe, placeholder.universe
633                    );
634                    Err(TypeError::Mismatch)
635                }
636            }
637
638            ty::Alias(data) => match self.structurally_relate_aliases {
639                StructurallyRelateAliases::No => {
640                    self.generalize_alias_term(data.into()).map(|v| v.expect_type())
641                }
642                StructurallyRelateAliases::Yes => relate::structurally_relate_tys(self, t, t),
643            },
644
645            _ => relate::structurally_relate_tys(self, t, t),
646        }?;
647
648        self.cache.insert((t, self.ambient_variance, self.in_alias), g);
649        Ok(g)
650    }
651
652    x;#[instrument(level = "debug", skip(self, r2), ret)]
653    fn regions(
654        &mut self,
655        r: ty::Region<'tcx>,
656        r2: ty::Region<'tcx>,
657    ) -> RelateResult<'tcx, ty::Region<'tcx>> {
658        assert_eq!(r, r2); // we are misusing TypeRelation here; both LHS and RHS ought to be ==
659
660        match r.kind() {
661            // Never make variables for regions bound within the type itself,
662            // nor for erased regions.
663            ty::ReBound(..) | ty::ReErased => {
664                return Ok(r);
665            }
666
667            // It doesn't really matter for correctness if we generalize ReError,
668            // since we're already on a doomed compilation path.
669            ty::ReError(_) => {
670                return Ok(r);
671            }
672
673            ty::RePlaceholder(..)
674            | ty::ReVar(..)
675            | ty::ReStatic
676            | ty::ReEarlyParam(..)
677            | ty::ReLateParam(..) => {
678                // see common code below
679            }
680        }
681
682        // If we are in an invariant context, we can re-use the region
683        // as is, unless it happens to be in some universe that we
684        // can't name.
685        if let ty::Invariant = self.ambient_variance {
686            let r_universe = self.infcx.universe_of_region(r);
687            if self.for_universe.can_name(r_universe) {
688                return Ok(r);
689            }
690        }
691
692        Ok(self
693            .infcx
694            .next_region_var_in_universe(RegionVariableOrigin::Misc(self.span), self.for_universe))
695    }
696
697    x;#[instrument(level = "debug", skip(self, c2), ret)]
698    fn consts(
699        &mut self,
700        c: ty::Const<'tcx>,
701        c2: ty::Const<'tcx>,
702    ) -> RelateResult<'tcx, ty::Const<'tcx>> {
703        assert_eq!(c, c2); // we are misusing TypeRelation here; both LHS and RHS ought to be ==
704
705        match c.kind() {
706            ty::ConstKind::Infer(InferConst::Var(vid)) => {
707                // If root const vids are equal, then `root_vid` and
708                // `vid` are related and we'd be inferring an infinitely
709                // deep const.
710                if TermVid::Const(
711                    self.infcx.inner.borrow_mut().const_unification_table().find(vid).vid,
712                ) == self.root_vid
713                {
714                    return Err(self.cyclic_term_error());
715                }
716
717                let mut inner = self.infcx.inner.borrow_mut();
718                let variable_table = &mut inner.const_unification_table();
719                match variable_table.probe_value(vid) {
720                    ConstVariableValue::Known { value: u } => {
721                        drop(inner);
722                        self.relate(u, u)
723                    }
724                    ConstVariableValue::Unknown { origin, universe } => {
725                        if self.for_universe.can_name(universe) {
726                            Ok(c)
727                        } else {
728                            let new_var_id = variable_table
729                                .new_key(ConstVariableValue::Unknown {
730                                    origin,
731                                    universe: self.for_universe,
732                                })
733                                .vid;
734
735                            // See the comment for type inference variables
736                            // for more details.
737                            if self.infcx.next_trait_solver()
738                                && !self.infcx.typing_mode().is_coherence()
739                                && self.in_alias
740                            {
741                                variable_table.union(vid, new_var_id);
742                            }
743                            Ok(ty::Const::new_var(self.cx(), new_var_id))
744                        }
745                    }
746                }
747            }
748            // FIXME: Unevaluated constants are also not rigid, so the current
749            // approach of always relating them structurally is incomplete.
750            //
751            // FIXME: replace the StructurallyRelateAliases::Yes branch with
752            // `structurally_relate_consts` once it is fully structural.
753            ty::ConstKind::Unevaluated(uv) => match self.structurally_relate_aliases {
754                // Hack: Fall back to old behavior if GCE is enabled (it used to just be the Yes
755                // path), as doing this new No path breaks some GCE things. I expect GCE to be
756                // ripped out soon so this shouldn't matter soon.
757                StructurallyRelateAliases::No if !self.cx().features().generic_const_exprs() => {
758                    self.generalize_alias_term(uv.into()).map(|v| v.expect_const())
759                }
760                _ => {
761                    let ty::UnevaluatedConst { def, args } = uv;
762                    let args = self.relate_with_variance(
763                        ty::Invariant,
764                        ty::VarianceDiagInfo::default(),
765                        args,
766                        args,
767                    )?;
768                    Ok(ty::Const::new_unevaluated(self.cx(), ty::UnevaluatedConst { def, args }))
769                }
770            },
771            ty::ConstKind::Placeholder(placeholder) => {
772                if self.for_universe.can_name(placeholder.universe) {
773                    Ok(c)
774                } else {
775                    debug!(
776                        "root universe {:?} cannot name placeholder in universe {:?}",
777                        self.for_universe, placeholder.universe
778                    );
779                    Err(TypeError::Mismatch)
780                }
781            }
782            _ => relate::structurally_relate_consts(self, c, c),
783        }
784    }
785
786    x;#[instrument(level = "debug", skip(self), ret)]
787    fn binders<T>(
788        &mut self,
789        a: ty::Binder<'tcx, T>,
790        _: ty::Binder<'tcx, T>,
791    ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
792    where
793        T: Relate<TyCtxt<'tcx>>,
794    {
795        let result = self.relate(a.skip_binder(), a.skip_binder())?;
796        Ok(a.rebind(result))
797    }
798}
799
800/// Result from a generalization operation. This includes
801/// not only the generalized type, but also a bool flag
802/// indicating whether further WF checks are needed.
803#[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)]
804struct Generalization<T> {
805    /// When generalizing `<?0 as Trait>::Assoc` or
806    /// `<T as Bar<<?0 as Foo>::Assoc>>::Assoc`
807    /// for `?0` generalization returns an inference
808    /// variable.
809    ///
810    /// This has to be handled with care as it can
811    /// otherwise very easily result in infinite
812    /// recursion.
813    pub value_may_be_infer: T,
814}