Skip to main content

rustc_type_ir/sty/
mod.rs

1use std::fmt;
2
3use derive_where::derive_where;
4#[cfg(feature = "nightly")]
5use rustc_macros::{Decodable_NoContext, Encodable_NoContext, StableHash_NoContext};
6use rustc_type_ir_macros::{GenericTypeVisitable, Lift_Generic};
7use tracing::debug;
8
9use crate::inherent::*;
10use crate::intern::Interned;
11use crate::relate::{Relate, RelateResult, TypeRelation};
12use crate::{
13    BoundRegion, BoundRegionKind, BoundVar, BoundVarIndexKind, DebruijnIndex, FallibleTypeFolder,
14    Flags, Interner, PlaceholderRegion, RegionKind, RegionVid, TypeFlags, TypeFoldable, TypeFolder,
15    TypeVisitable, TypeVisitor,
16};
17
18/// Use this rather than `RegionKind`, whenever possible.
19#[automatically_derived]
impl<I: Interner> ::core::clone::Clone for Region<I> where I: Interner {
    #[inline]
    fn clone(&self) -> Self { *self }
}
#[automatically_derived]
impl<I: Interner> ::core::marker::Copy for Region<I> where I: Interner { }
#[automatically_derived]
impl<I: Interner> ::core::cmp::PartialEq for Region<I> where I: Interner {
    #[inline]
    fn eq(&self, __other: &Self) -> ::core::primitive::bool {
        match (self, __other) {
            (Region(ref __field_0), Region(ref __other_field_0)) =>
                true &&
                    ::core::cmp::PartialEq::eq(__field_0, __other_field_0),
        }
    }
}
const _: () =
    {
        trait DeriveWhereAssertEq {
            fn assert(&self);
        }
        impl<I: Interner> DeriveWhereAssertEq for Region<I> where I: Interner
            {
            fn assert(&self) {
                struct __AssertEq<__T: ::core::cmp::Eq +
                    ?::core::marker::Sized>(::core::marker::PhantomData<__T>);
                let _: __AssertEq<I::InternedRegionKind>;
            }
        }
    };
#[automatically_derived]
impl<I: Interner> ::core::cmp::Eq for Region<I> where I: Interner { }
#[automatically_derived]
impl<I: Interner> ::core::hash::Hash for Region<I> where I: Interner {
    fn hash<__H: ::core::hash::Hasher>(&self, __state: &mut __H) {
        match self {
            Region(ref __field_0) => {
                ::core::hash::Hash::hash(__field_0, __state);
            }
        }
    }
}#[derive_where(Clone, Copy, PartialEq, Eq, Hash; I: Interner)]
20#[cfg_attr(feature = "nightly", derive(const _: () =
    {
        impl<I: Interner> ::rustc_data_structures::stable_hash::StableHash for
            Region<I> where
            I::InternedRegionKind: ::rustc_data_structures::stable_hash::StableHash
            {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    Region(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash_NoContext))]
21#[cfg_attr(feature = "nightly", rustc_pass_by_value)]
22#[derive(const _: () =
    {
        unsafe impl<I: Interner, __V>
            ::rustc_type_ir::GenericTypeVisitable<__V> for Region<I> where
            I::InternedRegionKind: ::rustc_type_ir::GenericTypeVisitable<__V>
            {
            fn generic_visit_with(&self, __visitor: &mut __V) {
                match *self {
                    Region(ref __binding_0) => {
                        {
                            ::rustc_type_ir::GenericTypeVisitable::<__V>::generic_visit_with(__binding_0,
                                __visitor);
                        }
                    }
                }
            }
        }
    };GenericTypeVisitable, const _: () =
    {
        impl<I: Interner, J> ::rustc_type_ir::lift::Lift<J> for Region<I>
            where J: Interner, I: ::rustc_type_ir::LiftInto<J> {
            type Lifted = Region<J>;
            fn lift_to_interner(self, interner: J) -> Self::Lifted {
                match self {
                    Region(__binding_0) => {
                        Region(__binding_0.lift_to_interner(interner))
                    }
                }
            }
        }
    };Lift_Generic)]
