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, InferConst, Term, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt,
10    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 alias consts use their parents generics.
81    /// They therefore often contain unused args, making these errors far more likely.
82    ///
83    /// A good example of this is the following:
84    ///
85    /// ```compile_fail,E0308
86    /// #![feature(generic_const_exprs)]
87    ///
88    /// fn bind<const N: usize>(value: [u8; N]) -> [u8; 3 + 4] {
89    ///     todo!()
90    /// }
91    ///
92    /// fn main() {
93    ///     let mut arr = Default::default();
94    ///     arr = bind(arr);
95    /// }
96    /// ```
97    ///
98    /// Here `3 + 4` ends up as `ConstKind::Alias` which uses the generics
99    /// of `fn bind` (meaning that its args contain `N`).
100    ///
101    /// `bind(arr)` now infers that the type of `arr` must be `[u8; N]`.
102    /// The assignment `arr = bind(arr)` now tries to equate `N` with `3 + 4`.
103    ///
104    /// As `3 + 4` contains `N` in its args, this must not succeed.
105    ///
106    /// See `tests/ui/const-generics/occurs-check/` for more examples where this is relevant.
107    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("instantiate_const_var",
                                    "rustc_infer::infer::relate::generalize",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/relate/generalize.rs"),
                                    ::tracing_core::__macro_support::Option::Some(107u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_infer::infer::relate::generalize"),
                                    ::tracing_core::field::FieldSet::new(&["target_is_expected",
                                                    "target_vid", "source_ct"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&target_is_expected
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target_vid)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source_ct)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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