Skip to main content

rustc_type_ir/
fast_reject.rs

1use std::fmt::Debug;
2use std::hash::Hash;
3use std::iter;
4use std::marker::PhantomData;
5
6use rustc_ast_ir::Mutability;
7#[cfg(feature = "nightly")]
8use rustc_data_structures::fingerprint::Fingerprint;
9#[cfg(feature = "nightly")]
10use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
11#[cfg(feature = "nightly")]
12use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_NoContext};
13
14use crate::inherent::*;
15use crate::visit::TypeVisitableExt as _;
16use crate::{self as ty, Interner};
17
18/// See `simplify_type`.
19#[derive(#[automatically_derived]
impl<DefId: ::core::clone::Clone> ::core::clone::Clone for
    SimplifiedType<DefId> {
    #[inline]
    fn clone(&self) -> SimplifiedType<DefId> {
        match self {
            SimplifiedType::Bool => SimplifiedType::Bool,
            SimplifiedType::Char => SimplifiedType::Char,
            SimplifiedType::Int(__self_0) =>
                SimplifiedType::Int(::core::clone::Clone::clone(__self_0)),
            SimplifiedType::Uint(__self_0) =>
                SimplifiedType::Uint(::core::clone::Clone::clone(__self_0)),
            SimplifiedType::Float(__self_0) =>
                SimplifiedType::Float(::core::clone::Clone::clone(__self_0)),
            SimplifiedType::Adt(__self_0) =>
                SimplifiedType::Adt(::core::clone::Clone::clone(__self_0)),
            SimplifiedType::Foreign(__self_0) =>
                SimplifiedType::Foreign(::core::clone::Clone::clone(__self_0)),
            SimplifiedType::Str => SimplifiedType::Str,
            SimplifiedType::Array => SimplifiedType::Array,
            SimplifiedType::Slice => SimplifiedType::Slice,
            SimplifiedType::Ref(__self_0) =>
                SimplifiedType::Ref(::core::clone::Clone::clone(__self_0)),
            SimplifiedType::Ptr(__self_0) =>
                SimplifiedType::Ptr(::core::clone::Clone::clone(__self_0)),
            SimplifiedType::Never => SimplifiedType::Never,
            SimplifiedType::Tuple(__self_0) =>
                SimplifiedType::Tuple(::core::clone::Clone::clone(__self_0)),
            SimplifiedType::MarkerTraitObject =>
                SimplifiedType::MarkerTraitObject,
            SimplifiedType::Trait(__self_0) =>
                SimplifiedType::Trait(::core::clone::Clone::clone(__self_0)),
            SimplifiedType::Closure(__self_0) =>
                SimplifiedType::Closure(::core::clone::Clone::clone(__self_0)),
            SimplifiedType::Coroutine(__self_0) =>
                SimplifiedType::Coroutine(::core::clone::Clone::clone(__self_0)),
            SimplifiedType::CoroutineWitness(__self_0) =>
                SimplifiedType::CoroutineWitness(::core::clone::Clone::clone(__self_0)),
            SimplifiedType::Function(__self_0) =>
                SimplifiedType::Function(::core::clone::Clone::clone(__self_0)),
            SimplifiedType::UnsafeBinder => SimplifiedType::UnsafeBinder,
            SimplifiedType::Placeholder => SimplifiedType::Placeholder,
            SimplifiedType::Error => SimplifiedType::Error,
        }
    }
}Clone, #[automatically_derived]
impl<DefId: ::core::marker::Copy> ::core::marker::Copy for
    SimplifiedType<DefId> {
}Copy, #[automatically_derived]
impl<DefId: ::core::fmt::Debug> ::core::fmt::Debug for SimplifiedType<DefId> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            SimplifiedType::Bool =>
                ::core::fmt::Formatter::write_str(f, "Bool"),
            SimplifiedType::Char =>
                ::core::fmt::Formatter::write_str(f, "Char"),
            SimplifiedType::Int(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Int",
                    &__self_0),
            SimplifiedType::Uint(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Uint",
                    &__self_0),
            SimplifiedType::Float(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Float",
                    &__self_0),
            SimplifiedType::Adt(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Adt",
                    &__self_0),
            SimplifiedType::Foreign(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Foreign", &__self_0),
            SimplifiedType::Str =>
                ::core::fmt::Formatter::write_str(f, "Str"),
            SimplifiedType::Array =>
                ::core::fmt::Formatter::write_str(f, "Array"),
            SimplifiedType::Slice =>
                ::core::fmt::Formatter::write_str(f, "Slice"),
            SimplifiedType::Ref(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Ref",
                    &__self_0),
            SimplifiedType::Ptr(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Ptr",
                    &__self_0),
            SimplifiedType::Never =>
                ::core::fmt::Formatter::write_str(f, "Never"),
            SimplifiedType::Tuple(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Tuple",
                    &__self_0),
            SimplifiedType::MarkerTraitObject =>
                ::core::fmt::Formatter::write_str(f, "MarkerTraitObject"),
            SimplifiedType::Trait(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Trait",
                    &__self_0),
            SimplifiedType::Closure(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Closure", &__self_0),
            SimplifiedType::Coroutine(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Coroutine", &__self_0),
            SimplifiedType::CoroutineWitness(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "CoroutineWitness", &__self_0),
            SimplifiedType::Function(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Function", &__self_0),
            SimplifiedType::UnsafeBinder =>
                ::core::fmt::Formatter::write_str(f, "UnsafeBinder"),
            SimplifiedType::Placeholder =>
                ::core::fmt::Formatter::write_str(f, "Placeholder"),
            SimplifiedType::Error =>
                ::core::fmt::Formatter::write_str(f, "Error"),
        }
    }
}Debug, #[automatically_derived]
impl<DefId: ::core::cmp::PartialEq> ::core::cmp::PartialEq for
    SimplifiedType<DefId> {
    #[inline]
    fn eq(&self, other: &SimplifiedType<DefId>) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (SimplifiedType::Int(__self_0), SimplifiedType::Int(__arg1_0))
                    => __self_0 == __arg1_0,
                (SimplifiedType::Uint(__self_0),
                    SimplifiedType::Uint(__arg1_0)) => __self_0 == __arg1_0,
                (SimplifiedType::Float(__self_0),
                    SimplifiedType::Float(__arg1_0)) => __self_0 == __arg1_0,
                (SimplifiedType::Adt(__self_0), SimplifiedType::Adt(__arg1_0))
                    => __self_0 == __arg1_0,
                (SimplifiedType::Foreign(__self_0),
                    SimplifiedType::Foreign(__arg1_0)) => __self_0 == __arg1_0,
                (SimplifiedType::Ref(__self_0), SimplifiedType::Ref(__arg1_0))
                    => __self_0 == __arg1_0,
                (SimplifiedType::Ptr(__self_0), SimplifiedType::Ptr(__arg1_0))
                    => __self_0 == __arg1_0,
                (SimplifiedType::Tuple(__self_0),
                    SimplifiedType::Tuple(__arg1_0)) => __self_0 == __arg1_0,
                (SimplifiedType::Trait(__self_0),
                    SimplifiedType::Trait(__arg1_0)) => __self_0 == __arg1_0,
                (SimplifiedType::Closure(__self_0),
                    SimplifiedType::Closure(__arg1_0)) => __self_0 == __arg1_0,
                (SimplifiedType::Coroutine(__self_0),
                    SimplifiedType::Coroutine(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (SimplifiedType::CoroutineWitness(__self_0),
                    SimplifiedType::CoroutineWitness(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (SimplifiedType::Function(__self_0),
                    SimplifiedType::Function(__arg1_0)) => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl<DefId: ::core::cmp::Eq> ::core::cmp::Eq for SimplifiedType<DefId> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<ty::IntTy>;
        let _: ::core::cmp::AssertParamIsEq<ty::UintTy>;
        let _: ::core::cmp::AssertParamIsEq<ty::FloatTy>;
        let _: ::core::cmp::AssertParamIsEq<DefId>;
        let _: ::core::cmp::AssertParamIsEq<Mutability>;
        let _: ::core::cmp::AssertParamIsEq<usize>;
    }
}Eq, #[automatically_derived]
impl<DefId: ::core::hash::Hash> ::core::hash::Hash for SimplifiedType<DefId> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state);
        match self {
            SimplifiedType::Int(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            SimplifiedType::Uint(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            SimplifiedType::Float(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            SimplifiedType::Adt(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            SimplifiedType::Foreign(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            SimplifiedType::Ref(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            SimplifiedType::Ptr(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            SimplifiedType::Tuple(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            SimplifiedType::Trait(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            SimplifiedType::Closure(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            SimplifiedType::Coroutine(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            SimplifiedType::CoroutineWitness(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            SimplifiedType::Function(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            _ => {}
        }
    }
}Hash)]
20#[cfg_attr(
21    feature = "nightly",
22    derive(const _: () =
    {
        impl<DefId, __E: ::rustc_serialize::Encoder>
            ::rustc_serialize::Encodable<__E> for SimplifiedType<DefId> where
            DefId: ::rustc_serialize::Encodable<__E> {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        SimplifiedType::Bool => { 0usize }
                        SimplifiedType::Char => { 1usize }
                        SimplifiedType::Int(ref __binding_0) => { 2usize }
                        SimplifiedType::Uint(ref __binding_0) => { 3usize }
                        SimplifiedType::Float(ref __binding_0) => { 4usize }
                        SimplifiedType::Adt(ref __binding_0) => { 5usize }
                        SimplifiedType::Foreign(ref __binding_0) => { 6usize }
                        SimplifiedType::Str => { 7usize }
                        SimplifiedType::Array => { 8usize }
                        SimplifiedType::Slice => { 9usize }
                        SimplifiedType::Ref(ref __binding_0) => { 10usize }
                        SimplifiedType::Ptr(ref __binding_0) => { 11usize }
                        SimplifiedType::Never => { 12usize }
                        SimplifiedType::Tuple(ref __binding_0) => { 13usize }
                        SimplifiedType::MarkerTraitObject => { 14usize }
                        SimplifiedType::Trait(ref __binding_0) => { 15usize }
                        SimplifiedType::Closure(ref __binding_0) => { 16usize }
                        SimplifiedType::Coroutine(ref __binding_0) => { 17usize }
                        SimplifiedType::CoroutineWitness(ref __binding_0) => {
                            18usize
                        }
                        SimplifiedType::Function(ref __binding_0) => { 19usize }
                        SimplifiedType::UnsafeBinder => { 20usize }
                        SimplifiedType::Placeholder => { 21usize }
                        SimplifiedType::Error => { 22usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    SimplifiedType::Bool => {}
                    SimplifiedType::Char => {}
                    SimplifiedType::Int(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    SimplifiedType::Uint(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    SimplifiedType::Float(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    SimplifiedType::Adt(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    SimplifiedType::Foreign(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    SimplifiedType::Str => {}
                    SimplifiedType::Array => {}
                    SimplifiedType::Slice => {}
                    SimplifiedType::Ref(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    SimplifiedType::Ptr(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    SimplifiedType::Never => {}
                    SimplifiedType::Tuple(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    SimplifiedType::MarkerTraitObject => {}
                    SimplifiedType::Trait(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    SimplifiedType::Closure(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    SimplifiedType::Coroutine(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    SimplifiedType::CoroutineWitness(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    SimplifiedType::Function(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    SimplifiedType::UnsafeBinder => {}
                    SimplifiedType::Placeholder => {}
                    SimplifiedType::Error => {}
                }
            }
        }
    };Encodable_NoContext, const _: () =
    {
        impl<DefId, __D: ::rustc_serialize::Decoder>
            ::rustc_serialize::Decodable<__D> for SimplifiedType<DefId> where
            DefId: ::rustc_serialize::Decodable<__D> {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { SimplifiedType::Bool }
                    1usize => { SimplifiedType::Char }
                    2usize => {
                        SimplifiedType::Int(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    3usize => {
                        SimplifiedType::Uint(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    4usize => {
                        SimplifiedType::Float(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    5usize => {
                        SimplifiedType::Adt(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    6usize => {
                        SimplifiedType::Foreign(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    7usize => { SimplifiedType::Str }
                    8usize => { SimplifiedType::Array }
                    9usize => { SimplifiedType::Slice }
                    10usize => {
                        SimplifiedType::Ref(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    11usize => {
                        SimplifiedType::Ptr(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    12usize => { SimplifiedType::Never }
                    13usize => {
                        SimplifiedType::Tuple(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    14usize => { SimplifiedType::MarkerTraitObject }
                    15usize => {
                        SimplifiedType::Trait(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    16usize => {
                        SimplifiedType::Closure(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    17usize => {
                        SimplifiedType::Coroutine(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    18usize => {
                        SimplifiedType::CoroutineWitness(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    19usize => {
                        SimplifiedType::Function(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    20usize => { SimplifiedType::UnsafeBinder }
                    21usize => { SimplifiedType::Placeholder }
                    22usize => { SimplifiedType::Error }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `SimplifiedType`, expected 0..23, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable_NoContext, const _: () =
    {
        impl<DefId, __CTX>
            ::rustc_data_structures::stable_hasher::HashStable<__CTX> for
            SimplifiedType<DefId> where
            DefId: ::rustc_data_structures::stable_hasher::HashStable<__CTX> {
            #[inline]
            fn hash_stable(&self, __hcx: &mut __CTX,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                ::std::mem::discriminant(self).hash_stable(__hcx, __hasher);
                match *self {
                    SimplifiedType::Bool => {}
                    SimplifiedType::Char => {}
                    SimplifiedType::Int(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                    SimplifiedType::Uint(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                    SimplifiedType::Float(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                    SimplifiedType::Adt(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                    SimplifiedType::Foreign(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                    SimplifiedType::Str => {}
                    SimplifiedType::Array => {}
                    SimplifiedType::Slice => {}
                    SimplifiedType::Ref(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                    SimplifiedType::Ptr(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                    SimplifiedType::Never => {}
                    SimplifiedType::Tuple(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                    SimplifiedType::MarkerTraitObject => {}
                    SimplifiedType::Trait(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                    SimplifiedType::Closure(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                    SimplifiedType::Coroutine(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                    SimplifiedType::CoroutineWitness(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                    SimplifiedType::Function(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                    SimplifiedType::UnsafeBinder => {}
                    SimplifiedType::Placeholder => {}
                    SimplifiedType::Error => {}
                }
            }
        }
    };HashStable_NoContext)
23)]
24pub enum SimplifiedType<DefId> {
25    Bool,
26    Char,
27    Int(ty::IntTy),
28    Uint(ty::UintTy),
29    Float(ty::FloatTy),
30    Adt(DefId),
31    Foreign(DefId),
32    Str,
33    Array,
34    Slice,
35    Ref(Mutability),
36    Ptr(Mutability),
37    Never,
38    Tuple(usize),
39    /// A trait object, all of whose components are markers
40    /// (e.g., `dyn Send + Sync`).
41    MarkerTraitObject,
42    Trait(DefId),
43    Closure(DefId),
44    Coroutine(DefId),
45    CoroutineWitness(DefId),
46    Function(usize),
47    UnsafeBinder,
48    Placeholder,
49    Error,
50}
51
52#[cfg(feature = "nightly")]
53impl<Hcx, DefId: HashStable<Hcx>> ToStableHashKey<Hcx> for SimplifiedType<DefId> {
54    type KeyType = Fingerprint;
55
56    #[inline]
57    fn to_stable_hash_key(&self, hcx: &mut Hcx) -> Fingerprint {
58        let mut hasher = StableHasher::new();
59        self.hash_stable(hcx, &mut hasher);
60        hasher.finish()
61    }
62}
63
64/// Generic parameters are pretty much just bound variables, e.g.
65/// the type of `fn foo<'a, T>(x: &'a T) -> u32 { ... }` can be thought of as
66/// `for<'a, T> fn(&'a T) -> u32`.
67///
68/// Typecheck of `foo` has to succeed for all possible generic arguments, so
69/// during typeck, we have to treat its generic parameters as if they
70/// were placeholders.
71///
72/// But when calling `foo` we only have to provide a specific generic argument.
73/// In that case the generic parameters are instantiated with inference variables.
74/// As we use `simplify_type` before that instantiation happens, we just treat
75/// generic parameters as if they were inference variables in that case.
76#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for TreatParams {
    #[inline]
    fn eq(&self, other: &TreatParams) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for TreatParams {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for TreatParams {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                TreatParams::InstantiateWithInfer => "InstantiateWithInfer",
                TreatParams::AsRigid => "AsRigid",
            })
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for TreatParams {
    #[inline]
    fn clone(&self) -> TreatParams { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for TreatParams { }Copy)]
77pub enum TreatParams {
78    /// Treat parameters as infer vars. This is the correct mode for caching
79    /// an impl's type for lookup.
80    InstantiateWithInfer,
81    /// Treat parameters as placeholders in the given environment. This is the
82    /// correct mode for *lookup*, as during candidate selection.
83    ///
84    /// This also treats projections with inference variables as infer vars
85    /// since they could be further normalized.
86    // FIXME(@lcnr): This treats aliases as rigid. This is only correct if the
87    // type has been structurally normalized. We should reflect this requirement
88    // in the variant name. It is currently incorrectly used in diagnostics.
89    AsRigid,
90}
91
92/// Tries to simplify a type by only returning the outermost injective¹ layer, if one exists.
93///
94/// **This function should only be used if you need to store or retrieve the type from some
95/// hashmap. If you want to quickly decide whether two types may unify, use the [DeepRejectCtxt]
96/// instead.**
97///
98/// The idea is to get something simple that we can use to quickly decide if two types could unify,
99/// for example during method lookup. If this function returns `Some(x)` it can only unify with
100/// types for which this method returns either `Some(x)` as well or `None`.
101///
102/// A special case here are parameters and projections, which are only injective
103/// if they are treated as placeholders.
104///
105/// For example when storing impls based on their simplified self type, we treat
106/// generic parameters as if they were inference variables. We must not simplify them here,
107/// as they can unify with any other type.
108///
109/// With projections we have to be even more careful, as treating them as placeholders
110/// is only correct if they are fully normalized.
111///
112/// ¹ meaning that if the outermost layers are different, then the whole types are also different.
113pub fn simplify_type<I: Interner>(
114    cx: I,
115    ty: I::Ty,
116    treat_params: TreatParams,
117) -> Option<SimplifiedType<I::DefId>> {
118    match ty.kind() {
119        ty::Bool => Some(SimplifiedType::Bool),
120        ty::Char => Some(SimplifiedType::Char),
121        ty::Int(int_type) => Some(SimplifiedType::Int(int_type)),
122        ty::Uint(uint_type) => Some(SimplifiedType::Uint(uint_type)),
123        ty::Float(float_type) => Some(SimplifiedType::Float(float_type)),
124        ty::Adt(def, _) => Some(SimplifiedType::Adt(def.def_id().into())),
125        ty::Str => Some(SimplifiedType::Str),
126        ty::Array(..) => Some(SimplifiedType::Array),
127        ty::Slice(..) => Some(SimplifiedType::Slice),
128        ty::Pat(ty, ..) => simplify_type(cx, ty, treat_params),
129        ty::RawPtr(_, mutbl) => Some(SimplifiedType::Ptr(mutbl)),
130        ty::Dynamic(trait_info, ..) => match trait_info.principal_def_id() {
131            Some(principal_def_id) if !cx.trait_is_auto(principal_def_id) => {
132                Some(SimplifiedType::Trait(principal_def_id.into()))
133            }
134            _ => Some(SimplifiedType::MarkerTraitObject),
135        },
136        ty::Ref(_, _, mutbl) => Some(SimplifiedType::Ref(mutbl)),
137        ty::FnDef(def_id, _) => Some(SimplifiedType::Closure(def_id.into())),
138        ty::Closure(def_id, _) => Some(SimplifiedType::Closure(def_id.into())),
139        ty::CoroutineClosure(def_id, _) => Some(SimplifiedType::Closure(def_id.into())),
140        ty::Coroutine(def_id, _) => Some(SimplifiedType::Coroutine(def_id.into())),
141        ty::CoroutineWitness(def_id, _) => Some(SimplifiedType::CoroutineWitness(def_id.into())),
142        ty::Never => Some(SimplifiedType::Never),
143        ty::Tuple(tys) => Some(SimplifiedType::Tuple(tys.len())),
144        ty::FnPtr(sig_tys, _hdr) => {
145            Some(SimplifiedType::Function(sig_tys.skip_binder().inputs().len()))
146        }
147        ty::UnsafeBinder(_) => Some(SimplifiedType::UnsafeBinder),
148        ty::Placeholder(..) => Some(SimplifiedType::Placeholder),
149        ty::Param(_) => match treat_params {
150            TreatParams::AsRigid => Some(SimplifiedType::Placeholder),
151            TreatParams::InstantiateWithInfer => None,
152        },
153        ty::Alias(..) => match treat_params {
154            // When treating `ty::Param` as a placeholder, projections also
155            // don't unify with anything else as long as they are fully normalized.
156            TreatParams::AsRigid
157                if !ty.has_non_region_infer() || cx.next_trait_solver_globally() =>
158            {
159                Some(SimplifiedType::Placeholder)
160            }
161            TreatParams::AsRigid | TreatParams::InstantiateWithInfer => None,
162        },
163        ty::Foreign(def_id) => Some(SimplifiedType::Foreign(def_id.into())),
164        ty::Error(_) => Some(SimplifiedType::Error),
165        ty::Bound(..) | ty::Infer(_) => None,
166    }
167}
168
169impl<DefId> SimplifiedType<DefId> {
170    pub fn def(self) -> Option<DefId> {
171        match self {
172            SimplifiedType::Adt(d)
173            | SimplifiedType::Foreign(d)
174            | SimplifiedType::Trait(d)
175            | SimplifiedType::Closure(d)
176            | SimplifiedType::Coroutine(d)
177            | SimplifiedType::CoroutineWitness(d) => Some(d),
178            _ => None,
179        }
180    }
181}
182
183/// Given generic arguments, could they be unified after
184/// replacing parameters with inference variables or placeholders.
185/// This behavior is toggled using the const generics.
186///
187/// We use this to quickly reject impl/wc candidates without needing
188/// to instantiate generic arguments/having to enter a probe.
189///
190/// We also use this function during coherence. For coherence the
191/// impls only have to overlap for some value, so we treat parameters
192/// on both sides like inference variables.
193#[derive(#[automatically_derived]
impl<I: ::core::fmt::Debug + Interner, const INSTANTIATE_LHS_WITH_INFER :
    bool, const INSTANTIATE_RHS_WITH_INFER : bool> ::core::fmt::Debug for
    DeepRejectCtxt<I, INSTANTIATE_LHS_WITH_INFER, INSTANTIATE_RHS_WITH_INFER>
    {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "DeepRejectCtxt", "_interner", &&self._interner)
    }
}Debug, #[automatically_derived]
impl<I: ::core::clone::Clone + Interner, const INSTANTIATE_LHS_WITH_INFER :
    bool, const INSTANTIATE_RHS_WITH_INFER : bool> ::core::clone::Clone for
    DeepRejectCtxt<I, INSTANTIATE_LHS_WITH_INFER, INSTANTIATE_RHS_WITH_INFER>
    {
    #[inline]
    fn clone(&self)
        ->
            DeepRejectCtxt<I, INSTANTIATE_LHS_WITH_INFER,
            INSTANTIATE_RHS_WITH_INFER> {
        DeepRejectCtxt {
            _interner: ::core::clone::Clone::clone(&self._interner),
        }
    }
}Clone, #[automatically_derived]
impl<I: ::core::marker::Copy + Interner, const INSTANTIATE_LHS_WITH_INFER :
    bool, const INSTANTIATE_RHS_WITH_INFER : bool> ::core::marker::Copy for
    DeepRejectCtxt<I, INSTANTIATE_LHS_WITH_INFER, INSTANTIATE_RHS_WITH_INFER>
    {
}Copy)]
194pub struct DeepRejectCtxt<
195    I: Interner,
196    const INSTANTIATE_LHS_WITH_INFER: bool,
197    const INSTANTIATE_RHS_WITH_INFER: bool,
198> {
199    _interner: PhantomData<I>,
200}
201
202impl<I: Interner> DeepRejectCtxt<I, false, false> {
203    /// Treat parameters in both the lhs and the rhs as rigid.
204    pub fn relate_rigid_rigid(_interner: I) -> DeepRejectCtxt<I, false, false> {
205        DeepRejectCtxt { _interner: PhantomData }
206    }
207}
208
209impl<I: Interner> DeepRejectCtxt<I, true, true> {
210    /// Treat parameters in both the lhs and the rhs as infer vars.
211    pub fn relate_infer_infer(_interner: I) -> DeepRejectCtxt<I, true, true> {
212        DeepRejectCtxt { _interner: PhantomData }
213    }
214}
215
216impl<I: Interner> DeepRejectCtxt<I, false, true> {
217    /// Treat parameters in the lhs as rigid, and in rhs as infer vars.
218    pub fn relate_rigid_infer(_interner: I) -> DeepRejectCtxt<I, false, true> {
219        DeepRejectCtxt { _interner: PhantomData }
220    }
221}
222
223impl<I: Interner, const INSTANTIATE_LHS_WITH_INFER: bool, const INSTANTIATE_RHS_WITH_INFER: bool>
224    DeepRejectCtxt<I, INSTANTIATE_LHS_WITH_INFER, INSTANTIATE_RHS_WITH_INFER>
225{
226    // Quite arbitrary. Large enough to only affect a very tiny amount of impls/crates
227    // and small enough to prevent hangs.
228    const STARTING_DEPTH: usize = 8;
229
230    pub fn args_may_unify(
231        self,
232        obligation_args: I::GenericArgs,
233        impl_args: I::GenericArgs,
234    ) -> bool {
235        self.args_may_unify_inner(obligation_args, impl_args, Self::STARTING_DEPTH)
236    }
237
238    pub fn types_may_unify(self, lhs: I::Ty, rhs: I::Ty) -> bool {
239        self.types_may_unify_inner(lhs, rhs, Self::STARTING_DEPTH)
240    }
241
242    pub fn types_may_unify_with_depth(self, lhs: I::Ty, rhs: I::Ty, depth_limit: usize) -> bool {
243        self.types_may_unify_inner(lhs, rhs, depth_limit)
244    }
245
246    fn args_may_unify_inner(
247        self,
248        obligation_args: I::GenericArgs,
249        impl_args: I::GenericArgs,
250        depth: usize,
251    ) -> bool {
252        // No need to decrement the depth here as this function is only
253        // recursively reachable via `types_may_unify_inner` which already
254        // increments the depth for us.
255        iter::zip(obligation_args.iter(), impl_args.iter()).all(|(obl, imp)| {
256            match (obl.kind(), imp.kind()) {
257                // We don't fast reject based on regions.
258                (ty::GenericArgKind::Lifetime(_), ty::GenericArgKind::Lifetime(_)) => true,
259                (ty::GenericArgKind::Type(obl), ty::GenericArgKind::Type(imp)) => {
260                    self.types_may_unify_inner(obl, imp, depth)
261                }
262                (ty::GenericArgKind::Const(obl), ty::GenericArgKind::Const(imp)) => {
263                    self.consts_may_unify_inner(obl, imp)
264                }
265                _ => {
    ::core::panicking::panic_fmt(format_args!("kind mismatch: {0:?} {1:?}",
            obl, imp));
}panic!("kind mismatch: {obl:?} {imp:?}"),
266            }
267        })
268    }
269
270    fn types_may_unify_inner(self, lhs: I::Ty, rhs: I::Ty, depth: usize) -> bool {
271        if lhs == rhs {
272            return true;
273        }
274
275        match rhs.kind() {
276            // Start by checking whether the `rhs` type may unify with
277            // pretty much everything. Just return `true` in that case.
278            ty::Param(_) => {
279                if INSTANTIATE_RHS_WITH_INFER {
280                    return true;
281                }
282            }
283            ty::Error(_) | ty::Alias(..) | ty::Bound(..) => return true,
284            ty::Infer(var) => return self.var_and_ty_may_unify(var, lhs),
285
286            // These types only unify with inference variables or their own
287            // variant.
288            ty::Bool
289            | ty::Char
290            | ty::Int(_)
291            | ty::Uint(_)
292            | ty::Float(_)
293            | ty::Adt(..)
294            | ty::Str
295            | ty::Array(..)
296            | ty::Slice(..)
297            | ty::RawPtr(..)
298            | ty::Dynamic(..)
299            | ty::Pat(..)
300            | ty::Ref(..)
301            | ty::Never
302            | ty::Tuple(..)
303            | ty::FnDef(..)
304            | ty::FnPtr(..)
305            | ty::Closure(..)
306            | ty::CoroutineClosure(..)
307            | ty::Coroutine(..)
308            | ty::CoroutineWitness(..)
309            | ty::Foreign(_)
310            | ty::Placeholder(_)
311            | ty::UnsafeBinder(_) => {}
312        };
313
314        // The type system needs to support exponentially large types
315        // as long as they are self-similar. While most other folders
316        // use caching to handle them, this folder exists purely as a
317        // perf optimization and is incredibly hot. In pretty much all
318        // uses checking the cache is slower than simply recursing, so
319        // we instead just add an arbitrary depth cutoff.
320        //
321        // We only decrement the depth here as the match on `rhs`
322        // does not recurse.
323        let Some(depth) = depth.checked_sub(1) else {
324            return true;
325        };
326
327        // For purely rigid types, use structural equivalence.
328        match lhs.kind() {
329            ty::Ref(_, lhs_ty, lhs_mutbl) => match rhs.kind() {
330                ty::Ref(_, rhs_ty, rhs_mutbl) => {
331                    lhs_mutbl == rhs_mutbl && self.types_may_unify_inner(lhs_ty, rhs_ty, depth)
332                }
333                _ => false,
334            },
335
336            ty::Adt(lhs_def, lhs_args) => match rhs.kind() {
337                ty::Adt(rhs_def, rhs_args) => {
338                    lhs_def == rhs_def && self.args_may_unify_inner(lhs_args, rhs_args, depth)
339                }
340                _ => false,
341            },
342
343            // Depending on the value of const generics, we either treat generic parameters
344            // like placeholders or like inference variables.
345            ty::Param(lhs) => {
346                INSTANTIATE_LHS_WITH_INFER
347                    || match rhs.kind() {
348                        ty::Param(rhs) => lhs == rhs,
349                        _ => false,
350                    }
351            }
352
353            // Placeholder types don't unify with anything on their own.
354            ty::Placeholder(lhs) => {
355                #[allow(non_exhaustive_omitted_patterns)] match rhs.kind() {
    ty::Placeholder(rhs) if lhs == rhs => true,
    _ => false,
}matches!(rhs.kind(), ty::Placeholder(rhs) if lhs == rhs)
356            }
357
358            ty::Infer(var) => self.var_and_ty_may_unify(var, rhs),
359
360            // As we're walking the whole type, it may encounter projections
361            // inside of binders and what not, so we're just going to assume that
362            // projections can unify with other stuff.
363            //
364            // Looking forward to lazy normalization this is the safer strategy anyways.
365            ty::Alias(..) => true,
366
367            ty::Int(_)
368            | ty::Uint(_)
369            | ty::Float(_)
370            | ty::Str
371            | ty::Bool
372            | ty::Char
373            | ty::Never
374            | ty::Foreign(_) => lhs == rhs,
375
376            ty::Tuple(lhs) => match rhs.kind() {
377                ty::Tuple(rhs) => {
378                    lhs.len() == rhs.len()
379                        && iter::zip(lhs.iter(), rhs.iter())
380                            .all(|(lhs, rhs)| self.types_may_unify_inner(lhs, rhs, depth))
381                }
382                _ => false,
383            },
384
385            ty::Array(lhs_ty, lhs_len) => match rhs.kind() {
386                ty::Array(rhs_ty, rhs_len) => {
387                    self.types_may_unify_inner(lhs_ty, rhs_ty, depth)
388                        && self.consts_may_unify_inner(lhs_len, rhs_len)
389                }
390                _ => false,
391            },
392
393            ty::RawPtr(lhs_ty, lhs_mutbl) => match rhs.kind() {
394                ty::RawPtr(rhs_ty, rhs_mutbl) => {
395                    lhs_mutbl == rhs_mutbl && self.types_may_unify_inner(lhs_ty, rhs_ty, depth)
396                }
397                _ => false,
398            },
399
400            ty::Slice(lhs_ty) => {
401                #[allow(non_exhaustive_omitted_patterns)] match rhs.kind() {
    ty::Slice(rhs_ty) if self.types_may_unify_inner(lhs_ty, rhs_ty, depth) =>
        true,
    _ => false,
}matches!(rhs.kind(), ty::Slice(rhs_ty) if self.types_may_unify_inner(lhs_ty, rhs_ty, depth))
402            }
403
404            ty::Dynamic(lhs_preds, ..) => {
405                // Ideally we would walk the existential predicates here or at least
406                // compare their length. But considering that the relevant `Relate` impl
407                // actually sorts and deduplicates these, that doesn't work.
408                #[allow(non_exhaustive_omitted_patterns)] match rhs.kind() {
    ty::Dynamic(rhs_preds, ..) if
        lhs_preds.principal_def_id() == rhs_preds.principal_def_id() => true,
    _ => false,
}matches!(rhs.kind(), ty::Dynamic(rhs_preds, ..) if
409                    lhs_preds.principal_def_id() == rhs_preds.principal_def_id()
410                )
411            }
412
413            ty::FnPtr(lhs_sig_tys, lhs_hdr) => match rhs.kind() {
414                ty::FnPtr(rhs_sig_tys, rhs_hdr) => {
415                    let lhs_sig_tys = lhs_sig_tys.skip_binder().inputs_and_output;
416                    let rhs_sig_tys = rhs_sig_tys.skip_binder().inputs_and_output;
417
418                    lhs_hdr == rhs_hdr
419                        && lhs_sig_tys.len() == rhs_sig_tys.len()
420                        && iter::zip(lhs_sig_tys.iter(), rhs_sig_tys.iter())
421                            .all(|(lhs, rhs)| self.types_may_unify_inner(lhs, rhs, depth))
422                }
423                _ => false,
424            },
425
426            ty::Bound(..) => true,
427
428            ty::FnDef(lhs_def_id, lhs_args) => match rhs.kind() {
429                ty::FnDef(rhs_def_id, rhs_args) => {
430                    lhs_def_id == rhs_def_id && self.args_may_unify_inner(lhs_args, rhs_args, depth)
431                }
432                _ => false,
433            },
434
435            ty::Closure(lhs_def_id, lhs_args) => match rhs.kind() {
436                ty::Closure(rhs_def_id, rhs_args) => {
437                    lhs_def_id == rhs_def_id && self.args_may_unify_inner(lhs_args, rhs_args, depth)
438                }
439                _ => false,
440            },
441
442            ty::CoroutineClosure(lhs_def_id, lhs_args) => match rhs.kind() {
443                ty::CoroutineClosure(rhs_def_id, rhs_args) => {
444                    lhs_def_id == rhs_def_id && self.args_may_unify_inner(lhs_args, rhs_args, depth)
445                }
446                _ => false,
447            },
448
449            ty::Coroutine(lhs_def_id, lhs_args) => match rhs.kind() {
450                ty::Coroutine(rhs_def_id, rhs_args) => {
451                    lhs_def_id == rhs_def_id && self.args_may_unify_inner(lhs_args, rhs_args, depth)
452                }
453                _ => false,
454            },
455
456            ty::CoroutineWitness(lhs_def_id, lhs_args) => match rhs.kind() {
457                ty::CoroutineWitness(rhs_def_id, rhs_args) => {
458                    lhs_def_id == rhs_def_id && self.args_may_unify_inner(lhs_args, rhs_args, depth)
459                }
460                _ => false,
461            },
462
463            ty::Pat(lhs_ty, _) => {
464                // FIXME(pattern_types): take pattern into account
465                #[allow(non_exhaustive_omitted_patterns)] match rhs.kind() {
    ty::Pat(rhs_ty, _) if self.types_may_unify_inner(lhs_ty, rhs_ty, depth) =>
        true,
    _ => false,
}matches!(rhs.kind(), ty::Pat(rhs_ty, _) if self.types_may_unify_inner(lhs_ty, rhs_ty, depth))
466            }
467
468            ty::UnsafeBinder(lhs_ty) => match rhs.kind() {
469                ty::UnsafeBinder(rhs_ty) => {
470                    self.types_may_unify(lhs_ty.skip_binder(), rhs_ty.skip_binder())
471                }
472                _ => false,
473            },
474
475            ty::Error(..) => true,
476        }
477    }
478
479    // Unlike `types_may_unify_inner`, this does not take a depth as
480    // we never recurse from this function.
481    fn consts_may_unify_inner(self, lhs: I::Const, rhs: I::Const) -> bool {
482        match rhs.kind() {
483            ty::ConstKind::Param(_) => {
484                if INSTANTIATE_RHS_WITH_INFER {
485                    return true;
486                }
487            }
488
489            ty::ConstKind::Expr(_)
490            | ty::ConstKind::Unevaluated(_)
491            | ty::ConstKind::Error(_)
492            | ty::ConstKind::Infer(_)
493            | ty::ConstKind::Bound(..) => {
494                return true;
495            }
496
497            ty::ConstKind::Value(..) | ty::ConstKind::Placeholder(_) => {}
498        };
499
500        match lhs.kind() {
501            ty::ConstKind::Value(lhs_val) => match rhs.kind() {
502                ty::ConstKind::Value(rhs_val) => lhs_val.valtree() == rhs_val.valtree(),
503                _ => false,
504            },
505
506            ty::ConstKind::Param(lhs) => {
507                INSTANTIATE_LHS_WITH_INFER
508                    || match rhs.kind() {
509                        ty::ConstKind::Param(rhs) => lhs == rhs,
510                        _ => false,
511                    }
512            }
513
514            // Placeholder consts don't unify with anything on their own
515            ty::ConstKind::Placeholder(lhs) => {
516                #[allow(non_exhaustive_omitted_patterns)] match rhs.kind() {
    ty::ConstKind::Placeholder(rhs) if lhs == rhs => true,
    _ => false,
}matches!(rhs.kind(), ty::ConstKind::Placeholder(rhs) if lhs == rhs)
517            }
518
519            // As we don't necessarily eagerly evaluate constants,
520            // they might unify with any value.
521            ty::ConstKind::Expr(_) | ty::ConstKind::Unevaluated(_) | ty::ConstKind::Error(_) => {
522                true
523            }
524
525            ty::ConstKind::Infer(_) | ty::ConstKind::Bound(..) => true,
526        }
527    }
528
529    fn var_and_ty_may_unify(self, var: ty::InferTy, ty: I::Ty) -> bool {
530        if !ty.is_known_rigid() {
531            return true;
532        }
533
534        match var {
535            ty::IntVar(_) => ty.is_integral(),
536            ty::FloatVar(_) => ty.is_floating_point(),
537            _ => true,
538        }
539    }
540}