]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_span/src/def_id.rs
Merge commit '2bb3996244cf1b89878da9e39841e9f6bf061602' into sync_cg_clif-2022-12-14
[rust.git] / compiler / rustc_span / src / def_id.rs
1 use crate::{HashStableContext, Symbol};
2 use rustc_data_structures::fingerprint::Fingerprint;
3 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
4 use rustc_data_structures::AtomicRef;
5 use rustc_index::vec::Idx;
6 use rustc_macros::HashStable_Generic;
7 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
8 use std::borrow::Borrow;
9 use std::fmt;
10 use std::hash::{Hash, Hasher};
11
12 rustc_index::newtype_index! {
13     pub struct CrateNum {
14         ENCODABLE = custom
15         DEBUG_FORMAT = "crate{}"
16     }
17 }
18
19 /// Item definitions in the currently-compiled crate would have the `CrateNum`
20 /// `LOCAL_CRATE` in their `DefId`.
21 pub const LOCAL_CRATE: CrateNum = CrateNum::from_u32(0);
22
23 impl CrateNum {
24     #[inline]
25     pub fn new(x: usize) -> CrateNum {
26         CrateNum::from_usize(x)
27     }
28
29     #[inline]
30     pub fn as_def_id(self) -> DefId {
31         DefId { krate: self, index: CRATE_DEF_INDEX }
32     }
33 }
34
35 impl fmt::Display for CrateNum {
36     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37         fmt::Display::fmt(&self.as_u32(), f)
38     }
39 }
40
41 /// As a local identifier, a `CrateNum` is only meaningful within its context, e.g. within a tcx.
42 /// Therefore, make sure to include the context when encode a `CrateNum`.
43 impl<E: Encoder> Encodable<E> for CrateNum {
44     default fn encode(&self, s: &mut E) {
45         s.emit_u32(self.as_u32());
46     }
47 }
48
49 impl<D: Decoder> Decodable<D> for CrateNum {
50     default fn decode(d: &mut D) -> CrateNum {
51         CrateNum::from_u32(d.read_u32())
52     }
53 }
54
55 /// A `DefPathHash` is a fixed-size representation of a `DefPath` that is
56 /// stable across crate and compilation session boundaries. It consists of two
57 /// separate 64-bit hashes. The first uniquely identifies the crate this
58 /// `DefPathHash` originates from (see [StableCrateId]), and the second
59 /// uniquely identifies the corresponding `DefPath` within that crate. Together
60 /// they form a unique identifier within an entire crate graph.
61 ///
62 /// There is a very small chance of hash collisions, which would mean that two
63 /// different `DefPath`s map to the same `DefPathHash`. Proceeding compilation
64 /// with such a hash collision would very probably lead to an ICE, and in the
65 /// worst case lead to a silent mis-compilation. The compiler therefore actively
66 /// and exhaustively checks for such hash collisions and aborts compilation if
67 /// it finds one.
68 ///
69 /// `DefPathHash` uses 64-bit hashes for both the crate-id part and the
70 /// crate-internal part, even though it is likely that there are many more
71 /// `LocalDefId`s in a single crate than there are individual crates in a crate
72 /// graph. Since we use the same number of bits in both cases, the collision
73 /// probability for the crate-local part will be quite a bit higher (though
74 /// still very small).
75 ///
76 /// This imbalance is not by accident: A hash collision in the
77 /// crate-local part of a `DefPathHash` will be detected and reported while
78 /// compiling the crate in question. Such a collision does not depend on
79 /// outside factors and can be easily fixed by the crate maintainer (e.g. by
80 /// renaming the item in question or by bumping the crate version in a harmless
81 /// way).
82 ///
83 /// A collision between crate-id hashes on the other hand is harder to fix
84 /// because it depends on the set of crates in the entire crate graph of a
85 /// compilation session. Again, using the same crate with a different version
86 /// number would fix the issue with a high probability -- but that might be
87 /// easier said then done if the crates in questions are dependencies of
88 /// third-party crates.
89 ///
90 /// That being said, given a high quality hash function, the collision
91 /// probabilities in question are very small. For example, for a big crate like
92 /// `rustc_middle` (with ~50000 `LocalDefId`s as of the time of writing) there
93 /// is a probability of roughly 1 in 14,750,000,000 of a crate-internal
94 /// collision occurring. For a big crate graph with 1000 crates in it, there is
95 /// a probability of 1 in 36,890,000,000,000 of a `StableCrateId` collision.
96 #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Debug)]
97 #[derive(HashStable_Generic, Encodable, Decodable)]
98 pub struct DefPathHash(pub Fingerprint);
99
100 impl DefPathHash {
101     /// Returns the [StableCrateId] identifying the crate this [DefPathHash]
102     /// originates from.
103     #[inline]
104     pub fn stable_crate_id(&self) -> StableCrateId {
105         StableCrateId(self.0.as_value().0)
106     }
107
108     /// Returns the crate-local part of the [DefPathHash].
109     ///
110     /// Used for tests.
111     #[inline]
112     pub fn local_hash(&self) -> u64 {
113         self.0.as_value().1
114     }
115
116     /// Builds a new [DefPathHash] with the given [StableCrateId] and
117     /// `local_hash`, where `local_hash` must be unique within its crate.
118     pub fn new(stable_crate_id: StableCrateId, local_hash: u64) -> DefPathHash {
119         DefPathHash(Fingerprint::new(stable_crate_id.0, local_hash))
120     }
121 }
122
123 impl Borrow<Fingerprint> for DefPathHash {
124     #[inline]
125     fn borrow(&self) -> &Fingerprint {
126         &self.0
127     }
128 }
129
130 /// A [`StableCrateId`] is a 64-bit hash of a crate name, together with all
131 /// `-Cmetadata` arguments, and some other data. It is to [`CrateNum`] what [`DefPathHash`] is to
132 /// [`DefId`]. It is stable across compilation sessions.
133 ///
134 /// Since the ID is a hash value, there is a small chance that two crates
135 /// end up with the same [`StableCrateId`]. The compiler will check for such
136 /// collisions when loading crates and abort compilation in order to avoid
137 /// further trouble.
138 ///
139 /// For more information on the possibility of hash collisions in rustc,
140 /// see the discussion in [`DefId`].
141 #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Debug)]
142 #[derive(HashStable_Generic, Encodable, Decodable)]
143 pub struct StableCrateId(pub(crate) u64);
144
145 impl StableCrateId {
146     pub fn to_u64(self) -> u64 {
147         self.0
148     }
149
150     /// Computes the stable ID for a crate with the given name and
151     /// `-Cmetadata` arguments.
152     pub fn new(crate_name: Symbol, is_exe: bool, mut metadata: Vec<String>) -> StableCrateId {
153         let mut hasher = StableHasher::new();
154         // We must hash the string text of the crate name, not the id, as the id is not stable
155         // across builds.
156         crate_name.as_str().hash(&mut hasher);
157
158         // We don't want the stable crate ID to depend on the order of
159         // -C metadata arguments, so sort them:
160         metadata.sort();
161         // Every distinct -C metadata value is only incorporated once:
162         metadata.dedup();
163
164         hasher.write(b"metadata");
165         for s in &metadata {
166             // Also incorporate the length of a metadata string, so that we generate
167             // different values for `-Cmetadata=ab -Cmetadata=c` and
168             // `-Cmetadata=a -Cmetadata=bc`
169             hasher.write_usize(s.len());
170             hasher.write(s.as_bytes());
171         }
172
173         // Also incorporate crate type, so that we don't get symbol conflicts when
174         // linking against a library of the same name, if this is an executable.
175         hasher.write(if is_exe { b"exe" } else { b"lib" });
176
177         // Also incorporate the rustc version. Otherwise, with -Zsymbol-mangling-version=v0
178         // and no -Cmetadata, symbols from the same crate compiled with different versions of
179         // rustc are named the same.
180         //
181         // RUSTC_FORCE_RUSTC_VERSION is used to inject rustc version information
182         // during testing.
183         if let Some(val) = std::env::var_os("RUSTC_FORCE_RUSTC_VERSION") {
184             hasher.write(val.to_string_lossy().into_owned().as_bytes())
185         } else {
186             hasher.write(option_env!("CFG_VERSION").unwrap_or("unknown version").as_bytes());
187         }
188
189         StableCrateId(hasher.finish())
190     }
191 }
192
193 rustc_index::newtype_index! {
194     /// A DefIndex is an index into the hir-map for a crate, identifying a
195     /// particular definition. It should really be considered an interned
196     /// shorthand for a particular DefPath.
197     pub struct DefIndex {
198         ENCODABLE = custom // (only encodable in metadata)
199
200         DEBUG_FORMAT = "DefIndex({})",
201         /// The crate root is always assigned index 0 by the AST Map code,
202         /// thanks to `NodeCollector::new`.
203         const CRATE_DEF_INDEX = 0,
204     }
205 }
206
207 impl<E: Encoder> Encodable<E> for DefIndex {
208     default fn encode(&self, _: &mut E) {
209         panic!("cannot encode `DefIndex` with `{}`", std::any::type_name::<E>());
210     }
211 }
212
213 impl<D: Decoder> Decodable<D> for DefIndex {
214     default fn decode(_: &mut D) -> DefIndex {
215         panic!("cannot decode `DefIndex` with `{}`", std::any::type_name::<D>());
216     }
217 }
218
219 /// A `DefId` identifies a particular *definition*, by combining a crate
220 /// index and a def index.
221 ///
222 /// You can create a `DefId` from a `LocalDefId` using `local_def_id.to_def_id()`.
223 #[derive(Clone, PartialEq, Eq, Copy)]
224 // Don't derive order on 64-bit big-endian, so we can be consistent regardless of field order.
225 #[cfg_attr(not(all(target_pointer_width = "64", target_endian = "big")), derive(PartialOrd, Ord))]
226 // On below-64 bit systems we can simply use the derived `Hash` impl
227 #[cfg_attr(not(target_pointer_width = "64"), derive(Hash))]
228 #[repr(C)]
229 #[rustc_pass_by_value]
230 // We guarantee field order. Note that the order is essential here, see below why.
231 pub struct DefId {
232     // cfg-ing the order of fields so that the `DefIndex` which is high entropy always ends up in
233     // the lower bits no matter the endianness. This allows the compiler to turn that `Hash` impl
234     // into a direct call to 'u64::hash(_)`.
235     #[cfg(not(all(target_pointer_width = "64", target_endian = "big")))]
236     pub index: DefIndex,
237     pub krate: CrateNum,
238     #[cfg(all(target_pointer_width = "64", target_endian = "big"))]
239     pub index: DefIndex,
240 }
241
242 // On 64-bit systems, we can hash the whole `DefId` as one `u64` instead of two `u32`s. This
243 // improves performance without impairing `FxHash` quality. So the below code gets compiled to a
244 // noop on little endian systems because the memory layout of `DefId` is as follows:
245 //
246 // ```
247 //     +-1--------------31-+-32-------------63-+
248 //     ! index             ! krate             !
249 //     +-------------------+-------------------+
250 // ```
251 //
252 // The order here has direct impact on `FxHash` quality because we have far more `DefIndex` per
253 // crate than we have `Crate`s within one compilation. Or in other words, this arrangement puts
254 // more entropy in the low bits than the high bits. The reason this matters is that `FxHash`, which
255 // is used throughout rustc, has problems distributing the entropy from the high bits, so reversing
256 // the order would lead to a large number of collisions and thus far worse performance.
257 //
258 // On 64-bit big-endian systems, this compiles to a 64-bit rotation by 32 bits, which is still
259 // faster than another `FxHash` round.
260 #[cfg(target_pointer_width = "64")]
261 impl Hash for DefId {
262     fn hash<H: Hasher>(&self, h: &mut H) {
263         (((self.krate.as_u32() as u64) << 32) | (self.index.as_u32() as u64)).hash(h)
264     }
265 }
266
267 // Implement the same comparison as derived with the other field order.
268 #[cfg(all(target_pointer_width = "64", target_endian = "big"))]
269 impl Ord for DefId {
270     #[inline]
271     fn cmp(&self, other: &DefId) -> std::cmp::Ordering {
272         Ord::cmp(&(self.index, self.krate), &(other.index, other.krate))
273     }
274 }
275 #[cfg(all(target_pointer_width = "64", target_endian = "big"))]
276 impl PartialOrd for DefId {
277     #[inline]
278     fn partial_cmp(&self, other: &DefId) -> Option<std::cmp::Ordering> {
279         Some(self.cmp(other))
280     }
281 }
282
283 impl DefId {
284     /// Makes a local `DefId` from the given `DefIndex`.
285     #[inline]
286     pub fn local(index: DefIndex) -> DefId {
287         DefId { krate: LOCAL_CRATE, index }
288     }
289
290     /// Returns whether the item is defined in the crate currently being compiled.
291     #[inline]
292     pub fn is_local(self) -> bool {
293         self.krate == LOCAL_CRATE
294     }
295
296     #[inline]
297     pub fn as_local(self) -> Option<LocalDefId> {
298         if self.is_local() { Some(LocalDefId { local_def_index: self.index }) } else { None }
299     }
300
301     #[inline]
302     #[track_caller]
303     pub fn expect_local(self) -> LocalDefId {
304         // NOTE: `match` below is required to apply `#[track_caller]`,
305         // i.e. don't use closures.
306         match self.as_local() {
307             Some(local_def_id) => local_def_id,
308             None => panic!("DefId::expect_local: `{:?}` isn't local", self),
309         }
310     }
311
312     #[inline]
313     pub fn is_crate_root(self) -> bool {
314         self.index == CRATE_DEF_INDEX
315     }
316
317     #[inline]
318     pub fn as_crate_root(self) -> Option<CrateNum> {
319         if self.is_crate_root() { Some(self.krate) } else { None }
320     }
321
322     #[inline]
323     pub fn is_top_level_module(self) -> bool {
324         self.is_local() && self.is_crate_root()
325     }
326 }
327
328 impl From<LocalDefId> for DefId {
329     fn from(local: LocalDefId) -> DefId {
330         local.to_def_id()
331     }
332 }
333
334 impl<E: Encoder> Encodable<E> for DefId {
335     default fn encode(&self, s: &mut E) {
336         self.krate.encode(s);
337         self.index.encode(s);
338     }
339 }
340
341 impl<D: Decoder> Decodable<D> for DefId {
342     default fn decode(d: &mut D) -> DefId {
343         DefId { krate: Decodable::decode(d), index: Decodable::decode(d) }
344     }
345 }
346
347 pub fn default_def_id_debug(def_id: DefId, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348     f.debug_struct("DefId").field("krate", &def_id.krate).field("index", &def_id.index).finish()
349 }
350
351 pub static DEF_ID_DEBUG: AtomicRef<fn(DefId, &mut fmt::Formatter<'_>) -> fmt::Result> =
352     AtomicRef::new(&(default_def_id_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
353
354 impl fmt::Debug for DefId {
355     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356         (*DEF_ID_DEBUG)(*self, f)
357     }
358 }
359
360 rustc_data_structures::define_id_collections!(DefIdMap, DefIdSet, DefIdMapEntry, DefId);
361
362 /// A `LocalDefId` is equivalent to a `DefId` with `krate == LOCAL_CRATE`. Since
363 /// we encode this information in the type, we can ensure at compile time that
364 /// no `DefId`s from upstream crates get thrown into the mix. There are quite a
365 /// few cases where we know that only `DefId`s from the local crate are expected;
366 /// a `DefId` from a different crate would signify a bug somewhere. This
367 /// is when `LocalDefId` comes in handy.
368 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
369 pub struct LocalDefId {
370     pub local_def_index: DefIndex,
371 }
372
373 // To ensure correctness of incremental compilation,
374 // `LocalDefId` must not implement `Ord` or `PartialOrd`.
375 // See https://github.com/rust-lang/rust/issues/90317.
376 impl !Ord for LocalDefId {}
377 impl !PartialOrd for LocalDefId {}
378
379 pub const CRATE_DEF_ID: LocalDefId = LocalDefId { local_def_index: CRATE_DEF_INDEX };
380
381 impl Idx for LocalDefId {
382     #[inline]
383     fn new(idx: usize) -> Self {
384         LocalDefId { local_def_index: Idx::new(idx) }
385     }
386     #[inline]
387     fn index(self) -> usize {
388         self.local_def_index.index()
389     }
390 }
391
392 impl LocalDefId {
393     #[inline]
394     pub fn to_def_id(self) -> DefId {
395         DefId { krate: LOCAL_CRATE, index: self.local_def_index }
396     }
397
398     #[inline]
399     pub fn is_top_level_module(self) -> bool {
400         self == CRATE_DEF_ID
401     }
402 }
403
404 impl fmt::Debug for LocalDefId {
405     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
406         self.to_def_id().fmt(f)
407     }
408 }
409
410 impl<E: Encoder> Encodable<E> for LocalDefId {
411     fn encode(&self, s: &mut E) {
412         self.to_def_id().encode(s);
413     }
414 }
415
416 impl<D: Decoder> Decodable<D> for LocalDefId {
417     fn decode(d: &mut D) -> LocalDefId {
418         DefId::decode(d).expect_local()
419     }
420 }
421
422 rustc_data_structures::define_id_collections!(
423     LocalDefIdMap,
424     LocalDefIdSet,
425     LocalDefIdMapEntry,
426     LocalDefId
427 );
428
429 impl<CTX: HashStableContext> HashStable<CTX> for DefId {
430     #[inline]
431     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
432         self.to_stable_hash_key(hcx).hash_stable(hcx, hasher);
433     }
434 }
435
436 impl<CTX: HashStableContext> HashStable<CTX> for LocalDefId {
437     #[inline]
438     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
439         self.to_stable_hash_key(hcx).hash_stable(hcx, hasher);
440     }
441 }
442
443 impl<CTX: HashStableContext> HashStable<CTX> for CrateNum {
444     #[inline]
445     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
446         self.to_stable_hash_key(hcx).hash_stable(hcx, hasher);
447     }
448 }
449
450 impl<CTX: HashStableContext> ToStableHashKey<CTX> for DefId {
451     type KeyType = DefPathHash;
452
453     #[inline]
454     fn to_stable_hash_key(&self, hcx: &CTX) -> DefPathHash {
455         hcx.def_path_hash(*self)
456     }
457 }
458
459 impl<CTX: HashStableContext> ToStableHashKey<CTX> for LocalDefId {
460     type KeyType = DefPathHash;
461
462     #[inline]
463     fn to_stable_hash_key(&self, hcx: &CTX) -> DefPathHash {
464         hcx.def_path_hash(self.to_def_id())
465     }
466 }
467
468 impl<CTX: HashStableContext> ToStableHashKey<CTX> for CrateNum {
469     type KeyType = DefPathHash;
470
471     #[inline]
472     fn to_stable_hash_key(&self, hcx: &CTX) -> DefPathHash {
473         self.as_def_id().to_stable_hash_key(hcx)
474     }
475 }