]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_span/src/def_id.rs
Auto merge of #83273 - cjgillot:endecode, r=michaelwoerister
[rust.git] / compiler / rustc_span / src / def_id.rs
1 use crate::crate_disambiguator::CrateDisambiguator;
2 use crate::HashStableContext;
3 use rustc_data_structures::fingerprint::Fingerprint;
4 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
5 use rustc_data_structures::AtomicRef;
6 use rustc_index::vec::Idx;
7 use rustc_macros::HashStable_Generic;
8 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
9 use std::borrow::Borrow;
10 use std::fmt;
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<E: Encoder> Encodable<E> for CrateNum {
89     default fn encode(&self, s: &mut E) -> Result<(), E::Error> {
90         s.emit_u32(self.as_u32())
91     }
92 }
93
94 impl<D: Decoder> Decodable<D> for CrateNum {
95     default fn decode(d: &mut D) -> Result<CrateNum, D::Error> {
96         Ok(CrateNum::from_u32(d.read_u32()?))
97     }
98 }
99
100 impl ::std::fmt::Debug for CrateNum {
101     fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
102         match self {
103             CrateNum::Index(id) => write!(fmt, "crate{}", id.private),
104             CrateNum::ReservedForIncrCompCache => write!(fmt, "crate for decoding incr comp cache"),
105         }
106     }
107 }
108
109 /// A `DefPathHash` is a fixed-size representation of a `DefPath` that is
110 /// stable across crate and compilation session boundaries. It consists of two
111 /// separate 64-bit hashes. The first uniquely identifies the crate this
112 /// `DefPathHash` originates from (see [StableCrateId]), and the second
113 /// uniquely identifies the corresponding `DefPath` within that crate. Together
114 /// they form a unique identifier within an entire crate graph.
115 ///
116 /// There is a very small chance of hash collisions, which would mean that two
117 /// different `DefPath`s map to the same `DefPathHash`. Proceeding compilation
118 /// with such a hash collision would very probably lead to an ICE, and in the
119 /// worst case lead to a silent mis-compilation. The compiler therefore actively
120 /// and exhaustively checks for such hash collisions and aborts compilation if
121 /// it finds one.
122 ///
123 /// `DefPathHash` uses 64-bit hashes for both the crate-id part and the
124 /// crate-internal part, even though it is likely that there are many more
125 /// `LocalDefId`s in a single crate than there are individual crates in a crate
126 /// graph. Since we use the same number of bits in both cases, the collision
127 /// probability for the crate-local part will be quite a bit higher (though
128 /// still very small).
129 ///
130 /// This imbalance is not by accident: A hash collision in the
131 /// crate-local part of a `DefPathHash` will be detected and reported while
132 /// compiling the crate in question. Such a collision does not depend on
133 /// outside factors and can be easily fixed by the crate maintainer (e.g. by
134 /// renaming the item in question or by bumping the crate version in a harmless
135 /// way).
136 ///
137 /// A collision between crate-id hashes on the other hand is harder to fix
138 /// because it depends on the set of crates in the entire crate graph of a
139 /// compilation session. Again, using the same crate with a different version
140 /// number would fix the issue with a high probability -- but that might be
141 /// easier said then done if the crates in questions are dependencies of
142 /// third-party crates.
143 ///
144 /// That being said, given a high quality hash function, the collision
145 /// probabilities in question are very small. For example, for a big crate like
146 /// `rustc_middle` (with ~50000 `LocalDefId`s as of the time of writing) there
147 /// is a probability of roughly 1 in 14,750,000,000 of a crate-internal
148 /// collision occurring. For a big crate graph with 1000 crates in it, there is
149 /// a probability of 1 in 36,890,000,000,000 of a `StableCrateId` collision.
150 #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Debug)]
151 #[derive(HashStable_Generic, Encodable, Decodable)]
152 pub struct DefPathHash(pub Fingerprint);
153
154 impl DefPathHash {
155     /// Returns the [StableCrateId] identifying the crate this [DefPathHash]
156     /// originates from.
157     #[inline]
158     pub fn stable_crate_id(&self) -> StableCrateId {
159         StableCrateId(self.0.as_value().0)
160     }
161
162     /// Returns the crate-local part of the [DefPathHash].
163     #[inline]
164     pub fn local_hash(&self) -> u64 {
165         self.0.as_value().1
166     }
167
168     /// Builds a new [DefPathHash] with the given [StableCrateId] and
169     /// `local_hash`, where `local_hash` must be unique within its crate.
170     pub fn new(stable_crate_id: StableCrateId, local_hash: u64) -> DefPathHash {
171         DefPathHash(Fingerprint::new(stable_crate_id.0, local_hash))
172     }
173 }
174
175 impl Borrow<Fingerprint> for DefPathHash {
176     #[inline]
177     fn borrow(&self) -> &Fingerprint {
178         &self.0
179     }
180 }
181
182 /// A [StableCrateId] is a 64 bit hash of `(crate-name, crate-disambiguator)`. It
183 /// is to [CrateNum] what [DefPathHash] is to [DefId]. It is stable across
184 /// compilation sessions.
185 ///
186 /// Since the ID is a hash value there is a (very small) chance that two crates
187 /// end up with the same [StableCrateId]. The compiler will check for such
188 /// collisions when loading crates and abort compilation in order to avoid
189 /// further trouble.
190 #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Debug, Encodable, Decodable)]
191 pub struct StableCrateId(u64);
192
193 impl StableCrateId {
194     /// Computes the stable ID for a crate with the given name and
195     /// disambiguator.
196     pub fn new(crate_name: &str, crate_disambiguator: CrateDisambiguator) -> StableCrateId {
197         use std::hash::Hash;
198
199         let mut hasher = StableHasher::new();
200         crate_name.hash(&mut hasher);
201         crate_disambiguator.hash(&mut hasher);
202         StableCrateId(hasher.finish())
203     }
204 }
205
206 rustc_index::newtype_index! {
207     /// A DefIndex is an index into the hir-map for a crate, identifying a
208     /// particular definition. It should really be considered an interned
209     /// shorthand for a particular DefPath.
210     pub struct DefIndex {
211         ENCODABLE = custom // (only encodable in metadata)
212
213         DEBUG_FORMAT = "DefIndex({})",
214         /// The crate root is always assigned index 0 by the AST Map code,
215         /// thanks to `NodeCollector::new`.
216         const CRATE_DEF_INDEX = 0,
217     }
218 }
219
220 impl<E: Encoder> Encodable<E> for DefIndex {
221     default fn encode(&self, _: &mut E) -> Result<(), E::Error> {
222         panic!("cannot encode `DefIndex` with `{}`", std::any::type_name::<E>());
223     }
224 }
225
226 impl<D: Decoder> Decodable<D> for DefIndex {
227     default fn decode(_: &mut D) -> Result<DefIndex, D::Error> {
228         panic!("cannot decode `DefIndex` with `{}`", std::any::type_name::<D>());
229     }
230 }
231
232 /// A `DefId` identifies a particular *definition*, by combining a crate
233 /// index and a def index.
234 ///
235 /// You can create a `DefId` from a `LocalDefId` using `local_def_id.to_def_id()`.
236 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy)]
237 pub struct DefId {
238     pub krate: CrateNum,
239     pub index: DefIndex,
240 }
241
242 impl DefId {
243     /// Makes a local `DefId` from the given `DefIndex`.
244     #[inline]
245     pub fn local(index: DefIndex) -> DefId {
246         DefId { krate: LOCAL_CRATE, index }
247     }
248
249     /// Returns whether the item is defined in the crate currently being compiled.
250     #[inline]
251     pub fn is_local(self) -> bool {
252         self.krate == LOCAL_CRATE
253     }
254
255     #[inline]
256     pub fn as_local(self) -> Option<LocalDefId> {
257         if self.is_local() { Some(LocalDefId { local_def_index: self.index }) } else { None }
258     }
259
260     #[inline]
261     pub fn expect_local(self) -> LocalDefId {
262         self.as_local().unwrap_or_else(|| panic!("DefId::expect_local: `{:?}` isn't local", self))
263     }
264
265     pub fn is_top_level_module(self) -> bool {
266         self.is_local() && self.index == CRATE_DEF_INDEX
267     }
268 }
269
270 impl<E: Encoder> Encodable<E> for DefId {
271     default fn encode(&self, s: &mut E) -> Result<(), E::Error> {
272         s.emit_struct("DefId", 2, |s| {
273             s.emit_struct_field("krate", 0, |s| self.krate.encode(s))?;
274
275             s.emit_struct_field("index", 1, |s| self.index.encode(s))
276         })
277     }
278 }
279
280 impl<D: Decoder> Decodable<D> for DefId {
281     default fn decode(d: &mut D) -> Result<DefId, D::Error> {
282         d.read_struct("DefId", 2, |d| {
283             Ok(DefId {
284                 krate: d.read_struct_field("krate", 0, Decodable::decode)?,
285                 index: d.read_struct_field("index", 1, Decodable::decode)?,
286             })
287         })
288     }
289 }
290
291 pub fn default_def_id_debug(def_id: DefId, f: &mut fmt::Formatter<'_>) -> fmt::Result {
292     f.debug_struct("DefId").field("krate", &def_id.krate).field("index", &def_id.index).finish()
293 }
294
295 pub static DEF_ID_DEBUG: AtomicRef<fn(DefId, &mut fmt::Formatter<'_>) -> fmt::Result> =
296     AtomicRef::new(&(default_def_id_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
297
298 impl fmt::Debug for DefId {
299     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
300         (*DEF_ID_DEBUG)(*self, f)
301     }
302 }
303
304 rustc_data_structures::define_id_collections!(DefIdMap, DefIdSet, DefId);
305
306 /// A LocalDefId is equivalent to a DefId with `krate == LOCAL_CRATE`. Since
307 /// we encode this information in the type, we can ensure at compile time that
308 /// no DefIds from upstream crates get thrown into the mix. There are quite a
309 /// few cases where we know that only DefIds from the local crate are expected
310 /// and a DefId from a different crate would signify a bug somewhere. This
311 /// is when LocalDefId comes in handy.
312 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
313 pub struct LocalDefId {
314     pub local_def_index: DefIndex,
315 }
316
317 pub const CRATE_DEF_ID: LocalDefId = LocalDefId { local_def_index: CRATE_DEF_INDEX };
318
319 impl Idx for LocalDefId {
320     #[inline]
321     fn new(idx: usize) -> Self {
322         LocalDefId { local_def_index: Idx::new(idx) }
323     }
324     #[inline]
325     fn index(self) -> usize {
326         self.local_def_index.index()
327     }
328 }
329
330 impl LocalDefId {
331     #[inline]
332     pub fn to_def_id(self) -> DefId {
333         DefId { krate: LOCAL_CRATE, index: self.local_def_index }
334     }
335
336     #[inline]
337     pub fn is_top_level_module(self) -> bool {
338         self.local_def_index == CRATE_DEF_INDEX
339     }
340 }
341
342 impl fmt::Debug for LocalDefId {
343     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
344         self.to_def_id().fmt(f)
345     }
346 }
347
348 impl<E: Encoder> Encodable<E> for LocalDefId {
349     fn encode(&self, s: &mut E) -> Result<(), E::Error> {
350         self.to_def_id().encode(s)
351     }
352 }
353
354 impl<D: Decoder> Decodable<D> for LocalDefId {
355     fn decode(d: &mut D) -> Result<LocalDefId, D::Error> {
356         DefId::decode(d).map(|d| d.expect_local())
357     }
358 }
359
360 rustc_data_structures::define_id_collections!(LocalDefIdMap, LocalDefIdSet, LocalDefId);
361
362 impl<CTX: HashStableContext> HashStable<CTX> for DefId {
363     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
364         hcx.hash_def_id(*self, hasher)
365     }
366 }
367
368 impl<CTX: HashStableContext> HashStable<CTX> for CrateNum {
369     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
370         hcx.hash_crate_num(*self, hasher)
371     }
372 }