23pub struct Region<I: Interner>(pub I::InternedRegionKind);
24
25// These are only the `inherent` trait methods that have been ported across
26impl<I: Interner> Region<I> {
27    #[inline]
28    pub fn new_var(interner: I, v: RegionVid) -> Self {
29        interner.intern_re_var(v)
30    }
31
32    pub fn get_name(self, interner: I) -> Option<I::Symbol> {
33        match self.kind() {
34            RegionKind::ReEarlyParam(ebr) => ebr.get_name(interner),
35            RegionKind::ReBound(_, br) => br.kind.get_name(interner),
36            RegionKind::ReLateParam(fr) => fr.kind.get_name(interner),
37            RegionKind::ReStatic => Some(I::Symbol::KW_STATIC_LIFETIME),
38            RegionKind::RePlaceholder(placeholder) => placeholder.bound.kind.get_name(interner),
39            _ => None,
40        }
41    }
42
43    pub fn get_name_or_anon(self, interner: I) -> I::Symbol {
44        match self.get_name(interner) {
45            Some(name) => name,
46            None => I::Symbol::SYM_ANON,
47        }
48    }
49
50    /// Given some item `binding_item`, check if this region is a generic parameter introduced by it
51    /// or one of the parent generics. Returns the `DefId` of the parameter definition if so.
52    pub fn opt_param_def_id(self, interner: I, binding_item: I::DefId) -> Option<I::DefId> {
53        match self.kind() {
54            RegionKind::ReEarlyParam(ebr) => {
55                Some(interner.generics_of(binding_item).param_region_def_id(interner, ebr))
56            }
57            RegionKind::ReLateParam(param) => param.kind.get_def_id(),
58            _ => None,
59        }
60    }
61
62    /// Is this region named by the user?
63    pub fn is_named(self, interner: I) -> bool {
64        match self.kind() {
65            RegionKind::ReEarlyParam(ebr) => ebr.is_named(interner),
66            RegionKind::ReBound(_, br) => br.kind.is_named(interner),
67            RegionKind::ReLateParam(fr) => fr.kind.is_named(interner),
68            RegionKind::ReStatic => true,
69            RegionKind::ReVar(..) => false,
70            RegionKind::RePlaceholder(placeholder) => placeholder.bound.kind.is_named(interner),
71            RegionKind::ReErased => false,
72            RegionKind::ReError(_) => false,
73        }
74    }
75
76    /// Constructs a `RegionKind::ReError` region and registers a delayed bug to ensure it gets
77    /// used.
78    #[track_caller]
79    pub fn new_error_misc(interner: I) -> Self {
80        Self::new_error_with_message(
81            interner,
82            I::Span::dummy(),
83            "RegionKind::ReError constructed but no error reported",
84        )
85    }
86
87    /// Constructs a `RegionKind::ReError` region and registers a delayed bug with the given `msg`
88    /// to ensure it gets used.
89    #[track_caller]
90    pub fn new_error_with_message(interner: I, span: I::Span, msg: impl ToString) -> Self {
91        let reported = interner.span_delayed_bug(span, msg);
92        Self::new_error(interner, reported)
93    }
94
95    #[inline]
96    pub fn new_late_param(interner: I, scope: I::DefId, kind: I::LateParamRegionKind) -> Self {
97        interner.intern_region(RegionKind::ReLateParam(LateParamRegion { scope, kind }))
98    }
99
100    #[inline]
101    pub fn new_early_param(interner: I, early_bound_region: I::EarlyParamRegion) -> Self {
102        interner.intern_region(RegionKind::ReEarlyParam(early_bound_region))
103    }
104
105    /// Constructs a `RegionKind::ReError` region.
106    #[track_caller]
107    pub fn new_error(interner: I, guar: I::ErrorGuaranteed) -> Self {
108        interner.intern_region(RegionKind::ReError(guar))
109    }
110
111    #[inline]
112    pub fn new_bound(interner: I, debruijn: DebruijnIndex, bound_region: BoundRegion<I>) -> Self {
113        interner.intern_bound_region(debruijn, bound_region)
114    }
115
116    #[inline]
117    pub fn new_anon_bound(interner: I, debruijn: DebruijnIndex, var: BoundVar) -> Self {
118        Self::new_bound(interner, debruijn, BoundRegion { var, kind: BoundRegionKind::Anon })
119    }
120
121    #[inline]
122    pub fn new_canonical_bound(interner: I, var: BoundVar) -> Self {
123        interner.intern_canonical_bound(var)
124    }
125
126    #[inline]
127    pub fn new_placeholder(interner: I, placeholder: PlaceholderRegion<I>) -> Self {
128        interner.intern_region(RegionKind::RePlaceholder(placeholder))
129    }
130
131    #[inline]
132    pub fn new_static(interner: I) -> Self {
133        interner.get_re_static_lifetime()
134    }
135
136    #[inline]
137    pub fn is_bound(self) -> bool {
138        #[allow(non_exhaustive_omitted_patterns)] match self.0.get() {
    RegionKind::ReBound(..) => true,
    _ => false,
}matches!(self.0.get(), RegionKind::ReBound(..))
139    }
140
141    #[inline]
142    pub fn is_error(self) -> bool {
143        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    RegionKind::ReError(_) => true,
    _ => false,
}matches!(self.kind(), RegionKind::ReError(_))
144    }
145
146    #[inline]
147    pub fn is_static(self) -> bool {
148        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    RegionKind::ReStatic => true,
    _ => false,
}matches!(self.kind(), RegionKind::ReStatic)
149    }
150
151    #[inline]
152    pub fn is_erased(self) -> bool {
153        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    RegionKind::ReErased => true,
    _ => false,
}matches!(self.kind(), RegionKind::ReErased)
154    }
155
156    #[inline]
157    pub fn is_placeholder(self) -> bool {
158        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    RegionKind::RePlaceholder(..) => true,
    _ => false,
}matches!(self.kind(), RegionKind::RePlaceholder(..))
159    }
160
161    /// True for free regions other than `'static`.
162    pub fn is_param(self) -> bool {
163        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    RegionKind::ReEarlyParam(_) | RegionKind::ReLateParam(_) => true,
    _ => false,
}matches!(self.kind(), RegionKind::ReEarlyParam(_) | RegionKind::ReLateParam(_))
164    }
165
166    /// True for free region in the current context.
167    ///
168    /// This is the case for `'static` and param regions.
169    pub fn is_free(self) -> bool {
170        match self.kind() {
171            RegionKind::ReStatic | RegionKind::ReEarlyParam(..) | RegionKind::ReLateParam(..) => {
172                true
173            }
174            RegionKind::ReVar(..)
175            | RegionKind::RePlaceholder(..)
176            | RegionKind::ReBound(..)
177            | RegionKind::ReErased
178            | RegionKind::ReError(..) => false,
179        }
180    }
181
182    pub fn is_var(self) -> bool {
183        #[allow(non_exhaustive_omitted_patterns)] match self.kind() {
    RegionKind::ReVar(_) => true,
    _ => false,
}matches!(self.kind(), RegionKind::ReVar(_))
184    }
185
186    pub fn as_var(self) -> RegionVid {
187        match self.kind() {
188            RegionKind::ReVar(vid) => vid,
189            _ => {
    ::core::panicking::panic_fmt(format_args!("expected region {0:?} to be of kind ReVar",
            self));
}panic!("expected region {:?} to be of kind ReVar", self),
190        }
191    }
192
193    // FIXME this should be made private and instead accessed via the
194    // trait Flags
195    #[inline]
196    pub fn type_flags(self) -> TypeFlags {
197        let mut flags = TypeFlags::empty();
198
199        match self.0.get() {
200            RegionKind::ReVar(..) => {
201                flags = flags | TypeFlags::HAS_FREE_REGIONS;
202                flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
203                flags = flags | TypeFlags::HAS_RE_INFER;
204            }
205            RegionKind::RePlaceholder(..) => {
206                flags = flags | TypeFlags::HAS_FREE_REGIONS;
207                flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
208                flags = flags | TypeFlags::HAS_RE_PLACEHOLDER;
209            }
210            RegionKind::ReEarlyParam(..) => {
211                flags = flags | TypeFlags::HAS_FREE_REGIONS;
212                flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
213                flags = flags | TypeFlags::HAS_RE_PARAM;
214            }
215            RegionKind::ReLateParam { .. } => {
216                flags = flags | TypeFlags::HAS_FREE_REGIONS;
217                flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
218            }
219            RegionKind::ReStatic => {
220                flags = flags | TypeFlags::HAS_FREE_REGIONS;
221            }
222            RegionKind::ReBound(BoundVarIndexKind::Canonical, _) => {
223                flags = flags | TypeFlags::HAS_RE_BOUND;
224                flags = flags | TypeFlags::HAS_CANONICAL_BOUND;
225            }
226            RegionKind::ReBound(BoundVarIndexKind::Bound(..), _) => {
227                flags = flags | TypeFlags::HAS_RE_BOUND;
228            }
229            RegionKind::ReErased => {
230                flags = flags | TypeFlags::HAS_RE_ERASED;
231            }
232            RegionKind::ReError(_) => {
233                flags = flags | TypeFlags::HAS_FREE_REGIONS;
234                flags = flags | TypeFlags::HAS_RE_ERROR;
235            }
236        }
237        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_type_ir/src/sty/mod.rs:237",
                        "rustc_type_ir::sty", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_type_ir/src/sty/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(237u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_type_ir::sty"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("type_flags({0:?}) = {1:?}",
                                                    self, flags) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("type_flags({:?}) = {:?}", self, flags);
238
239        flags
240    }
241
242    #[inline]
243    pub fn kind(self) -> RegionKind<I> {
244        self.0.get()
245    }
246
247    #[inline]
248    pub fn bound_at_or_above_binder(self, index: DebruijnIndex) -> bool {
249        match self.kind() {
250            RegionKind::ReBound(BoundVarIndexKind::Bound(debruijn), _) => debruijn >= index,
251            _ => false,
252        }
253    }
254}
255
256impl<I: Interner> Flags for Region<I> {
257    fn flags(&self) -> TypeFlags {
258        self.type_flags()
259    }
260
261    fn outer_exclusive_binder(&self) -> DebruijnIndex {
262        match self.kind() {
263            RegionKind::ReBound(BoundVarIndexKind::Bound(debruijn), _) => debruijn.shifted_in(1),
264            _ => crate::INNERMOST,
265        }
266    }
267}
268
269impl<I: Interner> IntoKind for Region<I> {
270    type Kind = RegionKind<I>;
271
272    fn kind(self) -> Self::Kind {
273        self.0.get()
274    }
275}
276
277impl<I: Interner> Relate<I> for Region<I> {
278    fn relate<R: TypeRelation<I>>(
279        relation: &mut R,
280        a: Region<I>,
281        b: Region<I>,
282    ) -> RelateResult<I, Region<I>> {
283        relation.regions(a, b)
284    }
285}
286
287impl<I: Interner> fmt::Debug for Region<I> {
288    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289        f.write_fmt(format_args!("{0:?}", self.kind()))write!(f, "{:?}", self.kind())
290    }
291}
292
293impl<I: Interner> TypeVisitable<I> for Region<I> {
294    fn visit_with<V: TypeVisitor<I>>(&self, visitor: &mut V) -> V::Result {
295        visitor.visit_region(*self)
296    }
297}
298
299impl<I: Interner> TypeFoldable<I> for Region<I> {
300    fn try_fold_with<F: FallibleTypeFolder<I>>(self, folder: &mut F) -> Result<Self, F::Error> {
301        folder.try_fold_region(self)
302    }
303
304    fn fold_with<F: TypeFolder<I>>(self, folder: &mut F) -> Self {
305        folder.fold_region(self)
306    }
307}
308
309#[automatically_derived]
impl<I: Interner> ::core::clone::Clone for LateParamRegion<I> where
    I: Interner {
    #[inline]
    fn clone(&self) -> Self { *self }
}
#[automatically_derived]
impl<I: Interner> ::core::marker::Copy for LateParamRegion<I> where
    I: Interner {
}
#[automatically_derived]
impl<I: Interner> ::core::cmp::PartialEq for LateParamRegion<I> where
    I: Interner {
    #[inline]
    fn eq(&self, __other: &Self) -> ::core::primitive::bool {
        match (self, __other) {
            (LateParamRegion {
                scope: ref __field_scope, kind: ref __field_kind },
                LateParamRegion {
                scope: ref __other_field_scope, kind: ref __other_field_kind
                }) =>
                true &&
                        ::core::cmp::PartialEq::eq(__field_scope,
                            __other_field_scope) &&
                    ::core::cmp::PartialEq::eq(__field_kind,
                        __other_field_kind),
        }
    }
}
const _: () =
    {
        trait DeriveWhereAssertEq {
            fn assert(&self);
        }
        impl<I: Interner> DeriveWhereAssertEq for LateParamRegion<I> where
            I: Interner {
            fn assert(&self) {
                struct __AssertEq<__T: ::core::cmp::Eq +
                    ?::core::marker::Sized>(::core::marker::PhantomData<__T>);
                let _: __AssertEq<I::DefId>;
                let _: __AssertEq<I::LateParamRegionKind>;
            }
        }
    };
