]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_data_structures/src/stable_hasher.rs
Bless nll tests.
[rust.git] / compiler / rustc_data_structures / src / stable_hasher.rs
1 use crate::sip128::SipHasher128;
2 use rustc_index::bit_set;
3 use rustc_index::vec;
4 use smallvec::SmallVec;
5 use std::hash::{BuildHasher, Hash, Hasher};
6 use std::mem;
7
8 #[cfg(test)]
9 mod tests;
10
11 /// When hashing something that ends up affecting properties like symbol names,
12 /// we want these symbol names to be calculated independently of other factors
13 /// like what architecture you're compiling *from*.
14 ///
15 /// To that end we always convert integers to little-endian format before
16 /// hashing and the architecture dependent `isize` and `usize` types are
17 /// extended to 64 bits if needed.
18 pub struct StableHasher {
19     state: SipHasher128,
20 }
21
22 impl ::std::fmt::Debug for StableHasher {
23     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24         write!(f, "{:?}", self.state)
25     }
26 }
27
28 pub trait StableHasherResult: Sized {
29     fn finish(hasher: StableHasher) -> Self;
30 }
31
32 impl StableHasher {
33     #[inline]
34     pub fn new() -> Self {
35         StableHasher { state: SipHasher128::new_with_keys(0, 0) }
36     }
37
38     #[inline]
39     pub fn finish<W: StableHasherResult>(self) -> W {
40         W::finish(self)
41     }
42 }
43
44 impl StableHasherResult for u128 {
45     #[inline]
46     fn finish(hasher: StableHasher) -> Self {
47         let (_0, _1) = hasher.finalize();
48         u128::from(_0) | (u128::from(_1) << 64)
49     }
50 }
51
52 impl StableHasherResult for u64 {
53     #[inline]
54     fn finish(hasher: StableHasher) -> Self {
55         hasher.finalize().0
56     }
57 }
58
59 impl StableHasher {
60     #[inline]
61     pub fn finalize(self) -> (u64, u64) {
62         self.state.finish128()
63     }
64 }
65
66 impl Hasher for StableHasher {
67     fn finish(&self) -> u64 {
68         panic!("use StableHasher::finalize instead");
69     }
70
71     #[inline]
72     fn write(&mut self, bytes: &[u8]) {
73         self.state.write(bytes);
74     }
75
76     #[inline]
77     fn write_u8(&mut self, i: u8) {
78         self.state.write_u8(i);
79     }
80
81     #[inline]
82     fn write_u16(&mut self, i: u16) {
83         self.state.write_u16(i.to_le());
84     }
85
86     #[inline]
87     fn write_u32(&mut self, i: u32) {
88         self.state.write_u32(i.to_le());
89     }
90
91     #[inline]
92     fn write_u64(&mut self, i: u64) {
93         self.state.write_u64(i.to_le());
94     }
95
96     #[inline]
97     fn write_u128(&mut self, i: u128) {
98         self.state.write_u128(i.to_le());
99     }
100
101     #[inline]
102     fn write_usize(&mut self, i: usize) {
103         // Always treat usize as u64 so we get the same results on 32 and 64 bit
104         // platforms. This is important for symbol hashes when cross compiling,
105         // for example.
106         self.state.write_u64((i as u64).to_le());
107     }
108
109     #[inline]
110     fn write_i8(&mut self, i: i8) {
111         self.state.write_i8(i);
112     }
113
114     #[inline]
115     fn write_i16(&mut self, i: i16) {
116         self.state.write_i16(i.to_le());
117     }
118
119     #[inline]
120     fn write_i32(&mut self, i: i32) {
121         self.state.write_i32(i.to_le());
122     }
123
124     #[inline]
125     fn write_i64(&mut self, i: i64) {
126         self.state.write_i64(i.to_le());
127     }
128
129     #[inline]
130     fn write_i128(&mut self, i: i128) {
131         self.state.write_i128(i.to_le());
132     }
133
134     #[inline]
135     fn write_isize(&mut self, i: isize) {
136         // Always treat isize as a 64-bit number so we get the same results on 32 and 64 bit
137         // platforms. This is important for symbol hashes when cross compiling,
138         // for example. Sign extending here is preferable as it means that the
139         // same negative number hashes the same on both 32 and 64 bit platforms.
140         let value = i as u64;
141
142         // Cold path
143         #[cold]
144         #[inline(never)]
145         fn hash_value(state: &mut SipHasher128, value: u64) {
146             state.write_u8(0xFF);
147             state.write_u64(value.to_le());
148         }
149
150         // `isize` values often seem to have a small (positive) numeric value in practice.
151         // To exploit this, if the value is small, we will hash a smaller amount of bytes.
152         // However, we cannot just skip the leading zero bytes, as that would produce the same hash
153         // e.g. if you hash two values that have the same bit pattern when they are swapped.
154         // See https://github.com/rust-lang/rust/pull/93014 for context.
155         //
156         // Therefore, we employ the following strategy:
157         // 1) When we encounter a value that fits within a single byte (the most common case), we
158         // hash just that byte. This is the most common case that is being optimized. However, we do
159         // not do this for the value 0xFF, as that is a reserved prefix (a bit like in UTF-8).
160         // 2) When we encounter a larger value, we hash a "marker" 0xFF and then the corresponding
161         // 8 bytes. Since this prefix cannot occur when we hash a single byte, when we hash two
162         // `isize`s that fit within a different amount of bytes, they should always produce a different
163         // byte stream for the hasher.
164         //
165         // To ensure that this optimization hashes the exact same bytes on both little-endian and
166         // big-endian architectures, we compare the value with 0xFF before we convert the number
167         // into a unified representation (little-endian).
168         if value < 0xFF {
169             self.state.write_u8(value as u8);
170         } else {
171             hash_value(&mut self.state, value);
172         }
173     }
174 }
175
176 /// Something that implements `HashStable<CTX>` can be hashed in a way that is
177 /// stable across multiple compilation sessions.
178 ///
179 /// Note that `HashStable` imposes rather more strict requirements than usual
180 /// hash functions:
181 ///
182 /// - Stable hashes are sometimes used as identifiers. Therefore they must
183 ///   conform to the corresponding `PartialEq` implementations:
184 ///
185 ///     - `x == y` implies `hash_stable(x) == hash_stable(y)`, and
186 ///     - `x != y` implies `hash_stable(x) != hash_stable(y)`.
187 ///
188 ///   That second condition is usually not required for hash functions
189 ///   (e.g. `Hash`). In practice this means that `hash_stable` must feed any
190 ///   information into the hasher that a `PartialEq` comparison takes into
191 ///   account. See [#49300](https://github.com/rust-lang/rust/issues/49300)
192 ///   for an example where violating this invariant has caused trouble in the
193 ///   past.
194 ///
195 /// - `hash_stable()` must be independent of the current
196 ///    compilation session. E.g. they must not hash memory addresses or other
197 ///    things that are "randomly" assigned per compilation session.
198 ///
199 /// - `hash_stable()` must be independent of the host architecture. The
200 ///   `StableHasher` takes care of endianness and `isize`/`usize` platform
201 ///   differences.
202 pub trait HashStable<CTX> {
203     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher);
204 }
205
206 /// Implement this for types that can be turned into stable keys like, for
207 /// example, for DefId that can be converted to a DefPathHash. This is used for
208 /// bringing maps into a predictable order before hashing them.
209 pub trait ToStableHashKey<HCX> {
210     type KeyType: Ord + Sized + HashStable<HCX>;
211     fn to_stable_hash_key(&self, hcx: &HCX) -> Self::KeyType;
212 }
213
214 // Implement HashStable by just calling `Hash::hash()`. This works fine for
215 // self-contained values that don't depend on the hashing context `CTX`.
216 #[macro_export]
217 macro_rules! impl_stable_hash_via_hash {
218     ($t:ty) => {
219         impl<CTX> $crate::stable_hasher::HashStable<CTX> for $t {
220             #[inline]
221             fn hash_stable(&self, _: &mut CTX, hasher: &mut $crate::stable_hasher::StableHasher) {
222                 ::std::hash::Hash::hash(self, hasher);
223             }
224         }
225     };
226 }
227
228 impl_stable_hash_via_hash!(i8);
229 impl_stable_hash_via_hash!(i16);
230 impl_stable_hash_via_hash!(i32);
231 impl_stable_hash_via_hash!(i64);
232 impl_stable_hash_via_hash!(isize);
233
234 impl_stable_hash_via_hash!(u8);
235 impl_stable_hash_via_hash!(u16);
236 impl_stable_hash_via_hash!(u32);
237 impl_stable_hash_via_hash!(u64);
238 impl_stable_hash_via_hash!(usize);
239
240 impl_stable_hash_via_hash!(u128);
241 impl_stable_hash_via_hash!(i128);
242
243 impl_stable_hash_via_hash!(char);
244 impl_stable_hash_via_hash!(());
245
246 impl<CTX> HashStable<CTX> for ! {
247     fn hash_stable(&self, _ctx: &mut CTX, _hasher: &mut StableHasher) {
248         unreachable!()
249     }
250 }
251
252 impl<CTX> HashStable<CTX> for ::std::num::NonZeroU32 {
253     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
254         self.get().hash_stable(ctx, hasher)
255     }
256 }
257
258 impl<CTX> HashStable<CTX> for ::std::num::NonZeroUsize {
259     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
260         self.get().hash_stable(ctx, hasher)
261     }
262 }
263
264 impl<CTX> HashStable<CTX> for f32 {
265     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
266         let val: u32 = unsafe { ::std::mem::transmute(*self) };
267         val.hash_stable(ctx, hasher);
268     }
269 }
270
271 impl<CTX> HashStable<CTX> for f64 {
272     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
273         let val: u64 = unsafe { ::std::mem::transmute(*self) };
274         val.hash_stable(ctx, hasher);
275     }
276 }
277
278 impl<CTX> HashStable<CTX> for ::std::cmp::Ordering {
279     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
280         (*self as i8).hash_stable(ctx, hasher);
281     }
282 }
283
284 impl<T1: HashStable<CTX>, CTX> HashStable<CTX> for (T1,) {
285     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
286         let (ref _0,) = *self;
287         _0.hash_stable(ctx, hasher);
288     }
289 }
290
291 impl<T1: HashStable<CTX>, T2: HashStable<CTX>, CTX> HashStable<CTX> for (T1, T2) {
292     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
293         let (ref _0, ref _1) = *self;
294         _0.hash_stable(ctx, hasher);
295         _1.hash_stable(ctx, hasher);
296     }
297 }
298
299 impl<T1, T2, T3, CTX> HashStable<CTX> for (T1, T2, T3)
300 where
301     T1: HashStable<CTX>,
302     T2: HashStable<CTX>,
303     T3: HashStable<CTX>,
304 {
305     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
306         let (ref _0, ref _1, ref _2) = *self;
307         _0.hash_stable(ctx, hasher);
308         _1.hash_stable(ctx, hasher);
309         _2.hash_stable(ctx, hasher);
310     }
311 }
312
313 impl<T1, T2, T3, T4, CTX> HashStable<CTX> for (T1, T2, T3, T4)
314 where
315     T1: HashStable<CTX>,
316     T2: HashStable<CTX>,
317     T3: HashStable<CTX>,
318     T4: HashStable<CTX>,
319 {
320     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
321         let (ref _0, ref _1, ref _2, ref _3) = *self;
322         _0.hash_stable(ctx, hasher);
323         _1.hash_stable(ctx, hasher);
324         _2.hash_stable(ctx, hasher);
325         _3.hash_stable(ctx, hasher);
326     }
327 }
328
329 impl<T: HashStable<CTX>, CTX> HashStable<CTX> for [T] {
330     default fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
331         self.len().hash_stable(ctx, hasher);
332         for item in self {
333             item.hash_stable(ctx, hasher);
334         }
335     }
336 }
337
338 impl<CTX> HashStable<CTX> for [u8] {
339     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
340         self.len().hash_stable(ctx, hasher);
341         hasher.write(self);
342     }
343 }
344
345 impl<T: HashStable<CTX>, CTX> HashStable<CTX> for Vec<T> {
346     #[inline]
347     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
348         (&self[..]).hash_stable(ctx, hasher);
349     }
350 }
351
352 impl<K, V, R, CTX> HashStable<CTX> for indexmap::IndexMap<K, V, R>
353 where
354     K: HashStable<CTX> + Eq + Hash,
355     V: HashStable<CTX>,
356     R: BuildHasher,
357 {
358     #[inline]
359     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
360         self.len().hash_stable(ctx, hasher);
361         for kv in self {
362             kv.hash_stable(ctx, hasher);
363         }
364     }
365 }
366
367 impl<K, R, CTX> HashStable<CTX> for indexmap::IndexSet<K, R>
368 where
369     K: HashStable<CTX> + Eq + Hash,
370     R: BuildHasher,
371 {
372     #[inline]
373     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
374         self.len().hash_stable(ctx, hasher);
375         for key in self {
376             key.hash_stable(ctx, hasher);
377         }
378     }
379 }
380
381 impl<A, CTX> HashStable<CTX> for SmallVec<[A; 1]>
382 where
383     A: HashStable<CTX>,
384 {
385     #[inline]
386     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
387         (&self[..]).hash_stable(ctx, hasher);
388     }
389 }
390
391 impl<T: ?Sized + HashStable<CTX>, CTX> HashStable<CTX> for Box<T> {
392     #[inline]
393     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
394         (**self).hash_stable(ctx, hasher);
395     }
396 }
397
398 impl<T: ?Sized + HashStable<CTX>, CTX> HashStable<CTX> for ::std::rc::Rc<T> {
399     #[inline]
400     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
401         (**self).hash_stable(ctx, hasher);
402     }
403 }
404
405 impl<T: ?Sized + HashStable<CTX>, CTX> HashStable<CTX> for ::std::sync::Arc<T> {
406     #[inline]
407     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
408         (**self).hash_stable(ctx, hasher);
409     }
410 }
411
412 impl<CTX> HashStable<CTX> for str {
413     #[inline]
414     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
415         self.as_bytes().hash_stable(ctx, hasher);
416     }
417 }
418
419 impl<CTX> HashStable<CTX> for String {
420     #[inline]
421     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
422         (&self[..]).hash_stable(hcx, hasher);
423     }
424 }
425
426 impl<HCX> ToStableHashKey<HCX> for String {
427     type KeyType = String;
428     #[inline]
429     fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType {
430         self.clone()
431     }
432 }
433
434 impl<CTX> HashStable<CTX> for bool {
435     #[inline]
436     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
437         (if *self { 1u8 } else { 0u8 }).hash_stable(ctx, hasher);
438     }
439 }
440
441 impl<T, CTX> HashStable<CTX> for Option<T>
442 where
443     T: HashStable<CTX>,
444 {
445     #[inline]
446     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
447         if let Some(ref value) = *self {
448             1u8.hash_stable(ctx, hasher);
449             value.hash_stable(ctx, hasher);
450         } else {
451             0u8.hash_stable(ctx, hasher);
452         }
453     }
454 }
455
456 impl<T1, T2, CTX> HashStable<CTX> for Result<T1, T2>
457 where
458     T1: HashStable<CTX>,
459     T2: HashStable<CTX>,
460 {
461     #[inline]
462     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
463         mem::discriminant(self).hash_stable(ctx, hasher);
464         match *self {
465             Ok(ref x) => x.hash_stable(ctx, hasher),
466             Err(ref x) => x.hash_stable(ctx, hasher),
467         }
468     }
469 }
470
471 impl<'a, T, CTX> HashStable<CTX> for &'a T
472 where
473     T: HashStable<CTX> + ?Sized,
474 {
475     #[inline]
476     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
477         (**self).hash_stable(ctx, hasher);
478     }
479 }
480
481 impl<T, CTX> HashStable<CTX> for ::std::mem::Discriminant<T> {
482     #[inline]
483     fn hash_stable(&self, _: &mut CTX, hasher: &mut StableHasher) {
484         ::std::hash::Hash::hash(self, hasher);
485     }
486 }
487
488 impl<T, CTX> HashStable<CTX> for ::std::ops::RangeInclusive<T>
489 where
490     T: HashStable<CTX>,
491 {
492     #[inline]
493     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
494         self.start().hash_stable(ctx, hasher);
495         self.end().hash_stable(ctx, hasher);
496     }
497 }
498
499 impl<I: vec::Idx, T, CTX> HashStable<CTX> for vec::IndexVec<I, T>
500 where
501     T: HashStable<CTX>,
502 {
503     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
504         self.len().hash_stable(ctx, hasher);
505         for v in &self.raw {
506             v.hash_stable(ctx, hasher);
507         }
508     }
509 }
510
511 impl<I: vec::Idx, CTX> HashStable<CTX> for bit_set::BitSet<I> {
512     fn hash_stable(&self, _ctx: &mut CTX, hasher: &mut StableHasher) {
513         ::std::hash::Hash::hash(self, hasher);
514     }
515 }
516
517 impl<R: vec::Idx, C: vec::Idx, CTX> HashStable<CTX> for bit_set::BitMatrix<R, C> {
518     fn hash_stable(&self, _ctx: &mut CTX, hasher: &mut StableHasher) {
519         ::std::hash::Hash::hash(self, hasher);
520     }
521 }
522
523 impl<T, CTX> HashStable<CTX> for bit_set::FiniteBitSet<T>
524 where
525     T: HashStable<CTX> + bit_set::FiniteBitSetTy,
526 {
527     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
528         self.0.hash_stable(hcx, hasher);
529     }
530 }
531
532 impl_stable_hash_via_hash!(::std::path::Path);
533 impl_stable_hash_via_hash!(::std::path::PathBuf);
534
535 impl<K, V, R, HCX> HashStable<HCX> for ::std::collections::HashMap<K, V, R>
536 where
537     K: ToStableHashKey<HCX> + Eq,
538     V: HashStable<HCX>,
539     R: BuildHasher,
540 {
541     #[inline]
542     fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
543         stable_hash_reduce(hcx, hasher, self.iter(), self.len(), |hasher, hcx, (key, value)| {
544             let key = key.to_stable_hash_key(hcx);
545             key.hash_stable(hcx, hasher);
546             value.hash_stable(hcx, hasher);
547         });
548     }
549 }
550
551 impl<K, R, HCX> HashStable<HCX> for ::std::collections::HashSet<K, R>
552 where
553     K: ToStableHashKey<HCX> + Eq,
554     R: BuildHasher,
555 {
556     fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
557         stable_hash_reduce(hcx, hasher, self.iter(), self.len(), |hasher, hcx, key| {
558             let key = key.to_stable_hash_key(hcx);
559             key.hash_stable(hcx, hasher);
560         });
561     }
562 }
563
564 impl<K, V, HCX> HashStable<HCX> for ::std::collections::BTreeMap<K, V>
565 where
566     K: ToStableHashKey<HCX>,
567     V: HashStable<HCX>,
568 {
569     fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
570         stable_hash_reduce(hcx, hasher, self.iter(), self.len(), |hasher, hcx, (key, value)| {
571             let key = key.to_stable_hash_key(hcx);
572             key.hash_stable(hcx, hasher);
573             value.hash_stable(hcx, hasher);
574         });
575     }
576 }
577
578 impl<K, HCX> HashStable<HCX> for ::std::collections::BTreeSet<K>
579 where
580     K: ToStableHashKey<HCX>,
581 {
582     fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) {
583         stable_hash_reduce(hcx, hasher, self.iter(), self.len(), |hasher, hcx, key| {
584             let key = key.to_stable_hash_key(hcx);
585             key.hash_stable(hcx, hasher);
586         });
587     }
588 }
589
590 fn stable_hash_reduce<HCX, I, C, F>(
591     hcx: &mut HCX,
592     hasher: &mut StableHasher,
593     mut collection: C,
594     length: usize,
595     hash_function: F,
596 ) where
597     C: Iterator<Item = I>,
598     F: Fn(&mut StableHasher, &mut HCX, I),
599 {
600     length.hash_stable(hcx, hasher);
601
602     match length {
603         1 => {
604             hash_function(hasher, hcx, collection.next().unwrap());
605         }
606         _ => {
607             let hash = collection
608                 .map(|value| {
609                     let mut hasher = StableHasher::new();
610                     hash_function(&mut hasher, hcx, value);
611                     hasher.finish::<u128>()
612                 })
613                 .reduce(|accum, value| accum.wrapping_add(value));
614             hash.hash_stable(hcx, hasher);
615         }
616     }
617 }
618
619 #[derive(PartialEq, Eq, Clone, Copy, Hash, Debug)]
620 pub enum NodeIdHashingMode {
621     Ignore,
622     HashDefPath,
623 }
624
625 /// Controls what data we do or not not hash.
626 /// Whenever a `HashStable` implementation caches its
627 /// result, it needs to include `HashingControls` as part
628 /// of the key, to ensure that is does not produce an incorrect
629 /// result (for example, using a `Fingerprint` produced while
630 /// hashing `Span`s when a `Fingeprint` without `Span`s is
631 /// being requested)
632 #[derive(Clone, Hash, Eq, PartialEq, Debug)]
633 pub struct HashingControls {
634     pub hash_spans: bool,
635     pub node_id_hashing_mode: NodeIdHashingMode,
636 }