Skip to main content

rustc_hir_id/
lib.rs

1//! Library containing Id types from `rustc_hir`, split out so crates can use it without depending
2//! on all of `rustc_hir` (which is large and depends on other large things like `rustc_target`).
3#![allow(internal_features)]
4#![feature(negative_impls)]
5#![feature(rustc_attrs)]
6
7pub mod def_path_hash_map;
8pub mod definitions;
9
10#[cfg(test)]
11mod tests;
12
13use std::fmt::{self, Debug};
14
15use rustc_data_structures::stable_hash::{
16    StableHash, StableHashCtxt, StableHasher, StableOrd, ToStableHashKey,
17};
18use rustc_macros::{Decodable, Encodable, StableHash};
19use rustc_serialize::ContextOrd;
20use rustc_span::def_id::{CRATE_DEF_ID, DefId, DefIndex, DefPathHash, LocalDefId, LocalModId};
21
22#[derive(#[automatically_derived]impl ::core::marker::Copy for OwnerId { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for OwnerId {
}
#[automatically_derived]impl ::core::clone::Clone for OwnerId {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<LocalDefId>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for OwnerId {
}
#[automatically_derived]impl ::core::cmp::PartialEq for OwnerId {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.def_id == other.def_id }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for OwnerId {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<LocalDefId>;
    }
}Eq, #[automatically_derived]impl ::core::hash::Hash for OwnerId {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.def_id, state)
    }
}Hash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for OwnerId {
            fn encode(&self, __encoder: &mut __E) {
                let OwnerId { def_id: ref __binding_0 } = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for OwnerId {
            fn decode(__decoder: &mut __D) -> Self {
                OwnerId {
                    def_id: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable)]
23pub struct OwnerId {
24    pub def_id: LocalDefId,
25}
26
27impl Debug for OwnerId {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        // Example: DefId(0:1 ~ aa[7697]::{use#0})
30        Debug::fmt(&self.def_id, f)
31    }
32}
33
34impl From<OwnerId> for HirId {
35    fn from(owner: OwnerId) -> HirId {
36        HirId { owner, local_id: ItemLocalId::ZERO }
37    }
38}
39
40impl From<OwnerId> for DefId {
41    fn from(value: OwnerId) -> Self {
42        value.to_def_id()
43    }
44}
45
46impl From<LocalModId> for OwnerId {
47    fn from(value: LocalModId) -> Self {
48        OwnerId { def_id: value.to_local_def_id() }
49    }
50}
51
52impl OwnerId {
53    #[inline]
54    pub fn to_def_id(self) -> DefId {
55        self.def_id.to_def_id()
56    }
57}
58
59impl rustc_index::Idx for OwnerId {
60    #[inline]
61    fn new(idx: usize) -> Self {
62        OwnerId { def_id: LocalDefId { local_def_index: DefIndex::from_usize(idx) } }
63    }
64
65    #[inline]
66    fn index(self) -> usize {
67        self.def_id.local_def_index.as_usize()
68    }
69}
70
71impl StableHash for OwnerId {
72    #[inline]
73    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
74        self.to_stable_hash_key(hcx).stable_hash(hcx, hasher);
75    }
76}
77
78impl ToStableHashKey for OwnerId {
79    type KeyType = DefPathHash;
80
81    #[inline]
82    fn to_stable_hash_key<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx) -> DefPathHash {
83        self.to_def_id().to_stable_hash_key(hcx)
84    }
85}
86
87/// Uniquely identifies a node in the HIR of the current crate. It is
88/// composed of the `owner`, which is the `LocalDefId` of the directly enclosing
89/// `hir::Item`, `hir::TraitItem`, or `hir::ImplItem` (i.e., the closest "item-like"),
90/// and the `local_id` which is unique within the given owner.
91///
92/// This two-level structure makes for more stable values: One can move an item
93/// around within the source code, or add or remove stuff before it, without
94/// the `local_id` part of the `HirId` changing, which is a very useful property in
95/// incremental compilation where we have to persist things through changes to
96/// the code base.
97#[derive(#[automatically_derived]impl ::core::marker::Copy for HirId { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for HirId {
}
#[automatically_derived]impl ::core::clone::Clone for HirId {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<OwnerId>;
        let _: ::core::clone::AssertParamIsClone<ItemLocalId>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for HirId { }
