Skip to main content

rustc_data_structures/
stable_hash.rs

1use std::ffi::OsStr;
2use std::hash::{BuildHasher, Hasher};
3use std::marker::PhantomData;
4use std::num::NonZero;
5
6use rustc_hashes::{Hash64, Hash128};
7use rustc_index::{Idx, IndexSlice, IndexVec, bit_set};
8use rustc_macros::StableHash;
9pub use rustc_stable_hash::{
10    FromStableHash, SipHasher128Hash as StableHasherHash, StableSipHasher128 as StableHasher,
11};
12use smallvec::SmallVec;
13use thin_vec::ThinVec;
14
15use crate::fingerprint::Fingerprint;
16
17#[cfg(test)]
18mod tests;
19
20/// This trait lets `StableHash` and `derive(StableHash)` be used in
21/// this crate (and other crates upstream of `rustc_middle`), while leaving
22/// certain operations to be defined in `rustc_middle` where more things are
23/// visible.
24pub trait StableHashCtxt {
25    /// The main event: stable hashing of a span.
26    fn stable_hash_span(&mut self, span: RawSpan, hasher: &mut StableHasher);
27
28    /// Compute a `Fingerprint`, which can be trivially turned into a `DefPathHash`.
29    fn def_path_hash(&self, def_id: RawDefId) -> Fingerprint;
30
31    /// Get the stable hash controls.
32    fn stable_hash_controls(&self) -> StableHashControls;
33
34    /// Assert that the provided `StableHashCtxt` is configured with the default
35    /// `StableHashControls`. We should always have bailed out before getting to here with a
36    fn assert_default_stable_hash_controls(&self, msg: &str);
37}
38
39/// Dummy impl of [`StableHashCtxt`], for code that can't provide a real context,
40/// and only wants to compute stable hashes for types that don't rely on the context.
41pub struct DummyStableHashCtxt;
42
43impl StableHashCtxt for DummyStableHashCtxt {
44    fn stable_hash_span(&mut self, _span: RawSpan, _hasher: &mut StableHasher) {
45        {
    ::core::panicking::panic_fmt(format_args!("method on dummy stable-hash context was unexpectedly called"));
};panic!("method on dummy stable-hash context was unexpectedly called");
46    }
47    fn def_path_hash(&self, _def_id: RawDefId) -> Fingerprint {
48        {
    ::core::panicking::panic_fmt(format_args!("method on dummy stable-hash context was unexpectedly called"));
};panic!("method on dummy stable-hash context was unexpectedly called");
49    }
50    fn stable_hash_controls(&self) -> StableHashControls {
51        {
    ::core::panicking::panic_fmt(format_args!("method on dummy stable-hash context was unexpectedly called"));
};panic!("method on dummy stable-hash context was unexpectedly called");
52    }
53    fn assert_default_stable_hash_controls(&self, _msg: &str) {
54        {
    ::core::panicking::panic_fmt(format_args!("method on dummy stable-hash context was unexpectedly called"));
};panic!("method on dummy stable-hash context was unexpectedly called");
55    }
56}
57
58// A type used to work around `Span` not being visible in this crate. It is the same size as
59// `Span` but has a different alignment.
60pub struct RawSpan(pub u64);
61
62// A type used to work around `DefId` not being visible in this crate. It is the same size as
63// `DefId`.
64pub struct RawDefId(pub u32, pub u32);
65
66/// Something that implements `StableHash` can be hashed in a way that is
67/// stable across multiple compilation sessions.
68///
69/// Note that `StableHash` imposes rather more strict requirements than usual
70/// hash functions:
71///
72/// - Stable hashes are sometimes used as identifiers. Therefore they must
73///   conform to the corresponding `PartialEq` implementations:
74///
75///     - `x == y` implies `stable_hash(x) == stable_hash(y)`, and
76///     - `x != y` implies `stable_hash(x) != stable_hash(y)`.
77///
78///   That second condition is usually not required for hash functions
79///   (e.g. `Hash`). In practice this means that `stable_hash` must feed any
80///   information into the hasher that a `PartialEq` comparison takes into
81///   account. See [#49300](https://github.com/rust-lang/rust/issues/49300)
82///   for an example where violating this invariant has caused trouble in the
83///   past.
84///
85/// - `stable_hash()` must be independent of the current
86///    compilation session. E.g. they must not hash memory addresses or other
87///    things that are "randomly" assigned per compilation session.
88///
89/// - `stable_hash()` must be independent of the host architecture. The
90///   `StableHasher` takes care of endianness and `isize`/`usize` platform
91///   differences.
92///
93/// # Consistency across compiler stages
94///
95/// Because the stage1 compiler is built against the bootstrap stdlib, but the stage2
96/// compiler uses in-tree stdlib, implementations of `StableHash` must not rely on `Hash`
97/// impls that were provided or derived by the standard library. Doing so leads to weird
98/// bugs and CI failures that can block changes to those stdlib hash impls.
99///
100/// (Unfortunately, as of late 2026 we have many stable-hash impls that _do_
101/// leak details of stdlib hash impls.)
102///
103/// See <https://github.com/rust-lang/rust/pull/164458> for more context.
104pub trait StableHash {
105    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher);
106}
107
108/// Implement this for types that can be turned into stable keys like, for
109/// example, for DefId that can be converted to a DefPathHash. This is used for
110/// bringing maps into a predictable order before hashing them.
111pub trait ToStableHashKey {
112    type KeyType: Ord + Sized + StableHash;
113    fn to_stable_hash_key<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx) -> Self::KeyType;
114}
115
116/// Trait for marking a type as having a sort order that is
117/// stable across compilation session boundaries. More formally:
118///
119/// ```txt
120/// Ord::cmp(a1, b1) == Ord::cmp(a2, b2)
121///    where a2 = decode(encode(a1, context1), context2)
122///          b2 = decode(encode(b1, context1), context2)
123/// ```
124///
125/// i.e. the result of `Ord::cmp` is not influenced by encoding
126/// the values in one session and then decoding them in another
127/// session.
128///
129/// This is trivially true for types where encoding and decoding
130/// don't change the bytes of the values that are used during
131/// comparison and comparison only depends on these bytes (as
132/// opposed to some non-local state). Examples are u32, String,
133/// Path, etc.
134///
135/// But it is not true for:
136///  - `*const T` and `*mut T` because the values of these pointers
137///    will change between sessions.
138///  - `DefIndex`, `CrateNum`, `LocalDefId`, because their concrete
139///    values depend on state that might be different between
140///    compilation sessions.
141///
142/// The associated constant `CAN_USE_UNSTABLE_SORT` denotes whether
143/// unstable sorting can be used for this type. Set to true if and
144/// only if `a == b` implies `a` and `b` are fully indistinguishable.
145pub trait StableOrd: Ord {
146    const CAN_USE_UNSTABLE_SORT: bool;
147
148    /// Marker to ensure that implementors have carefully considered
149    /// whether their `Ord` implementation obeys this trait's contract.
150    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: ();
151}
152
153impl<T: StableOrd> StableOrd for &T {
154    const CAN_USE_UNSTABLE_SORT: bool = T::CAN_USE_UNSTABLE_SORT;
155
156    // Ordering of a reference is exactly that of the referent, and since
157    // the ordering of the referet is stable so must be the ordering of the
158    // reference.
159    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
160}
161
162/// This is a companion trait to `StableOrd`. Some types like `Symbol` can be
163/// compared in a cross-session stable way, but their `Ord` implementation is
164/// not stable. In such cases, a `StableOrd` implementation can be provided
165/// to offer a lightweight way for stable sorting. (The more heavyweight option
166/// is to sort via `ToStableHashKey`, but then sorting needs to have access to
167/// a stable hashing context and `ToStableHashKey` can also be expensive as in
168/// the case of `Symbol` where it has to allocate a `String`.)
169///
170/// See the documentation of [StableOrd] for how stable sort order is defined.
171/// The same definition applies here. Be careful when implementing this trait.
172pub trait StableCompare {
173    const CAN_USE_UNSTABLE_SORT: bool;
174
175    fn stable_cmp(&self, other: &Self) -> std::cmp::Ordering;
176}
177
178/// `StableOrd` denotes that the type's `Ord` implementation is stable, so
179/// we can implement `StableCompare` by just delegating to `Ord`.
180impl<T: StableOrd> StableCompare for T {
181    const CAN_USE_UNSTABLE_SORT: bool = T::CAN_USE_UNSTABLE_SORT;
182
183    fn stable_cmp(&self, other: &Self) -> std::cmp::Ordering {
184        self.cmp(other)
185    }
186}
187
188/// Implements [`StableHash`] and [`StableOrd`] for a primitive integer type.
189/// The stable-hash impl calls the corresponding `Hasher::write_*` method.
190macro_rules! impl_stable_traits_for_int {
191    (
192        $ty:ty, $write_ty_method:ident
193    ) => {
194        impl StableHash for $ty {
195            #[inline]
196            fn stable_hash<Hcx>(&self, _: &mut Hcx, hasher: &mut StableHasher) {
197                hasher.$write_ty_method(*self);
198            }
199        }
200
201        impl StableOrd for $ty {
202            const CAN_USE_UNSTABLE_SORT: bool = true;
203
204            // Encoding and decoding doesn't change the bytes of trivial types
205            // and `Ord::cmp` depends only on those bytes.
206            const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
207        }
208    };
209}
210
211impl StableHash for u8 {
    #[inline]
    fn stable_hash<Hcx>(&self, _: &mut Hcx, hasher: &mut StableHasher) {
        hasher.write_u8(*self);
    }
}
impl StableOrd for u8 {
    const CAN_USE_UNSTABLE_SORT: bool = true;
    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
}impl_stable_traits_for_int!(u8, write_u8);
212impl StableHash for u16 {
    #[inline]
    fn stable_hash<Hcx>(&self, _: &mut Hcx, hasher: &mut StableHasher) {
        hasher.write_u16(*self);
    }
}
impl StableOrd for u16 {
    const CAN_USE_UNSTABLE_SORT: bool = true;
    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
}impl_stable_traits_for_int!(u16, write_u16);
213impl StableHash for u32 {
    #[inline]
    fn stable_hash<Hcx>(&self, _: &mut Hcx, hasher: &mut StableHasher) {
        hasher.write_u32(*self);
    }
}
impl StableOrd for u32 {
    const CAN_USE_UNSTABLE_SORT: bool = true;
    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
}impl_stable_traits_for_int!(u32, write_u32);
214impl StableHash for u64 {
    #[inline]
    fn stable_hash<Hcx>(&self, _: &mut Hcx, hasher: &mut StableHasher) {
        hasher.write_u64(*self);
    }
}
impl StableOrd for u64 {
    const CAN_USE_UNSTABLE_SORT: bool = true;
    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
}impl_stable_traits_for_int!(u64, write_u64);
215impl StableHash for u128 {
    #[inline]
    fn stable_hash<Hcx>(&self, _: &mut Hcx, hasher: &mut StableHasher) {
        hasher.write_u128(*self);
    }
}
impl StableOrd for u128 {
    const CAN_USE_UNSTABLE_SORT: bool = true;
    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
}impl_stable_traits_for_int!(u128, write_u128);
216impl StableHash for usize {
    #[inline]
    fn stable_hash<Hcx>(&self, _: &mut Hcx, hasher: &mut StableHasher) {
        hasher.write_usize(*self);
    }
}
impl StableOrd for usize {
    const CAN_USE_UNSTABLE_SORT: bool = true;
    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
}impl_stable_traits_for_int!(usize, write_usize);
217
218impl StableHash for i8 {
    #[inline]
    fn stable_hash<Hcx>(&self, _: &mut Hcx, hasher: &mut StableHasher) {
        hasher.write_i8(*self);
    }
}
impl StableOrd for i8 {
    const CAN_USE_UNSTABLE_SORT: bool = true;
    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
}impl_stable_traits_for_int!(i8, write_i8);
219impl StableHash for i16 {
    #[inline]
    fn stable_hash<Hcx>(&self, _: &mut Hcx, hasher: &mut StableHasher) {
        hasher.write_i16(*self);
    }
}
impl StableOrd for i16 {
    const CAN_USE_UNSTABLE_SORT: bool = true;
    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
}impl_stable_traits_for_int!(i16, write_i16);
220impl StableHash for i32 {
    #[inline]
    fn stable_hash<Hcx>(&self, _: &mut Hcx, hasher: &mut StableHasher) {
        hasher.write_i32(*self);
    }
}
impl StableOrd for i32 {
    const CAN_USE_UNSTABLE_SORT: bool = true;
    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
}impl_stable_traits_for_int!(i32, write_i32);
221impl StableHash for i64 {
    #[inline]
    fn stable_hash<Hcx>(&self, _: &mut Hcx, hasher: &mut StableHasher) {
        hasher.write_i64(*self);
    }
}
impl StableOrd for i64 {
    const CAN_USE_UNSTABLE_SORT: bool = true;
    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
}impl_stable_traits_for_int!(i64, write_i64);
222impl StableHash for i128 {
    #[inline]
    fn stable_hash<Hcx>(&self, _: &mut Hcx, hasher: &mut StableHasher) {
        hasher.write_i128(*self);
    }
}
impl StableOrd for i128 {
    const CAN_USE_UNSTABLE_SORT: bool = true;
    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
}impl_stable_traits_for_int!(i128, write_i128);
223impl StableHash for isize {
    #[inline]
    fn stable_hash<Hcx>(&self, _: &mut Hcx, hasher: &mut StableHasher) {
        hasher.write_isize(*self);
    }
}
impl StableOrd for isize {
    const CAN_USE_UNSTABLE_SORT: bool = true;
    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
}impl_stable_traits_for_int!(isize, write_isize);
224
225impl StableHash for char {
226    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
227        u32::from(*self).stable_hash(hcx, hasher);
228    }
229}
230
231impl StableHash for () {
232    fn stable_hash<Hcx: StableHashCtxt>(&self, _hcx: &mut Hcx, _hasher: &mut StableHasher) {
233        // No need to hash anything for the unit type.
234    }
235}
236
237impl StableHash for Hash64 {
238    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
239        self.as_u64().stable_hash(hcx, hasher);
240    }
241}
242
243impl StableHash for Hash128 {
244    #[inline]
245    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
246        self.as_u128().stable_hash(hcx, hasher);
247    }
248}
249
250impl StableOrd for Hash128 {
251    const CAN_USE_UNSTABLE_SORT: bool = true;
252
253    // Encoding and decoding doesn't change the bytes of `Hash128`
254    // and `Ord::cmp` depends only on those bytes.
255    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
256}
257
258impl StableHash for ! {
259    fn stable_hash<Hcx>(&self, _hcx: &mut Hcx, _hasher: &mut StableHasher) {
260        ::core::panicking::unreachable_default_msg()unreachable!()
261    }
262}
263
264impl<T> StableHash for PhantomData<T> {
265    fn stable_hash<Hcx>(&self, _hcx: &mut Hcx, _hasher: &mut StableHasher) {}
266}
267
268impl<T: StableHash + std::num::ZeroablePrimitive> StableHash for NonZero<T> {
269    #[inline]
270    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
271        self.get().stable_hash(hcx, hasher)
272    }
273}
274
275impl StableHash for f32 {
276    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
277        let val: u32 = self.to_bits();
278        val.stable_hash(hcx, hasher);
279    }
280}
281
282impl StableHash for f64 {
283    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
284        let val: u64 = self.to_bits();
285        val.stable_hash(hcx, hasher);
286    }
287}
288
289impl StableHash for ::std::cmp::Ordering {
290    #[inline]
291    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
292        (*self as i8).stable_hash(hcx, hasher);
293    }
294}
295
296impl<T1: StableHash> StableHash for (T1,) {
297    #[inline]
298    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
299        let (ref _0,) = *self;
300        _0.stable_hash(hcx, hasher);
301    }
302}
303
304impl<T1: StableHash, T2: StableHash> StableHash for (T1, T2) {
305    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
306        let (ref _0, ref _1) = *self;
307        _0.stable_hash(hcx, hasher);
308        _1.stable_hash(hcx, hasher);
309    }
310}
311
312impl<T1: StableOrd, T2: StableOrd> StableOrd for (T1, T2) {
313    const CAN_USE_UNSTABLE_SORT: bool = T1::CAN_USE_UNSTABLE_SORT && T2::CAN_USE_UNSTABLE_SORT;
314
315    // Ordering of tuples is a pure function of their elements' ordering, and since
316    // the ordering of each element is stable so must be the ordering of the tuple.
317    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
318}
319
320impl<T1, T2, T3> StableHash for (T1, T2, T3)
321where
322    T1: StableHash,
323    T2: StableHash,
324    T3: StableHash,
325{
326    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
327        let (ref _0, ref _1, ref _2) = *self;
328        _0.stable_hash(hcx, hasher);
329        _1.stable_hash(hcx, hasher);
330        _2.stable_hash(hcx, hasher);
331    }
332}
333
334impl<T1: StableOrd, T2: StableOrd, T3: StableOrd> StableOrd for (T1, T2, T3) {
335    const CAN_USE_UNSTABLE_SORT: bool =
336        T1::CAN_USE_UNSTABLE_SORT && T2::CAN_USE_UNSTABLE_SORT && T3::CAN_USE_UNSTABLE_SORT;
337
338    // Ordering of tuples is a pure function of their elements' ordering, and since
339    // the ordering of each element is stable so must be the ordering of the tuple.
340    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
341}
342
343impl<T1, T2, T3, T4> StableHash for (T1, T2, T3, T4)
344where
345    T1: StableHash,
346    T2: StableHash,
347    T3: StableHash,
348    T4: StableHash,
349{
350    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
351        let (ref _0, ref _1, ref _2, ref _3) = *self;
352        _0.stable_hash(hcx, hasher);
353        _1.stable_hash(hcx, hasher);
354        _2.stable_hash(hcx, hasher);
355        _3.stable_hash(hcx, hasher);
356    }
357}
358
359impl<T1: StableOrd, T2: StableOrd, T3: StableOrd, T4: StableOrd> StableOrd for (T1, T2, T3, T4) {
360    const CAN_USE_UNSTABLE_SORT: bool = T1::CAN_USE_UNSTABLE_SORT
361        && T2::CAN_USE_UNSTABLE_SORT
362        && T3::CAN_USE_UNSTABLE_SORT
363        && T4::CAN_USE_UNSTABLE_SORT;
364
365    // Ordering of tuples is a pure function of their elements' ordering, and since
366    // the ordering of each element is stable so must be the ordering of the tuple.
367    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
368}
369
370impl<T: StableHash> StableHash for [T] {
371    default fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
372        self.len().stable_hash(hcx, hasher);
373        for item in self {
374            item.stable_hash(hcx, hasher);
375        }
376    }
377}
378
379impl StableHash for [u8] {
380    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
381        self.len().stable_hash(hcx, hasher);
382        hasher.write(self);
383    }
384}
385
386impl<T: StableHash> StableHash for Vec<T> {
387    #[inline]
388    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
389        self[..].stable_hash(hcx, hasher);
390    }
391}
392
393impl<K, V, R> StableHash for indexmap::IndexMap<K, V, R>
394where
395    K: StableHash,
396    V: StableHash,
397    R: BuildHasher,
398{
399    #[inline]
400    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
401        self.len().stable_hash(hcx, hasher);
402        for kv in self {
403            kv.stable_hash(hcx, hasher);
404        }
405    }
406}
407
408impl<K, R> StableHash for indexmap::IndexSet<K, R>
409where
410    K: StableHash,
411    R: BuildHasher,
412{
413    #[inline]
414    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
415        self.len().stable_hash(hcx, hasher);
416        for key in self {
417            key.stable_hash(hcx, hasher);
418        }
419    }
420}
421
422impl<A, const N: usize> StableHash for SmallVec<[A; N]>
423where
424    A: StableHash,
425{
426    #[inline]
427    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
428        self[..].stable_hash(hcx, hasher);
429    }
430}
431
432impl<T: StableHash> StableHash for ThinVec<T> {
433    #[inline]
434    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
435        self[..].stable_hash(hcx, hasher);
436    }
437}
438
439impl<T: ?Sized + StableHash> StableHash for Box<T> {
440    #[inline]
441    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
442        (**self).stable_hash(hcx, hasher);
443    }
444}
445
446impl<T: ?Sized + StableHash> StableHash for ::std::rc::Rc<T> {
447    #[inline]
448    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
449        (**self).stable_hash(hcx, hasher);
450    }
451}
452
453impl<T: ?Sized + StableHash> StableHash for ::std::sync::Arc<T> {
454    #[inline]
455    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
456        (**self).stable_hash(hcx, hasher);
457    }
458}
459
460impl StableHash for str {
461    #[inline]
462    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
463        self.as_bytes().stable_hash(hcx, hasher);
464    }
465}
466
467impl StableOrd for &str {
468    const CAN_USE_UNSTABLE_SORT: bool = true;
469
470    // Encoding and decoding doesn't change the bytes of string slices
471    // and `Ord::cmp` depends only on those bytes.
472    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
473}
474
475impl StableHash for String {
476    #[inline]
477    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
478        self[..].stable_hash(hcx, hasher);
479    }
480}
481
482impl StableOrd for String {
483    const CAN_USE_UNSTABLE_SORT: bool = true;
484
485    // String comparison only depends on their contents and the
486    // contents are not changed by (de-)serialization.
487    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
488}
489
490impl StableHash for bool {
491    #[inline]
492    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
493        (if *self { 1u8 } else { 0u8 }).stable_hash(hcx, hasher);
494    }
495}
496
497impl StableOrd for bool {
498    const CAN_USE_UNSTABLE_SORT: bool = true;
499
500    // sort order of bools is not changed by (de-)serialization.
501    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
502}
503
504impl<T> StableHash for Option<T>
505where
506    T: StableHash,
507{
508    #[inline]
509    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
510        if let Some(ref value) = *self {
511            1u8.stable_hash(hcx, hasher);
512            value.stable_hash(hcx, hasher);
513        } else {
514            0u8.stable_hash(hcx, hasher);
515        }
516    }
517}
518
519impl<T: StableOrd> StableOrd for Option<T> {
520    const CAN_USE_UNSTABLE_SORT: bool = T::CAN_USE_UNSTABLE_SORT;
521
522    // the Option wrapper does not add instability to comparison.
523    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
524}
525
526impl<T1, T2> StableHash for Result<T1, T2>
527where
528    T1: StableHash,
529    T2: StableHash,
530{
531    #[inline]
532    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
533        #[derive(const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for Tag {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    Tag::Ok => 0u8.stable_hash(__hcx, __hasher),
                    Tag::Err => 1u8.stable_hash(__hcx, __hasher),
                }
                match *self { Tag::Ok => {} Tag::Err => {} }
            }
        }
    };StableHash)]
