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