]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_data_structures/src/intern.rs
Show a note where a macro failed to match
[rust.git] / compiler / rustc_data_structures / src / intern.rs
1 use crate::stable_hasher::{HashStable, StableHasher};
2 use std::cmp::Ordering;
3 use std::hash::{Hash, Hasher};
4 use std::ops::Deref;
5 use std::ptr;
6
7 use crate::fingerprint::Fingerprint;
8
9 mod private {
10     #[derive(Clone, Copy, Debug)]
11     pub struct PrivateZst;
12 }
13
14 /// A reference to a value that is interned, and is known to be unique.
15 ///
16 /// Note that it is possible to have a `T` and a `Interned<T>` that are (or
17 /// refer to) equal but different values. But if you have two different
18 /// `Interned<T>`s, they both refer to the same value, at a single location in
19 /// memory. This means that equality and hashing can be done on the value's
20 /// address rather than the value's contents, which can improve performance.
21 ///
22 /// The `PrivateZst` field means you can pattern match with `Interned(v, _)`
23 /// but you can only construct a `Interned` with `new_unchecked`, and not
24 /// directly.
25 #[derive(Debug)]
26 #[rustc_pass_by_value]
27 pub struct Interned<'a, T>(pub &'a T, pub private::PrivateZst);
28
29 impl<'a, T> Interned<'a, T> {
30     /// Create a new `Interned` value. The value referred to *must* be interned
31     /// and thus be unique, and it *must* remain unique in the future. This
32     /// function has `_unchecked` in the name but is not `unsafe`, because if
33     /// the uniqueness condition is violated condition it will cause incorrect
34     /// behaviour but will not affect memory safety.
35     #[inline]
36     pub const fn new_unchecked(t: &'a T) -> Self {
37         Interned(t, private::PrivateZst)
38     }
39 }
40
41 impl<'a, T> Clone for Interned<'a, T> {
42     fn clone(&self) -> Self {
43         *self
44     }
45 }
46
47 impl<'a, T> Copy for Interned<'a, T> {}
48
49 impl<'a, T> Deref for Interned<'a, T> {
50     type Target = T;
51
52     #[inline]
53     fn deref(&self) -> &T {
54         self.0
55     }
56 }
57
58 impl<'a, T> PartialEq for Interned<'a, T> {
59     #[inline]
60     fn eq(&self, other: &Self) -> bool {
61         // Pointer equality implies equality, due to the uniqueness constraint.
62         ptr::eq(self.0, other.0)
63     }
64 }
65
66 impl<'a, T> Eq for Interned<'a, T> {}
67
68 impl<'a, T: PartialOrd> PartialOrd for Interned<'a, T> {
69     fn partial_cmp(&self, other: &Interned<'a, T>) -> Option<Ordering> {
70         // Pointer equality implies equality, due to the uniqueness constraint,
71         // but the contents must be compared otherwise.
72         if ptr::eq(self.0, other.0) {
73             Some(Ordering::Equal)
74         } else {
75             let res = self.0.partial_cmp(&other.0);
76             debug_assert_ne!(res, Some(Ordering::Equal));
77             res
78         }
79     }
80 }
81
82 impl<'a, T: Ord> Ord for Interned<'a, T> {
83     fn cmp(&self, other: &Interned<'a, T>) -> Ordering {
84         // Pointer equality implies equality, due to the uniqueness constraint,
85         // but the contents must be compared otherwise.
86         if ptr::eq(self.0, other.0) {
87             Ordering::Equal
88         } else {
89             let res = self.0.cmp(&other.0);
90             debug_assert_ne!(res, Ordering::Equal);
91             res
92         }
93     }
94 }
95
96 impl<'a, T> Hash for Interned<'a, T> {
97     #[inline]
98     fn hash<H: Hasher>(&self, s: &mut H) {
99         // Pointer hashing is sufficient, due to the uniqueness constraint.
100         ptr::hash(self.0, s)
101     }
102 }
103
104 impl<T, CTX> HashStable<CTX> for Interned<'_, T>
105 where
106     T: HashStable<CTX>,
107 {
108     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
109         self.0.hash_stable(hcx, hasher);
110     }
111 }
112
113 /// A helper trait so that `Interned` things can cache stable hashes reproducibly.
114 pub trait InternedHashingContext {
115     fn with_def_path_and_no_spans(&mut self, f: impl FnOnce(&mut Self));
116 }
117
118 /// A helper type that you can wrap round your own type in order to automatically
119 /// cache the stable hash on creation and not recompute it whenever the stable hash
120 /// of the type is computed.
121 /// This is only done in incremental mode. You can also opt out of caching by using
122 /// StableHash::ZERO for the hash, in which case the hash gets computed each time.
123 /// This is useful if you have values that you intern but never (can?) use for stable
124 /// hashing.
125 #[derive(Copy, Clone)]
126 pub struct WithStableHash<T> {
127     pub internee: T,
128     pub stable_hash: Fingerprint,
129 }
130
131 impl<T: PartialEq> PartialEq for WithStableHash<T> {
132     #[inline]
133     fn eq(&self, other: &Self) -> bool {
134         self.internee.eq(&other.internee)
135     }
136 }
137
138 impl<T: Eq> Eq for WithStableHash<T> {}
139
140 impl<T: Ord> PartialOrd for WithStableHash<T> {
141     fn partial_cmp(&self, other: &WithStableHash<T>) -> Option<Ordering> {
142         Some(self.internee.cmp(&other.internee))
143     }
144 }
145
146 impl<T: Ord> Ord for WithStableHash<T> {
147     fn cmp(&self, other: &WithStableHash<T>) -> Ordering {
148         self.internee.cmp(&other.internee)
149     }
150 }
151
152 impl<T> Deref for WithStableHash<T> {
153     type Target = T;
154
155     #[inline]
156     fn deref(&self) -> &T {
157         &self.internee
158     }
159 }
160
161 impl<T: Hash> Hash for WithStableHash<T> {
162     #[inline]
163     fn hash<H: Hasher>(&self, s: &mut H) {
164         self.internee.hash(s)
165     }
166 }
167
168 impl<T: HashStable<CTX>, CTX: InternedHashingContext> HashStable<CTX> for WithStableHash<T> {
169     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
170         if self.stable_hash == Fingerprint::ZERO || cfg!(debug_assertions) {
171             // No cached hash available. This can only mean that incremental is disabled.
172             // We don't cache stable hashes in non-incremental mode, because they are used
173             // so rarely that the performance actually suffers.
174
175             // We need to build the hash as if we cached it and then hash that hash, as
176             // otherwise the hashes will differ between cached and non-cached mode.
177             let stable_hash: Fingerprint = {
178                 let mut hasher = StableHasher::new();
179                 hcx.with_def_path_and_no_spans(|hcx| self.internee.hash_stable(hcx, &mut hasher));
180                 hasher.finish()
181             };
182             if cfg!(debug_assertions) && self.stable_hash != Fingerprint::ZERO {
183                 assert_eq!(
184                     stable_hash, self.stable_hash,
185                     "cached stable hash does not match freshly computed stable hash"
186                 );
187             }
188             stable_hash.hash_stable(hcx, hasher);
189         } else {
190             self.stable_hash.hash_stable(hcx, hasher);
191         }
192     }
193 }
194
195 #[cfg(test)]
196 mod tests;