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