534        enum Tag {
535            Ok,
536            Err,
537        }
538        match *self {
539            Ok(ref x) => {
540                Tag::Ok.stable_hash(hcx, hasher);
541                x.stable_hash(hcx, hasher);
542            }
543            Err(ref x) => {
544                Tag::Err.stable_hash(hcx, hasher);
545                x.stable_hash(hcx, hasher);
546            }
547        }
548    }
549}
550
551impl<'a, T> StableHash for &'a T
552where
553    T: StableHash + ?Sized,
554{
555    #[inline]
556    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
557        (**self).stable_hash(hcx, hasher);
558    }
559}
560
561/// There is no way to stable-hash a `Discriminant` without leaking unstable
562/// details of how the host compiler chooses and hashes discriminants.
563///
564/// That would be bad, because stable hashes must be consistent between
565/// the stage1 compiler (built with the bootstrap compiler/stdlib)
566/// and the stage2 compiler (built with the in-tree compiler/stdlib).
567///
568/// See <https://github.com/rust-lang/rust/issues/164734> for more context.
569///
570/// If you need to manually stable-hash a discriminant, instead derive `StableHash`
571/// on a dedicated "tag" enum, and then hash the appropriate tag for each variant.
572/// For an example, see the impl of `StableHash for Result`.
573impl<T> !StableHash for std::mem::Discriminant<T> {}
574
575impl<T> StableHash for ::std::range::RangeInclusive<T>
576where
577    T: StableHash,
578{
579    #[inline]
580    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
581        self.start.stable_hash(hcx, hasher);
582        self.last.stable_hash(hcx, hasher);
583    }
584}
585
586impl<I: Idx, T> StableHash for IndexSlice<I, T>
587where
588    T: StableHash,
589{
590    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
591        self.len().stable_hash(hcx, hasher);
592        for v in &self.raw {
593            v.stable_hash(hcx, hasher);
594        }
595    }
596}
597
598impl<I: Idx, T> StableHash for IndexVec<I, T>
599where
600    T: StableHash,
601{
602    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
603        self.len().stable_hash(hcx, hasher);
604        for v in &self.raw {
605            v.stable_hash(hcx, hasher);
606        }
607    }
608}
609
610impl<I: Idx> StableHash for bit_set::DenseBitSet<I> {
611    fn stable_hash<Hcx: StableHashCtxt>(&self, _hcx: &mut Hcx, hasher: &mut StableHasher) {
612        bit_set::DenseBitSet::stable_hash_inner(self, hasher);
613    }
614}
615
616impl<R: Idx, C: Idx> StableHash for bit_set::BitMatrix<R, C> {
617    fn stable_hash<Hcx: StableHashCtxt>(&self, _hcx: &mut Hcx, hasher: &mut StableHasher) {
618        bit_set::BitMatrix::stable_hash_inner(self, hasher);
619    }
620}
621
622impl StableHash for OsStr {
623    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
624        self.as_encoded_bytes().stable_hash(hcx, hasher);
625    }
626}
627
628impl StableHash for std::path::Path {
629    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
630        use std::path::{Component, Prefix};
631
632        /// Tag value to be mixed in with each kind of component/prefix.
633        #[derive(const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for Tag {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    Tag::StartOfPath => 0u8.stable_hash(__hcx, __hasher),
                    Tag::PrefixVerbatim => 1u8.stable_hash(__hcx, __hasher),
                    Tag::PrefixVerbatimUNC => 2u8.stable_hash(__hcx, __hasher),
                    Tag::PrefixVerbatimDisk => 3u8.stable_hash(__hcx, __hasher),
                    Tag::PrefixDeviceNS => 4u8.stable_hash(__hcx, __hasher),
                    Tag::PrefixUNC => 5u8.stable_hash(__hcx, __hasher),
                    Tag::PrefixDisk => 6u8.stable_hash(__hcx, __hasher),
                    Tag::RootDir => 7u8.stable_hash(__hcx, __hasher),
                    Tag::CurDir => 8u8.stable_hash(__hcx, __hasher),
                    Tag::ParentDir => 9u8.stable_hash(__hcx, __hasher),
                    Tag::Normal => 10u8.stable_hash(__hcx, __hasher),
                    Tag::EndOfPath => 11u8.stable_hash(__hcx, __hasher),
                }
                match *self {
                    Tag::StartOfPath => {}
                    Tag::PrefixVerbatim => {}
                    Tag::PrefixVerbatimUNC => {}
                    Tag::PrefixVerbatimDisk => {}
                    Tag::PrefixDeviceNS => {}
                    Tag::PrefixUNC => {}
                    Tag::PrefixDisk => {}
                    Tag::RootDir => {}
                    Tag::CurDir => {}
                    Tag::ParentDir => {}
                    Tag::Normal => {}
                    Tag::EndOfPath => {}
                }
            }
        }
    };StableHash)]
