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::{self, InferConst, Term, Ty, TyCtxt, TypeVisitableExt};
9use rustc_span::Span;
10use tracing::{debug, instrument, warn};
11
12use super::{PredicateEmittingRelation, Relate, RelateResult, TypeRelation};
13use crate::infer::type_variable::TypeVariableValue;
14use crate::infer::unify_key::ConstVariableValue;
15use crate::infer::{InferCtxt, RegionVariableOrigin, relate};
16
17#[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)]
18enum TermVid {
19    Ty(ty::TyVid),
20    Const(ty::ConstVid),
21}
22
23impl From<ty::TyVid> for TermVid {
24    fn from(value: ty::TyVid) -> Self {
25        TermVid::Ty(value)
26    }
27}
28
29impl From<ty::ConstVid> for TermVid {
30    fn from(value: ty::ConstVid) -> Self {
31        TermVid::Const(value)
32    }
33}
34
35impl<'tcx> InferCtxt<'tcx> {
36    /// The idea is that we should ensure that the type variable `target_vid`
37    /// is equal to, a subtype of, or a supertype of `source_ty`.
38    ///
39    /// For this, we will instantiate `target_vid` with a *generalized* version
40    /// of `source_ty`. Generalization introduces other inference variables wherever
41    /// subtyping could occur. This also does the occurs checks, detecting whether
42    /// instantiating `target_vid` would result in a cyclic type. We eagerly error
43    /// in this case.
44    ///
45    /// This is *not* expected to be used anywhere except for an implementation of
46    /// `TypeRelation`. Do not use this, and instead please use `At::eq`, for all
47    /// other usecases (i.e. setting the value of a type var).
48    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("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(48u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer::relate::generalize"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("target_is_expected")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("target_is_expected");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("target_vid")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("target_vid");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("instantiation_variance")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("instantiation_variance");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("source_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("source_ty");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&target_is_expected
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target_vid)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instantiation_variance)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source_ty)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: 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))]
49    pub fn instantiate_ty_var<R: PredicateEmittingRelation<InferCtxt<'tcx>>>(
50        &self,
51        relation: &mut R,
52        target_is_expected: bool,
53        target_vid: ty::TyVid,
54        instantiation_variance: ty::Variance,
55        source_ty: Ty<'tcx>,
56    ) -> RelateResult<'tcx, ()> {
57        debug_assert!(self.inner.borrow_mut().type_variables().probe(target_vid).is_unknown());
58
59        self.instantiate_var(
60            relation,
61            target_is_expected,
62            target_vid.into(),
63            instantiation_variance,
64            source_ty.into(),
65        )
66    }
67
68    /// Instantiates the const variable `target_vid` with the given constant.
69    ///
70    /// This also tests if the given const `ct` contains an inference variable which was previously
71    /// unioned with `target_vid`. If this is the case, inferring `target_vid` to `ct`
72    /// would result in an infinite type as we continuously replace an inference variable
73    /// in `ct` with `ct` itself.
74    ///
75    /// This is especially important as alias consts use their parents generics.
76    /// They therefore often contain unused args, making these errors far more likely.
77    ///
78    /// A good example of this is the following:
79    ///
80    /// ```compile_fail,E0308
81    /// #![feature(generic_const_exprs)]
82    ///
83    /// fn bind<const N: usize>(value: [u8; N]) -> [u8; 3 + 4] {
84    ///     todo!()
85    /// }
86    ///
87    /// fn main() {
88    ///     let mut arr = Default::default();
89    ///     arr = bind(arr);
90    /// }
91    /// ```
92    ///
93    /// Here `3 + 4` ends up as `ConstKind::Alias` which uses the generics
94    /// of `fn bind` (meaning that its args contain `N`).
95    ///
96    /// `bind(arr)` now infers that the type of `arr` must be `[u8; N]`.
97    /// The assignment `arr = bind(arr)` now tries to equate `N` with `3 + 4`.
98    ///
99    /// As `3 + 4` contains `N` in its args, this must not succeed.
100    ///
101    /// See `tests/ui/const-generics/occurs-check/` for more examples where this is relevant.
102    #[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(102u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer::relate::generalize"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("target_is_expected")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("target_is_expected");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("target_vid")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("target_vid");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("source_ct")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("source_ct");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&target_is_expected
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target_vid)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source_ct)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: 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))]
103    pub(crate) fn instantiate_const_var<R: PredicateEmittingRelation<InferCtxt<'tcx>>>(
104        &self,
105        relation: &mut R,
106        target_is_expected: bool,
107        target_vid: ty::ConstVid,
108        source_ct: ty::Const<'tcx>,
109    ) -> RelateResult<'tcx, ()> {
110        // FIXME(generic_const_exprs): Occurs check failures for alias consts
111        // and generic expressions are not yet handled correctly.
112        debug_assert!(
113            self.inner.borrow_mut().const_unification_table().probe_value(target_vid).is_unknown()
114        );
115
116        self.instantiate_var(
117            relation,
118            target_is_expected,
119            target_vid.into(),
120            ty::Invariant,
121            source_ct.into(),
122        )
123    }
124
125    #[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(125u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer::relate::generalize"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("target_is_expected")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("target_is_expected");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("target_vid")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("target_vid");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("instantiation_variance")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("instantiation_variance");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("source_term")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("source_term");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&target_is_expected
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target_vid)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instantiation_variance)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source_term)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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