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