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_span::def_id::{CRATE_DEF_ID, DefId, DefIndex, DefPathHash, LocalDefId};
20
21#[derive(#[automatically_derived]
impl ::core::marker::Copy for OwnerId { }Copy, #[automatically_derived]
impl ::core::clone::Clone for OwnerId {
    #[inline]
    fn clone(&self) -> OwnerId {
        let _: ::core::clone::AssertParamIsClone<LocalDefId>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for OwnerId {
    #[inline]
    fn eq(&self, other: &OwnerId) -> 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)]
22pub struct OwnerId {
23    pub def_id: LocalDefId,
24}
25
26impl Debug for OwnerId {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        // Example: DefId(0:1 ~ aa[7697]::{use#0})
29        Debug::fmt(&self.def_id, f)
30    }
31}
32
33impl From<OwnerId> for HirId {
34    fn from(owner: OwnerId) -> HirId {
35        HirId { owner, local_id: ItemLocalId::ZERO }
36    }
37}
38
39impl From<OwnerId> for DefId {
40    fn from(value: OwnerId) -> Self {
41        value.to_def_id()
42    }
43}
44
45impl OwnerId {
46    #[inline]
47    pub fn to_def_id(self) -> DefId {
48        self.def_id.to_def_id()
49    }
50}
51
52impl rustc_index::Idx for OwnerId {
53    #[inline]
54    fn new(idx: usize) -> Self {
55        OwnerId { def_id: LocalDefId { local_def_index: DefIndex::from_usize(idx) } }
56    }
57
58    #[inline]
59    fn index(self) -> usize {
60        self.def_id.local_def_index.as_usize()
61    }
62}
63
64impl StableHash for OwnerId {
65    #[inline]
66    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
67        self.to_stable_hash_key(hcx).stable_hash(hcx, hasher);
68    }
69}
70
71impl ToStableHashKey for OwnerId {
72    type KeyType = DefPathHash;
73
74    #[inline]
75    fn to_stable_hash_key<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx) -> DefPathHash {
76        self.to_def_id().to_stable_hash_key(hcx)
77    }
78}
79
80/// Uniquely identifies a node in the HIR of the current crate. It is
81/// composed of the `owner`, which is the `LocalDefId` of the directly enclosing
82/// `hir::Item`, `hir::TraitItem`, or `hir::ImplItem` (i.e., the closest "item-like"),
83/// and the `local_id` which is unique within the given owner.
84///
85/// This two-level structure makes for more stable values: One can move an item
86/// around within the source code, or add or remove stuff before it, without
87/// the `local_id` part of the `HirId` changing, which is a very useful property in
88/// incremental compilation where we have to persist things through changes to
89/// the code base.
90#[derive(#[automatically_derived]
impl ::core::marker::Copy for HirId { }Copy, #[automatically_derived]
impl ::core::clone::Clone for HirId {
    #[inline]
    fn clone(&self) -> HirId {
        let _: ::core::clone::AssertParamIsClone<OwnerId>;
        let _: ::core::clone::AssertParamIsClone<ItemLocalId>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for HirId {
    #[inline]
    fn eq(&self, other: &HirId) -> 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)]
91#[rustc_pass_by_value]
92pub struct HirId {
93    pub owner: OwnerId,
94    pub local_id: ItemLocalId,
95}
96
97// To ensure correctness of incremental compilation,
98// `HirId` must not implement `Ord` or `PartialOrd`.
99// See https://github.com/rust-lang/rust/issues/90317.
100impl !Ord for HirId {}
101impl !PartialOrd for HirId {}
102
103impl Debug for HirId {
104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105        // Example: HirId(DefId(0:1 ~ aa[7697]::{use#0}).10)
106        // Don't use debug_tuple to always keep this on one line.
107        f.write_fmt(format_args!("HirId({0:?}.{1:?})", self.owner, self.local_id))write!(f, "HirId({:?}.{:?})", self.owner, self.local_id)
108    }
109}
110
111impl HirId {
112    /// Signal local id which should never be used.
113    pub const INVALID: HirId =
114        HirId { owner: OwnerId { def_id: CRATE_DEF_ID }, local_id: ItemLocalId::INVALID };
115
116    #[inline]
117    pub fn expect_owner(self) -> OwnerId {
118        {
    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);
119        self.owner
120    }
121
122    #[inline]
123    pub fn as_owner(self) -> Option<OwnerId> {
124        if self.local_id.index() == 0 { Some(self.owner) } else { None }
125    }
126
127    #[inline]
128    pub fn is_owner(self) -> bool {
129        self.local_id.index() == 0
130    }
131
132    #[inline]
133    pub fn make_owner(owner: LocalDefId) -> Self {
134        Self { owner: OwnerId { def_id: owner }, local_id: ItemLocalId::ZERO }
135    }
136}
137
138impl fmt::Display for HirId {
139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140        f.write_fmt(format_args!("{0:?}", self))write!(f, "{self:?}")
141    }
142}
143
144pub 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);
145pub 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!(
146    ItemLocalMap,
147    ItemLocalSet,
148    ItemLocalMapEntry,
149    ItemLocalId
150);
151
152impl ::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! {
153    /// An `ItemLocalId` uniquely identifies something within a given "item-like";
154    /// that is, within a `hir::Item`, `hir::TraitItem`, or `hir::ImplItem`. There is no
155    /// guarantee that the numerical value of a given `ItemLocalId` corresponds to
156    /// the node's position within the owning item in any way, but there is a
157    /// guarantee that the `ItemLocalId`s within an owner occupy a dense range of
158    /// integers starting at zero, so a mapping that maps all or most nodes within
159    /// an "item-like" to something else can be implemented by a `Vec` instead of a
160    /// tree or hash map.
161    #[stable_hash]
162    #[encodable]
163    #[orderable]
164    pub struct ItemLocalId {}
165}
166
167impl ItemLocalId {
168    /// Signal local id which should never be used.
169    pub const INVALID: ItemLocalId = ItemLocalId::MAX;
170}
171
172impl StableOrd for ItemLocalId {
173    const CAN_USE_UNSTABLE_SORT: bool = true;
174
175    // `Ord` is implemented as just comparing the ItemLocalId's numerical
176    // values and these are not changed by (de-)serialization.
177    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
178}
179
180/// The `HirId` corresponding to `CRATE_NODE_ID` and `CRATE_DEF_ID`.
181pub const CRATE_HIR_ID: HirId =
182    HirId { owner: OwnerId { def_id: CRATE_DEF_ID }, local_id: ItemLocalId::ZERO };
183
184pub const CRATE_OWNER_ID: OwnerId = OwnerId { def_id: CRATE_DEF_ID };