634        enum Tag {
635            StartOfPath,
636            PrefixVerbatim,
637            PrefixVerbatimUNC,
638            PrefixVerbatimDisk,
639            PrefixDeviceNS,
640            PrefixUNC,
641            PrefixDisk,
642            RootDir,
643            CurDir,
644            ParentDir,
645            Normal,
646            EndOfPath,
647        }
648
649        // Explicitly tag the start of each path, so that empty paths always hash something.
650        Tag::StartOfPath.stable_hash(hcx, hasher);
651
652        for (i, component) in self.components().enumerate() {
653            // Mix in the index of each component, to avoid potentially trivial collisions
654            // between inputs like `("foo/bar", "baz")` and `("foo", "bar/baz")`.
655            i.stable_hash(hcx, hasher);
656            match component {
657                Component::Prefix(prefix) => match prefix.kind() {
658                    Prefix::Verbatim(os_str) => {
659                        Tag::PrefixVerbatim.stable_hash(hcx, hasher);
660                        os_str.stable_hash(hcx, hasher);
661                    }
662                    Prefix::VerbatimUNC(host, share) => {
663                        Tag::PrefixVerbatimUNC.stable_hash(hcx, hasher);
664                        host.stable_hash(hcx, hasher);
665                        share.stable_hash(hcx, hasher);
666                    }
667                    Prefix::VerbatimDisk(letter) => {
668                        Tag::PrefixVerbatimDisk.stable_hash(hcx, hasher);
669                        letter.stable_hash(hcx, hasher);
670                    }
671                    Prefix::DeviceNS(os_str) => {
672                        Tag::PrefixDeviceNS.stable_hash(hcx, hasher);
673                        os_str.stable_hash(hcx, hasher);
674                    }
675                    Prefix::UNC(host, share) => {
676                        Tag::PrefixUNC.stable_hash(hcx, hasher);
677                        host.stable_hash(hcx, hasher);
678                        share.stable_hash(hcx, hasher);
679                    }
680                    Prefix::Disk(letter) => {
681                        Tag::PrefixDisk.stable_hash(hcx, hasher);
682                        letter.stable_hash(hcx, hasher);
683                    }
684                },
685                Component::RootDir => Tag::RootDir.stable_hash(hcx, hasher),
686                Component::CurDir => Tag::CurDir.stable_hash(hcx, hasher),
687                Component::ParentDir => Tag::ParentDir.stable_hash(hcx, hasher),
688                Component::Normal(os_str) => {
689                    Tag::Normal.stable_hash(hcx, hasher);
690                    os_str.stable_hash(hcx, hasher);
691                }
692            }
693        }
694
695        // Explicitly tag the end of each path, so that empty paths always hash something.
696        // (Tagging the start and the end and the component-index is potentially overkill.)
697        Tag::EndOfPath.stable_hash(hcx, hasher);
698    }
699}
700
701impl StableOrd for std::path::Path {
702    /// FIXME(Zalathar): Unstably sorting paths is pre-existing behavior, but potentially wrong.
703    const CAN_USE_UNSTABLE_SORT: bool = true;
704    /// Stdlib path sorting should (hopefully) not change.
705    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
706}
707
708impl StableHash for std::path::PathBuf {
709    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
710        self.as_path().stable_hash(hcx, hasher);
711    }
712}
713
714impl StableOrd for std::path::PathBuf {
715    const CAN_USE_UNSTABLE_SORT: bool = <std::path::Path as StableOrd>::CAN_USE_UNSTABLE_SORT;
716    /// Stdlib path sorting should (hopefully) not change.
717    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
718}
719
720// It is not safe to implement StableHash for HashSet, HashMap or any other collection type
721// with unstable but observable iteration order.
722// See https://github.com/rust-lang/compiler-team/issues/533 for further information.
723impl<V> !StableHash for std::collections::HashSet<V> {}
724impl<K, V> !StableHash for std::collections::HashMap<K, V> {}
725
726impl<K, V> StableHash for ::std::collections::BTreeMap<K, V>
727where
728    K: StableHash + StableOrd,
729    V: StableHash,
730{
731    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
732        self.len().stable_hash(hcx, hasher);
733        for entry in self.iter() {
734            entry.stable_hash(hcx, hasher);
735        }
736    }
737}
738
739impl<K> StableHash for ::std::collections::BTreeSet<K>
740where
741    K: StableHash + StableOrd,
742{
743    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
744        self.len().stable_hash(hcx, hasher);
745        for entry in self.iter() {
746            entry.stable_hash(hcx, hasher);
747        }
748    }
749}
750
751/// Controls what data we do or do not hash.
752/// Whenever a `StableHash` implementation caches its
753/// result, it needs to include `StableHashControls` as part
754/// of the key, to ensure that it does not produce an incorrect
755/// result (for example, using a `Fingerprint` produced while
756/// hashing `Span`s when a `Fingerprint` without `Span`s is
757/// being requested)
758#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for StableHashControls {
}
#[automatically_derived]impl ::core::clone::Clone for StableHashControls {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<bool>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for StableHashControls { }Copy, #[automatically_derived]impl ::core::hash::Hash for StableHashControls {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.hash_spans, state)
    }
}Hash, #[automatically_derived]impl ::core::cmp::Eq for StableHashControls {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<bool>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    StableHashControls {
}
#[automatically_derived]impl ::core::cmp::PartialEq for StableHashControls {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.hash_spans == other.hash_spans }
}PartialEq, #[automatically_derived]impl ::core::fmt::Debug for StableHashControls {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "StableHashControls hash_spans", &&self.hash_spans)
    }
}Debug)]
759pub struct StableHashControls {
760    pub hash_spans: bool,
761}