#[automatically_derived]impl ::core::cmp::PartialEq for HirId {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.owner == other.owner && self.local_id == other.local_id
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for HirId {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<OwnerId>;
        let _: ::core::cmp::AssertParamIsEq<ItemLocalId>;
    }
}Eq, #[automatically_derived]impl ::core::hash::Hash for HirId {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.owner, state);
        ::core::hash::Hash::hash(&self.local_id, state)
    }
}Hash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for HirId {
            fn encode(&self, __encoder: &mut __E) {
                let HirId { owner: ref __binding_0, local_id: ref __binding_1
                        } = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                    __encoder);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for HirId {
            fn decode(__decoder: &mut __D) -> Self {
                HirId {
                    owner: ::rustc_serialize::Decodable::decode(__decoder),
                    local_id: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for HirId {
            #[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 {
                    HirId { owner: ref __binding_0, local_id: ref __binding_1 }
                        => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
98#[rustc_pass_by_value]
99pub struct HirId {
100    pub owner: OwnerId,
101    pub local_id: ItemLocalId,
102}
103
104// To ensure correctness of incremental compilation,
105// `HirId` must not implement `Ord` or `PartialOrd`.
106// See https://github.com/rust-lang/rust/issues/90317.
107impl !Ord for HirId {}
108impl !PartialOrd for HirId {}
109
110impl Debug for HirId {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        // Example: HirId(DefId(0:1 ~ aa[7697]::{use#0}).10)
113        // Don't use debug_tuple to always keep this on one line.
114        f.write_fmt(format_args!("HirId({0:?}.{1:?})", self.owner, self.local_id))write!(f, "HirId({:?}.{:?})", self.owner, self.local_id)
115    }
116}
117
118impl HirId {
119    /// Signal local id which should never be used.
120    pub const INVALID: HirId =
121        HirId { owner: OwnerId { def_id: CRATE_DEF_ID }, local_id: ItemLocalId::INVALID };
122
123    #[inline]
124    pub fn expect_owner(self) -> OwnerId {
125        {
    match (&self.local_id.index(), &0) {
        (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);
            }
        }
    }
};assert_eq!(self.local_id.index(), 0);
126        self.owner
127    }
128
129    #[inline]
130    pub fn as_owner(self) -> Option<OwnerId> {
131        if self.local_id.index() == 0 { Some(self.owner) } else { None }
132    }
133
134    #[inline]
135    pub fn is_owner(self) -> bool {
136        self.local_id.index() == 0
137    }
138
139    #[inline]
140    pub fn make_owner(owner: LocalDefId) -> Self {
141        Self { owner: OwnerId { def_id: owner }, local_id: ItemLocalId::ZERO }
142    }
143}
144
145impl fmt::Display for HirId {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        f.write_fmt(format_args!("{0:?}", self))write!(f, "{self:?}")
148    }
149}
150
151impl From<LocalModId> for HirId {
152    fn from(id: LocalModId) -> Self {
153        HirId::make_owner(id.to_local_def_id())
154    }
155}
156
157pub type HirIdMap<T> = ::rustc_data_structures::fx::FxIndexMap<HirId, T>;
pub type HirIdSet = ::rustc_data_structures::fx::FxIndexSet<HirId>;
pub type HirIdMapEntry<'a, T> =
    ::rustc_data_structures::fx::IndexEntry<'a, HirId, T>;rustc_data_structures::define_stable_id_collections!(HirIdMap, HirIdSet, HirIdMapEntry, HirId);
158pub type ItemLocalMap<T> =
    ::rustc_data_structures::unord::UnordMap<ItemLocalId, T>;
pub type ItemLocalSet = ::rustc_data_structures::unord::UnordSet<ItemLocalId>;
pub type ItemLocalMapEntry<'a, T> =
    ::rustc_data_structures::fx::StdEntry<'a, ItemLocalId, T>;rustc_data_structures::define_id_collections!(
159    ItemLocalMap,
160    ItemLocalSet,
161    ItemLocalMapEntry,
162    ItemLocalId
163);
164
165#[automatically_derived]impl ::core::marker::Copy for ItemLocalId { }
impl ItemLocalId {
    #[doc = r" Maximum value the index can take, as a `u32`."]
    pub const MAX_AS_U32: u32 = 0xFFFF_FF00;
    #[doc = r" Maximum value the index can take."]
    pub const MAX: Self = Self::from_u32(0xFFFF_FF00);
    #[doc = r" Zero value of the index."]
    pub const ZERO: Self = Self::from_u32(0);
    #[doc = r" Creates a new index from a given `usize`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_usize(value: usize) -> Self {
        if !(value <= (0xFFFF_FF00 as usize)) {
            ::core::panicking::panic("assertion failed: value <= (0xFFFF_FF00 as usize)")
        };
        unsafe { Self::from_u32_unchecked(value as u32) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_u32(value: u32) -> Self {
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u16`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_u16(value: u16) -> Self {
        let value = value as u32;
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc =
    r" The provided value must be less than or equal to the maximum value for the newtype."]
    #[doc =
    r" Providing a value outside this range is undefined due to layout restrictions."]
    #[doc = r""]
    #[doc = r" Prefer using `from_u32`."]
    #[inline]
    pub const unsafe fn from_u32_unchecked(value: u32) -> Self {
        Self {
            private_use_as_methods_instead: unsafe {
                std::mem::transmute(value)
            },
        }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    pub const fn index(self) -> usize { self.as_usize() }
    #[doc = r" Extracts the value of this index as a `u32`."]
    #[inline]
    pub const fn as_u32(self) -> u32 {
        unsafe { std::mem::transmute(self.private_use_as_methods_instead) }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    pub const fn as_usize(self) -> usize { self.as_u32() as usize }
}
impl std::ops::Add<usize> for ItemLocalId {
    type Output = Self;
    #[inline]
    fn add(self, other: usize) -> Self {
        Self::from_usize(self.index() + other)
    }
}
impl std::ops::AddAssign<usize> for ItemLocalId {
    #[inline]
    fn add_assign(&mut self, other: usize) { *self = *self + other; }
}
impl rustc_index::Idx for ItemLocalId {
    #[inline]
    fn new(value: usize) -> Self { Self::from_usize(value) }
    #[inline]
    fn index(self) -> usize { self.as_usize() }
}
impl ::std::iter::Step for ItemLocalId {
    #[inline]
    fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
        <usize as
                ::std::iter::Step>::steps_between(&Self::index(*start),
            &Self::index(*end))
    }
    #[inline]
    fn forward_checked(start: Self, u: usize) -> Option<Self> {
        Self::index(start).checked_add(u).map(Self::from_usize)
    }
    #[inline]
    fn backward_checked(start: Self, u: usize) -> Option<Self> {
        Self::index(start).checked_sub(u).map(Self::from_usize)
    }
    #[inline]
    fn forward_overflowing(start: Self, u: usize) -> (Self, bool) {
        let (s, o) = Self::index(start).overflowing_add(u);
        (Self::from_usize(s), o)
    }
    #[inline]
    fn backward_overflowing(start: Self, u: usize) -> (Self, bool) {
        let (s, o) = Self::index(start).overflowing_sub(u);
        (Self::from_usize(s), o)
    }
}
impl ::std::cmp::Ord for ItemLocalId {
    #[inline]
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.as_u32().cmp(&other.as_u32())
    }
}
impl ::std::cmp::PartialOrd for ItemLocalId {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl ::rustc_data_structures::stable_hash::StableHash for ItemLocalId {
    fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
        hcx: &mut __Hcx,
        hasher: &mut ::rustc_data_structures::stable_hash::StableHasher) {
        self.as_u32().stable_hash(hcx, hasher)
    }
}
impl From<ItemLocalId> for u32 {
    #[inline]
    fn from(v: ItemLocalId) -> u32 { v.as_u32() }
}
impl From<ItemLocalId> for usize {
    #[inline]
    fn from(v: ItemLocalId) -> usize { v.as_usize() }
}
impl From<usize> for ItemLocalId {
    #[inline]
    fn from(value: usize) -> Self { Self::from_usize(value) }
}
impl From<u32> for ItemLocalId {
    #[inline]
    fn from(value: u32) -> Self { Self::from_u32(value) }
}
impl ::std::cmp::Eq for ItemLocalId {}
impl ::std::cmp::PartialEq for ItemLocalId {
    fn eq(&self, other: &Self) -> bool { self.as_u32().eq(&other.as_u32()) }
}
impl ::std::marker::StructuralPartialEq for ItemLocalId {}
impl ::std::hash::Hash for ItemLocalId {
    fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
        self.as_u32().hash(state)
    }
}
impl<D: ::rustc_serialize::Decoder> ::rustc_serialize::Decodable<D> for
    ItemLocalId {
    fn decode(d: &mut D) -> Self { Self::from_u32(d.read_u32()) }
}
impl<E: ::rustc_serialize::Encoder> ::rustc_serialize::Encodable<E> for
    ItemLocalId {
    fn encode(&self, e: &mut E) { e.emit_u32(self.as_u32()); }
}
impl ::std::fmt::Debug for ItemLocalId {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        fmt.write_fmt(format_args!("{0}", self.as_u32()))
    }
}rustc_index::newtype_index! {
166    /// An `ItemLocalId` uniquely identifies something within a given "item-like";
167    /// that is, within a `hir::Item`, `hir::TraitItem`, or `hir::ImplItem`. There is no
168    /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
169    /// the node's position within the owning item in any way, but there is a
170    /// guarantee that the `ItemLocalId`s within an owner occupy a dense range of
171    /// integers starting at zero, so a mapping that maps all or most nodes within
172    /// an "item-like" to something else can be implemented by a `Vec` instead of a
173    /// tree or hash map.
174    #[stable_hash]
175    #[encodable]
176    #[orderable]
177    pub struct ItemLocalId {}
178}
179
180impl<E> ContextOrd<E> for ItemLocalId {
181    fn stable_cmp_with_context(_context: E) -> impl FnMut(&Self, &Self) -> std::cmp::Ordering {
182        <Self as Ord>::cmp
183    }
184}
185
186impl ItemLocalId {
187    /// Signal local id which should never be used.
188    pub const INVALID: ItemLocalId = ItemLocalId::MAX;
189}
190
191impl StableOrd for ItemLocalId {
192    const CAN_USE_UNSTABLE_SORT: bool = true;
193
194    // `Ord` is implemented as just comparing the ItemLocalId's numerical
195    // values and these are not changed by (de-)serialization.
196    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
197}
198
199/// The `HirId` corresponding to `CRATE_NODE_ID` and `CRATE_DEF_ID`.
200pub const CRATE_HIR_ID: HirId =
201    HirId { owner: OwnerId { def_id: CRATE_DEF_ID }, local_id: ItemLocalId::ZERO };
202
203pub const CRATE_OWNER_ID: OwnerId = OwnerId { def_id: CRATE_DEF_ID };