rustc_hir/
hir_id.rs

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