1 use crate::sip128::SipHasher128;
2 use rustc_index::bit_set;
4 use smallvec::SmallVec;
5 use std::hash::{BuildHasher, Hash, Hasher};
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*.
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 {
22 impl ::std::fmt::Debug for StableHasher {
23 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24 write!(f, "{:?}", self.state)
28 pub trait StableHasherResult: Sized {
29 fn finish(hasher: StableHasher) -> Self;
34 pub fn new() -> Self {
35 StableHasher { state: SipHasher128::new_with_keys(0, 0) }
39 pub fn finish<W: StableHasherResult>(self) -> W {
44 impl StableHasherResult for u128 {
46 fn finish(hasher: StableHasher) -> Self {
47 let (_0, _1) = hasher.finalize();
48 u128::from(_0) | (u128::from(_1) << 64)
52 impl StableHasherResult for u64 {
54 fn finish(hasher: StableHasher) -> Self {
61 pub fn finalize(self) -> (u64, u64) {
62 self.state.finish128()
66 impl Hasher for StableHasher {
67 fn finish(&self) -> u64 {
68 panic!("use StableHasher::finalize instead");
72 fn write(&mut self, bytes: &[u8]) {
73 self.state.write(bytes);
77 fn write_u8(&mut self, i: u8) {
78 self.state.write_u8(i);
82 fn write_u16(&mut self, i: u16) {
83 self.state.short_write(i.to_le_bytes());
87 fn write_u32(&mut self, i: u32) {
88 self.state.short_write(i.to_le_bytes());
92 fn write_u64(&mut self, i: u64) {
93 self.state.short_write(i.to_le_bytes());
97 fn write_u128(&mut self, i: u128) {
98 self.state.write(&i.to_le_bytes());
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,
106 self.state.short_write((i as u64).to_le_bytes());
110 fn write_i8(&mut self, i: i8) {
111 self.state.write_i8(i);
115 fn write_i16(&mut self, i: i16) {
116 self.state.short_write((i as u16).to_le_bytes());
120 fn write_i32(&mut self, i: i32) {
121 self.state.short_write((i as u32).to_le_bytes());
125 fn write_i64(&mut self, i: i64) {
126 self.state.short_write((i as u64).to_le_bytes());
130 fn write_i128(&mut self, i: i128) {
131 self.state.write(&(i as u128).to_le_bytes());
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;
145 fn hash_value(state: &mut SipHasher128, value: u64) {
146 state.write_u8(0xFF);
147 state.short_write(value.to_le_bytes());
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.
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.
165 self.state.write_u8(value as u8);
167 hash_value(&mut self.state, value);
172 /// Something that implements `HashStable<CTX>` can be hashed in a way that is
173 /// stable across multiple compilation sessions.
175 /// Note that `HashStable` imposes rather more strict requirements than usual
178 /// - Stable hashes are sometimes used as identifiers. Therefore they must
179 /// conform to the corresponding `PartialEq` implementations:
181 /// - `x == y` implies `hash_stable(x) == hash_stable(y)`, and
182 /// - `x != y` implies `hash_stable(x) != hash_stable(y)`.
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
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.
195 /// - `hash_stable()` must be independent of the host architecture. The
196 /// `StableHasher` takes care of endianness and `isize`/`usize` platform
198 pub trait HashStable<CTX> {
199 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher);
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;
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`.
213 macro_rules! impl_stable_hash_via_hash {
215 impl<CTX> $crate::stable_hasher::HashStable<CTX> for $t {
217 fn hash_stable(&self, _: &mut CTX, hasher: &mut $crate::stable_hasher::StableHasher) {
218 ::std::hash::Hash::hash(self, hasher);
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);
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);
236 impl_stable_hash_via_hash!(u128);
237 impl_stable_hash_via_hash!(i128);
239 impl_stable_hash_via_hash!(char);
240 impl_stable_hash_via_hash!(());
242 impl<CTX> HashStable<CTX> for ! {
243 fn hash_stable(&self, _ctx: &mut CTX, _hasher: &mut StableHasher) {
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)
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)
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);
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);
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);
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);
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);
295 impl<T1, T2, T3, CTX> HashStable<CTX> for (T1, T2, T3)
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);
309 impl<T1, T2, T3, T4, CTX> HashStable<CTX> for (T1, T2, T3, T4)
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);
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);
329 item.hash_stable(ctx, hasher);
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);
341 impl<T: HashStable<CTX>, CTX> HashStable<CTX> for Vec<T> {
343 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
344 (&self[..]).hash_stable(ctx, hasher);
348 impl<K, V, R, CTX> HashStable<CTX> for indexmap::IndexMap<K, V, R>
350 K: HashStable<CTX> + Eq + Hash,
355 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
356 self.len().hash_stable(ctx, hasher);
358 kv.hash_stable(ctx, hasher);
363 impl<K, R, CTX> HashStable<CTX> for indexmap::IndexSet<K, R>
365 K: HashStable<CTX> + Eq + Hash,
369 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
370 self.len().hash_stable(ctx, hasher);
372 key.hash_stable(ctx, hasher);
377 impl<A, CTX> HashStable<CTX> for SmallVec<[A; 1]>
382 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
383 (&self[..]).hash_stable(ctx, hasher);
387 impl<T: ?Sized + HashStable<CTX>, CTX> HashStable<CTX> for Box<T> {
389 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
390 (**self).hash_stable(ctx, hasher);
394 impl<T: ?Sized + HashStable<CTX>, CTX> HashStable<CTX> for ::std::rc::Rc<T> {
396 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
397 (**self).hash_stable(ctx, hasher);
401 impl<T: ?Sized + HashStable<CTX>, CTX> HashStable<CTX> for ::std::sync::Arc<T> {
403 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
404 (**self).hash_stable(ctx, hasher);
408 impl<CTX> HashStable<CTX> for str {
410 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
411 self.as_bytes().hash_stable(ctx, hasher);
415 impl<CTX> HashStable<CTX> for String {
417 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
418 (&self[..]).hash_stable(hcx, hasher);
422 impl<HCX> ToStableHashKey<HCX> for String {
423 type KeyType = String;
425 fn to_stable_hash_key(&self, _: &HCX) -> Self::KeyType {
430 impl<CTX> HashStable<CTX> for bool {
432 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
433 (if *self { 1u8 } else { 0u8 }).hash_stable(ctx, hasher);
437 impl<T, CTX> HashStable<CTX> for Option<T>
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);
447 0u8.hash_stable(ctx, hasher);
452 impl<T1, T2, CTX> HashStable<CTX> for Result<T1, T2>
458 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
459 mem::discriminant(self).hash_stable(ctx, hasher);
461 Ok(ref x) => x.hash_stable(ctx, hasher),
462 Err(ref x) => x.hash_stable(ctx, hasher),
467 impl<'a, T, CTX> HashStable<CTX> for &'a T
469 T: HashStable<CTX> + ?Sized,
472 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
473 (**self).hash_stable(ctx, hasher);
477 impl<T, CTX> HashStable<CTX> for ::std::mem::Discriminant<T> {
479 fn hash_stable(&self, _: &mut CTX, hasher: &mut StableHasher) {
480 ::std::hash::Hash::hash(self, hasher);
484 impl<T, CTX> HashStable<CTX> for ::std::ops::RangeInclusive<T>
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);
495 impl<I: vec::Idx, T, CTX> HashStable<CTX> for vec::IndexVec<I, T>
499 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
500 self.len().hash_stable(ctx, hasher);
502 v.hash_stable(ctx, hasher);
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);
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);
519 impl<T, CTX> HashStable<CTX> for bit_set::FiniteBitSet<T>
521 T: HashStable<CTX> + bit_set::FiniteBitSetTy,
523 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
524 self.0.hash_stable(hcx, hasher);
528 impl_stable_hash_via_hash!(::std::path::Path);
529 impl_stable_hash_via_hash!(::std::path::PathBuf);
531 impl<K, V, R, HCX> HashStable<HCX> for ::std::collections::HashMap<K, V, R>
533 K: ToStableHashKey<HCX> + Eq,
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);
547 impl<K, R, HCX> HashStable<HCX> for ::std::collections::HashSet<K, R>
549 K: ToStableHashKey<HCX> + Eq,
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);
560 impl<K, V, HCX> HashStable<HCX> for ::std::collections::BTreeMap<K, V>
562 K: ToStableHashKey<HCX>,
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);
574 impl<K, HCX> HashStable<HCX> for ::std::collections::BTreeSet<K>
576 K: ToStableHashKey<HCX>,
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);
586 fn stable_hash_reduce<HCX, I, C, F>(
588 hasher: &mut StableHasher,
593 C: Iterator<Item = I>,
594 F: Fn(&mut StableHasher, &mut HCX, I),
596 length.hash_stable(hcx, hasher);
600 hash_function(hasher, hcx, collection.next().unwrap());
603 let hash = collection
605 let mut hasher = StableHasher::new();
606 hash_function(&mut hasher, hcx, value);
607 hasher.finish::<u128>()
609 .reduce(|accum, value| accum.wrapping_add(value));
610 hash.hash_stable(hcx, hasher);
615 #[derive(PartialEq, Eq, Clone, Copy, Hash, Debug)]
616 pub enum NodeIdHashingMode {
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
628 #[derive(Clone, Hash, Eq, PartialEq, Debug)]
629 pub struct HashingControls {
630 pub hash_spans: bool,
631 pub node_id_hashing_mode: NodeIdHashingMode,