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