]> git.lizzy.rs Git - rust.git/blob - src/librustc_span/def_id.rs
a874f81868f153ab6f373101b30136841687b10e
[rust.git] / src / librustc_span / def_id.rs
1 use crate::HashStableContext;
2 use rustc_data_structures::fingerprint::Fingerprint;
3 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
4 use rustc_data_structures::AtomicRef;
5 use rustc_index::vec::Idx;
6 use rustc_macros::HashStable_Generic;
7 use rustc_serialize::{Decoder, Encoder};
8 use std::borrow::Borrow;
9 use std::fmt;
10
11 rustc_index::newtype_index! {
12     pub struct CrateId {
13         ENCODABLE = custom
14     }
15 }
16
17 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
18 pub enum CrateNum {
19     /// A special `CrateNum` that we use for the `tcx.rcache` when decoding from
20     /// the incr. comp. cache.
21     ReservedForIncrCompCache,
22     Index(CrateId),
23 }
24
25 /// Item definitions in the currently-compiled crate would have the `CrateNum`
26 /// `LOCAL_CRATE` in their `DefId`.
27 pub const LOCAL_CRATE: CrateNum = CrateNum::Index(CrateId::from_u32(0));
28
29 impl Idx for CrateNum {
30     #[inline]
31     fn new(value: usize) -> Self {
32         CrateNum::Index(Idx::new(value))
33     }
34
35     #[inline]
36     fn index(self) -> usize {
37         match self {
38             CrateNum::Index(idx) => Idx::index(idx),
39             _ => panic!("Tried to get crate index of {:?}", self),
40         }
41     }
42 }
43
44 impl CrateNum {
45     pub fn new(x: usize) -> CrateNum {
46         CrateNum::from_usize(x)
47     }
48
49     pub fn from_usize(x: usize) -> CrateNum {
50         CrateNum::Index(CrateId::from_usize(x))
51     }
52
53     pub fn from_u32(x: u32) -> CrateNum {
54         CrateNum::Index(CrateId::from_u32(x))
55     }
56
57     pub fn as_usize(self) -> usize {
58         match self {
59             CrateNum::Index(id) => id.as_usize(),
60             _ => panic!("tried to get index of non-standard crate {:?}", self),
61         }
62     }
63
64     pub fn as_u32(self) -> u32 {
65         match self {
66             CrateNum::Index(id) => id.as_u32(),
67             _ => panic!("tried to get index of non-standard crate {:?}", self),
68         }
69     }
70
71     pub fn as_def_id(&self) -> DefId {
72         DefId { krate: *self, index: CRATE_DEF_INDEX }
73     }
74 }
75
76 impl fmt::Display for CrateNum {
77     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78         match self {
79             CrateNum::Index(id) => fmt::Display::fmt(&id.private, f),
80             CrateNum::ReservedForIncrCompCache => write!(f, "crate for decoding incr comp cache"),
81         }
82     }
83 }
84
85 /// As a local identifier, a `CrateNum` is only meaningful within its context, e.g. within a tcx.
86 /// Therefore, make sure to include the context when encode a `CrateNum`.
87 impl rustc_serialize::UseSpecializedEncodable for CrateNum {
88     fn default_encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
89         e.emit_u32(self.as_u32())
90     }
91 }
92 impl rustc_serialize::UseSpecializedDecodable for CrateNum {
93     fn default_decode<D: Decoder>(d: &mut D) -> Result<CrateNum, D::Error> {
94         Ok(CrateNum::from_u32(d.read_u32()?))
95     }
96 }
97
98 impl ::std::fmt::Debug for CrateNum {
99     fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
100         match self {
101             CrateNum::Index(id) => write!(fmt, "crate{}", id.private),
102             CrateNum::ReservedForIncrCompCache => write!(fmt, "crate for decoding incr comp cache"),
103         }
104     }
105 }
106
107 #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Debug, RustcEncodable, RustcDecodable)]
108 #[derive(HashStable_Generic)]
109 pub struct DefPathHash(pub Fingerprint);
110
111 impl Borrow<Fingerprint> for DefPathHash {
112     #[inline]
113     fn borrow(&self) -> &Fingerprint {
114         &self.0
115     }
116 }
117
118 rustc_index::newtype_index! {
119     /// A DefIndex is an index into the hir-map for a crate, identifying a
120     /// particular definition. It should really be considered an interned
121     /// shorthand for a particular DefPath.
122     pub struct DefIndex {
123         DEBUG_FORMAT = "DefIndex({})",
124
125         /// The crate root is always assigned index 0 by the AST Map code,
126         /// thanks to `NodeCollector::new`.
127         const CRATE_DEF_INDEX = 0,
128     }
129 }
130
131 impl rustc_serialize::UseSpecializedEncodable for DefIndex {}
132 impl rustc_serialize::UseSpecializedDecodable for DefIndex {}
133
134 /// A `DefId` identifies a particular *definition*, by combining a crate
135 /// index and a def index.
136 ///
137 /// You can create a `DefId` from a `LocalDefId` using `local_def_id.to_def_id()`.
138 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy)]
139 pub struct DefId {
140     pub krate: CrateNum,
141     pub index: DefIndex,
142 }
143
144 impl DefId {
145     /// Makes a local `DefId` from the given `DefIndex`.
146     #[inline]
147     pub fn local(index: DefIndex) -> DefId {
148         DefId { krate: LOCAL_CRATE, index }
149     }
150
151     #[inline]
152     pub fn is_local(self) -> bool {
153         self.krate == LOCAL_CRATE
154     }
155
156     #[inline]
157     pub fn as_local(self) -> Option<LocalDefId> {
158         if self.is_local() { Some(LocalDefId { local_def_index: self.index }) } else { None }
159     }
160
161     #[inline]
162     pub fn expect_local(self) -> LocalDefId {
163         self.as_local().unwrap_or_else(|| panic!("DefId::expect_local: `{:?}` isn't local", self))
164     }
165
166     pub fn is_top_level_module(self) -> bool {
167         self.is_local() && self.index == CRATE_DEF_INDEX
168     }
169 }
170
171 impl rustc_serialize::UseSpecializedEncodable for DefId {
172     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
173         let krate = u64::from(self.krate.as_u32());
174         let index = u64::from(self.index.as_u32());
175         s.emit_u64((krate << 32) | index)
176     }
177 }
178 impl rustc_serialize::UseSpecializedDecodable for DefId {
179     fn default_decode<D: Decoder>(d: &mut D) -> Result<DefId, D::Error> {
180         let def_id = d.read_u64()?;
181         let krate = CrateNum::from_u32((def_id >> 32) as u32);
182         let index = DefIndex::from_u32((def_id & 0xffffffff) as u32);
183         Ok(DefId { krate, index })
184     }
185 }
186
187 pub fn default_def_id_debug(def_id: DefId, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188     f.debug_struct("DefId").field("krate", &def_id.krate).field("index", &def_id.index).finish()
189 }
190
191 pub static DEF_ID_DEBUG: AtomicRef<fn(DefId, &mut fmt::Formatter<'_>) -> fmt::Result> =
192     AtomicRef::new(&(default_def_id_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
193
194 impl fmt::Debug for DefId {
195     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196         (*DEF_ID_DEBUG)(*self, f)
197     }
198 }
199
200 rustc_data_structures::define_id_collections!(DefIdMap, DefIdSet, DefId);
201
202 /// A LocalDefId is equivalent to a DefId with `krate == LOCAL_CRATE`. Since
203 /// we encode this information in the type, we can ensure at compile time that
204 /// no DefIds from upstream crates get thrown into the mix. There are quite a
205 /// few cases where we know that only DefIds from the local crate are expected
206 /// and a DefId from a different crate would signify a bug somewhere. This
207 /// is when LocalDefId comes in handy.
208 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
209 pub struct LocalDefId {
210     pub local_def_index: DefIndex,
211 }
212
213 impl Idx for LocalDefId {
214     #[inline]
215     fn new(idx: usize) -> Self {
216         LocalDefId { local_def_index: Idx::new(idx) }
217     }
218     #[inline]
219     fn index(self) -> usize {
220         self.local_def_index.index()
221     }
222 }
223
224 impl LocalDefId {
225     #[inline]
226     pub fn to_def_id(self) -> DefId {
227         DefId { krate: LOCAL_CRATE, index: self.local_def_index }
228     }
229
230     #[inline]
231     pub fn is_top_level_module(self) -> bool {
232         self.local_def_index == CRATE_DEF_INDEX
233     }
234 }
235
236 impl fmt::Debug for LocalDefId {
237     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238         self.to_def_id().fmt(f)
239     }
240 }
241
242 impl rustc_serialize::UseSpecializedEncodable for LocalDefId {}
243 impl rustc_serialize::UseSpecializedDecodable for LocalDefId {}
244
245 impl<CTX: HashStableContext> HashStable<CTX> for DefId {
246     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
247         hcx.hash_def_id(*self, hasher)
248     }
249 }
250
251 impl<CTX: HashStableContext> HashStable<CTX> for CrateNum {
252     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
253         hcx.hash_crate_num(*self, hasher)
254     }
255 }