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