#[automatically_derived]
impl<I: Interner> ::core::cmp::Eq for LateParamRegion<I> where I: Interner { }
#[automatically_derived]
impl<I: Interner> ::core::hash::Hash for LateParamRegion<I> where I: Interner
    {
    fn hash<__H: ::core::hash::Hasher>(&self, __state: &mut __H) {
        match self {
            LateParamRegion { scope: ref __field_scope, kind: ref __field_kind
                } => {
                ::core::hash::Hash::hash(__field_scope, __state);
                ::core::hash::Hash::hash(__field_kind, __state);
            }
        }
    }
}#[derive_where(Clone, Copy, PartialEq, Eq, Hash; I: Interner)]
310#[cfg_attr(
311    feature = "nightly",
312    derive(const _: () =
    {
        impl<I: Interner, __E: ::rustc_serialize::Encoder>
            ::rustc_serialize::Encodable<__E> for LateParamRegion<I> where
            I::DefId: ::rustc_serialize::Encodable<__E>,
            I::LateParamRegionKind: ::rustc_serialize::Encodable<__E> {
            fn encode(&self, __encoder: &mut __E) {
                let LateParamRegion {
                        scope: ref __binding_0, kind: ref __binding_1 } = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                    __encoder);
            }
        }
    };Encodable_NoContext, const _: () =
    {
        impl<I: Interner, __D: ::rustc_serialize::Decoder>
            ::rustc_serialize::Decodable<__D> for LateParamRegion<I> where
            I::DefId: ::rustc_serialize::Decodable<__D>,
            I::LateParamRegionKind: ::rustc_serialize::Decodable<__D> {
            fn decode(__decoder: &mut __D) -> Self {
                LateParamRegion {
                    scope: ::rustc_serialize::Decodable::decode(__decoder),
                    kind: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable_NoContext, const _: () =
    {
        impl<I: Interner> ::rustc_data_structures::stable_hash::StableHash for
            LateParamRegion<I> where
            I::DefId: ::rustc_data_structures::stable_hash::StableHash,
            I::LateParamRegionKind: ::rustc_data_structures::stable_hash::StableHash
            {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    LateParamRegion {
                        scope: ref __binding_0, kind: ref __binding_1 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash_NoContext)
313)]
314/// The parameter representation of late-bound function parameters, "some region
315/// at least as big as the scope `fr.scope`".
316///
317/// Similar to a placeholder region as we create `LateParam` regions when entering a binder
318/// except they are always in the root universe and instead of using a boundvar to distinguish
319/// between others we use the `DefId` of the parameter. For this reason the `bound_region` field
320/// should basically always be `BoundRegionKind::Named` as otherwise there is no way of telling
321/// different parameters apart.
322pub struct LateParamRegion<I: Interner> {
323    pub scope: I::DefId,
324    pub kind: I::LateParamRegionKind,
325}
326
327impl<I: Interner> fmt::Debug for LateParamRegion<I> {
328    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
329        f.write_fmt(format_args!("ReLateParam({0:?}, {1:?})", self.scope, self.kind))write!(f, "ReLateParam({:?}, {:?})", self.scope, self.kind)
330    }
331}