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