Skip to main content

rustc_span/
def_id.rs

1use std::fmt;
2use std::hash::{BuildHasherDefault, Hash, Hasher};
3
4use rustc_data_structures::AtomicRef;
5use rustc_data_structures::fingerprint::Fingerprint;
6use rustc_data_structures::stable_hash::{
7    RawDefId, StableHash, StableHashCtxt, StableHasher, StableOrd, ToStableHashKey,
8};
9use rustc_data_structures::unhash::Unhasher;
10use rustc_hashes::Hash64;
11use rustc_index::Idx;
12use rustc_macros::{BlobDecodable, Decodable, Encodable, StableHash};
13use rustc_serialize::{Decodable, Encodable};
14
15use crate::{SpanDecoder, SpanEncoder, Symbol};
16
17pub type StableCrateIdMap =
18    indexmap::IndexMap<StableCrateId, CrateNum, BuildHasherDefault<Unhasher>>;
19
20#[automatically_derived]
impl ::core::marker::Copy for CrateNum { }
impl CrateNum {
    #[doc = r" Maximum value the index can take, as a `u32`."]
    pub const MAX_AS_U32: u32 = 0xFFFF_FF00;
    #[doc = r" Maximum value the index can take."]
    pub const MAX: Self = Self::from_u32(0xFFFF_FF00);
    #[doc = r" Zero value of the index."]
    pub const ZERO: Self = Self::from_u32(0);
    #[doc = r" Creates a new index from a given `usize`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_usize(value: usize) -> Self {
        if !(value <= (0xFFFF_FF00 as usize)) {
            ::core::panicking::panic("assertion failed: value <= (0xFFFF_FF00 as usize)")
        };
        unsafe { Self::from_u32_unchecked(value as u32) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_u32(value: u32) -> Self {
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u16`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_u16(value: u16) -> Self {
        let value = value as u32;
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc =
    r" The provided value must be less than or equal to the maximum value for the newtype."]
    #[doc =
    r" Providing a value outside this range is undefined due to layout restrictions."]
    #[doc = r""]
    #[doc = r" Prefer using `from_u32`."]
    #[inline]
    pub const unsafe fn from_u32_unchecked(value: u32) -> Self {
        Self {
            private_use_as_methods_instead: unsafe {
                std::mem::transmute(value)
            },
        }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    pub const fn index(self) -> usize { self.as_usize() }
    #[doc = r" Extracts the value of this index as a `u32`."]
    #[inline]
    pub const fn as_u32(self) -> u32 {
        unsafe { std::mem::transmute(self.private_use_as_methods_instead) }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    pub const fn as_usize(self) -> usize { self.as_u32() as usize }
}
impl std::ops::Add<usize> for CrateNum {
    type Output = Self;
    #[inline]
    fn add(self, other: usize) -> Self {
        Self::from_usize(self.index() + other)
    }
}
impl std::ops::AddAssign<usize> for CrateNum {
    #[inline]
    fn add_assign(&mut self, other: usize) { *self = *self + other; }
}
impl rustc_index::Idx for CrateNum {
    #[inline]
    fn new(value: usize) -> Self { Self::from_usize(value) }
    #[inline]
    fn index(self) -> usize { self.as_usize() }
}
impl ::std::iter::Step for CrateNum {
    #[inline]
    fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
        <usize as
                ::std::iter::Step>::steps_between(&Self::index(*start),
            &Self::index(*end))
    }
    #[inline]
    fn forward_checked(start: Self, u: usize) -> Option<Self> {
        Self::index(start).checked_add(u).map(Self::from_usize)
    }
    #[inline]
    fn backward_checked(start: Self, u: usize) -> Option<Self> {
        Self::index(start).checked_sub(u).map(Self::from_usize)
    }
    #[inline]
    fn forward_overflowing(start: Self, u: usize) -> (Self, bool) {
        let (s, o) = Self::index(start).overflowing_add(u);
        (Self::from_usize(s), o)
    }
    #[inline]
    fn backward_overflowing(start: Self, u: usize) -> (Self, bool) {
        let (s, o) = Self::index(start).overflowing_sub(u);
        (Self::from_usize(s), o)
    }
}
impl ::std::cmp::Ord for CrateNum {
    #[inline]
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.as_u32().cmp(&other.as_u32())
    }
}
impl ::std::cmp::PartialOrd for CrateNum {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl From<CrateNum> for u32 {
    #[inline]
    fn from(v: CrateNum) -> u32 { v.as_u32() }
}
impl From<CrateNum> for usize {
    #[inline]
    fn from(v: CrateNum) -> usize { v.as_usize() }
}
impl From<usize> for CrateNum {
    #[inline]
    fn from(value: usize) -> Self { Self::from_usize(value) }
}
impl From<u32> for CrateNum {
    #[inline]
    fn from(value: u32) -> Self { Self::from_u32(value) }
}
impl ::std::cmp::Eq for CrateNum {}
impl ::std::cmp::PartialEq for CrateNum {
    fn eq(&self, other: &Self) -> bool { self.as_u32().eq(&other.as_u32()) }
}
impl ::std::marker::StructuralPartialEq for CrateNum {}
impl ::std::hash::Hash for CrateNum {
    fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
        self.as_u32().hash(state)
    }
}
impl ::std::fmt::Debug for CrateNum {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        fmt.write_fmt(format_args!("crate{0}", self.as_u32()))
    }
}rustc_index::newtype_index! {
21    #[orderable]
22    #[debug_format = "crate{}"]
23    pub struct CrateNum {}
24}
25
26/// Item definitions in the currently-compiled crate would have the `CrateNum`
27/// `LOCAL_CRATE` in their `DefId`.
28pub const LOCAL_CRATE: CrateNum = CrateNum::ZERO;
29
30impl CrateNum {
31    #[inline]
32    pub fn new(x: usize) -> CrateNum {
33        CrateNum::from_usize(x)
34    }
35
36    // FIXME(typed_def_id): Replace this with `as_mod_def_id`.
37    #[inline]
38    pub fn as_def_id(self) -> DefId {
39        DefId { krate: self, index: CRATE_DEF_INDEX }
40    }
41
42    #[inline]
43    pub fn as_mod_id(self) -> ModId {
44        ModId::new_unchecked(DefId { krate: self, index: CRATE_DEF_INDEX })
45    }
46}
47
48impl fmt::Display for CrateNum {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        fmt::Display::fmt(&self.as_u32(), f)
51    }
52}
53
54/// A `DefPathHash` is a fixed-size representation of a `DefPath` that is
55/// stable across crate and compilation session boundaries. It consists of two
56/// separate 64-bit hashes. The first uniquely identifies the crate this
57/// `DefPathHash` originates from (see [StableCrateId]), and the second
58/// uniquely identifies the corresponding `DefPath` within that crate. Together
59/// they form a unique identifier within an entire crate graph.
60///
61/// There is a very small chance of hash collisions, which would mean that two
62/// different `DefPath`s map to the same `DefPathHash`. Proceeding compilation
63/// with such a hash collision would very probably lead to an ICE, and in the
64/// worst case lead to a silent mis-compilation. The compiler therefore actively
65/// and exhaustively checks for such hash collisions and aborts compilation if
66/// it finds one.
67///
68/// `DefPathHash` uses 64-bit hashes for both the crate-id part and the
69/// crate-internal part, even though it is likely that there are many more
70/// `LocalDefId`s in a single crate than there are individual crates in a crate
71/// graph. Since we use the same number of bits in both cases, the collision
72/// probability for the crate-local part will be quite a bit higher (though
73/// still very small).
74///
75/// This imbalance is not by accident: A hash collision in the
76/// crate-local part of a `DefPathHash` will be detected and reported while
77/// compiling the crate in question. Such a collision does not depend on
78/// outside factors and can be easily fixed by the crate maintainer (e.g. by
79/// renaming the item in question or by bumping the crate version in a harmless
80/// way).
81///
82/// A collision between crate-id hashes on the other hand is harder to fix
83/// because it depends on the set of crates in the entire crate graph of a
84/// compilation session. Again, using the same crate with a different version
85/// number would fix the issue with a high probability -- but that might be
86/// easier said than done if the crates in questions are dependencies of
87/// third-party crates.
88///
89/// That being said, given a high quality hash function, the collision
90/// probabilities in question are very small. For example, for a big crate like
91/// `rustc_middle` (with ~50000 `LocalDefId`s as of the time of writing) there
92/// is a probability of roughly 1 in 14,750,000,000 of a crate-internal
93/// collision occurring. For a big crate graph with 1000 crates in it, there is
94/// a probability of 1 in 36,890,000,000,000 of a `StableCrateId` collision.
95#[derive(#[automatically_derived]
impl ::core::marker::Copy for DefPathHash { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for DefPathHash { }
#[automatically_derived]
impl ::core::clone::Clone for DefPathHash {
    #[inline]
    fn clone(&self) -> DefPathHash {
        let _: ::core::clone::AssertParamIsClone<Fingerprint>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::hash::Hash for DefPathHash {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for DefPathHash { }
#[automatically_derived]
impl ::core::cmp::PartialEq for DefPathHash {
    #[inline]
    fn eq(&self, other: &DefPathHash) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for DefPathHash {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Fingerprint>;
    }
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for DefPathHash {
    #[inline]
    fn partial_cmp(&self, other: &DefPathHash)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for DefPathHash {
    #[inline]
    fn cmp(&self, other: &DefPathHash) -> ::core::cmp::Ordering {
        ::core::cmp::Ord::cmp(&self.0, &other.0)
    }
}Ord, #[automatically_derived]
impl ::core::fmt::Debug for DefPathHash {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "DefPathHash",
            &&self.0)
    }
}Debug)]
96#[derive(const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for DefPathHash
            {
            #[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 {
                    DefPathHash(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for DefPathHash {
            fn encode(&self, __encoder: &mut __E) {
                let DefPathHash(ref __binding_0) = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for DefPathHash {
            fn decode(__decoder: &mut __D) -> Self {
                DefPathHash(::rustc_serialize::Decodable::decode(__decoder))
            }
        }
    };Decodable)]
97pub struct DefPathHash(pub Fingerprint);
98
99impl DefPathHash {
100    /// Returns the [StableCrateId] identifying the crate this [DefPathHash]
101    /// originates from.
102    #[inline]
103    pub fn stable_crate_id(&self) -> StableCrateId {
104        StableCrateId(self.0.split().0)
105    }
106
107    /// Returns the crate-local part of the [DefPathHash].
108    #[inline]
109    pub fn local_hash(&self) -> Hash64 {
110        self.0.split().1
111    }
112
113    /// Builds a new [DefPathHash] with the given [StableCrateId] and
114    /// `local_hash`, where `local_hash` must be unique within its crate.
115    #[inline]
116    pub fn new(stable_crate_id: StableCrateId, local_hash: Hash64) -> DefPathHash {
117        DefPathHash(Fingerprint::new(stable_crate_id.0, local_hash))
118    }
119}
120
121impl Default for DefPathHash {
122    fn default() -> Self {
123        DefPathHash(Fingerprint::ZERO)
124    }
125}
126
127impl StableOrd for DefPathHash {
128    const CAN_USE_UNSTABLE_SORT: bool = true;
129
130    // `DefPathHash` sort order is not affected by (de)serialization.
131    const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED: () = ();
132}
133
134/// A [`StableCrateId`] is a 64-bit hash of a crate name, together with all
135/// `-Cmetadata` arguments, and some other data. It is to [`CrateNum`] what [`DefPathHash`] is to
136/// [`DefId`]. It is stable across compilation sessions.
137///
138/// Since the ID is a hash value, there is a small chance that two crates
139/// end up with the same [`StableCrateId`]. The compiler will check for such
140/// collisions when loading crates and abort compilation in order to avoid
141/// further trouble.
142///
143/// For more information on the possibility of hash collisions in rustc,
144/// see the discussion in [`DefId`].
145#[derive(#[automatically_derived]
impl ::core::marker::Copy for StableCrateId { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for StableCrateId { }
#[automatically_derived]
impl ::core::clone::Clone for StableCrateId {
    #[inline]
    fn clone(&self) -> StableCrateId {
        let _: ::core::clone::AssertParamIsClone<Hash64>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for StableCrateId { }
#[automatically_derived]
impl ::core::cmp::PartialEq for StableCrateId {
    #[inline]
    fn eq(&self, other: &StableCrateId) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for StableCrateId {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Hash64>;
    }
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for StableCrateId {
    #[inline]
    fn partial_cmp(&self, other: &StableCrateId)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for StableCrateId {
    #[inline]
    fn cmp(&self, other: &StableCrateId) -> ::core::cmp::Ordering {
        ::core::cmp::Ord::cmp(&self.0, &other.0)
    }
}Ord, #[automatically_derived]
impl ::core::fmt::Debug for StableCrateId {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "StableCrateId",
            &&self.0)
    }
}Debug)]
146#[derive(#[automatically_derived]
impl ::core::hash::Hash for StableCrateId {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for
            StableCrateId {
            #[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 {
                    StableCrateId(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for StableCrateId {
            fn encode(&self, __encoder: &mut __E) {
                let StableCrateId(ref __binding_0) = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::BlobDecoder> ::rustc_serialize::Decodable<__D>
            for StableCrateId {
            fn decode(__decoder: &mut __D) -> Self {
                StableCrateId(::rustc_serialize::Decodable::decode(__decoder))
            }
        }
    };BlobDecodable)]
147pub struct StableCrateId(pub(crate) Hash64);
148
149impl StableCrateId {
150    /// Computes the stable ID for a crate with the given name and
151    /// `-Cmetadata` arguments.
152    pub fn new(
153        crate_name: Symbol,
154        is_exe: bool,
155        mut metadata: Vec<String>,
156        cfg_version: &'static str,
157    ) -> StableCrateId {
158        let mut hasher = StableHasher::new();
159        // We must hash the string text of the crate name, not the id, as the id is not stable
160        // across builds.
161        crate_name.as_str().hash(&mut hasher);
162
163        // We don't want the stable crate ID to depend on the order of
164        // -C metadata arguments, so sort them:
165        metadata.sort();
166        // Every distinct -C metadata value is only incorporated once:
167        metadata.dedup();
168
169        hasher.write(b"metadata");
170        for s in &metadata {
171            // Also incorporate the length of a metadata string, so that we generate
172            // different values for `-Cmetadata=ab -Cmetadata=c` and
173            // `-Cmetadata=a -Cmetadata=bc`
174            hasher.write_usize(s.len());
175            hasher.write(s.as_bytes());
176        }
177
178        // Also incorporate crate type, so that we don't get symbol conflicts when
179        // linking against a library of the same name, if this is an executable.
180        hasher.write(if is_exe { b"exe" } else { b"lib" });
181
182        // Also incorporate the rustc version. Otherwise, with -Zsymbol-mangling-version=v0
183        // and no -Cmetadata, symbols from the same crate compiled with different versions of
184        // rustc are named the same.
185        //
186        // RUSTC_FORCE_RUSTC_VERSION is used to inject rustc version information
187        // during testing.
188        if let Some(val) = std::env::var_os("RUSTC_FORCE_RUSTC_VERSION") {
189            hasher.write(val.to_string_lossy().into_owned().as_bytes())
190        } else {
191            hasher.write(cfg_version.as_bytes())
192        }
193
194        StableCrateId(hasher.finish())
195    }
196
197    #[inline]
198    pub fn as_u64(self) -> u64 {
199        self.0.as_u64()
200    }
201}
202
203impl fmt::LowerHex for StableCrateId {
204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205        fmt::LowerHex::fmt(&self.0, f)
206    }
207}
208
209#[automatically_derived]
impl ::core::marker::Copy for DefIndex { }
#[doc = " The crate root is always assigned index 0 by the AST Map code,"]
#[doc = " thanks to `NodeCollector::new`."]
pub const CRATE_DEF_INDEX: DefIndex = DefIndex::from_u32(0);
impl DefIndex {
    #[doc = r" Maximum value the index can take, as a `u32`."]
    pub const MAX_AS_U32: u32 = 0xFFFF_FF00;
    #[doc = r" Maximum value the index can take."]
    pub const MAX: Self = Self::from_u32(0xFFFF_FF00);
    #[doc = r" Zero value of the index."]
    pub const ZERO: Self = Self::from_u32(0);
    #[doc = r" Creates a new index from a given `usize`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_usize(value: usize) -> Self {
        if !(value <= (0xFFFF_FF00 as usize)) {
            ::core::panicking::panic("assertion failed: value <= (0xFFFF_FF00 as usize)")
        };
        unsafe { Self::from_u32_unchecked(value as u32) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_u32(value: u32) -> Self {
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u16`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_u16(value: u16) -> Self {
        let value = value as u32;
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc =
    r" The provided value must be less than or equal to the maximum value for the newtype."]
    #[doc =
    r" Providing a value outside this range is undefined due to layout restrictions."]
    #[doc = r""]
    #[doc = r" Prefer using `from_u32`."]
    #[inline]
    pub const unsafe fn from_u32_unchecked(value: u32) -> Self {
        Self {
            private_use_as_methods_instead: unsafe {
                std::mem::transmute(value)
            },
        }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    pub const fn index(self) -> usize { self.as_usize() }
    #[doc = r" Extracts the value of this index as a `u32`."]
    #[inline]
    pub const fn as_u32(self) -> u32 {
        unsafe { std::mem::transmute(self.private_use_as_methods_instead) }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    pub const fn as_usize(self) -> usize { self.as_u32() as usize }
}
impl std::ops::Add<usize> for DefIndex {
    type Output = Self;
    #[inline]
    fn add(self, other: usize) -> Self {
        Self::from_usize(self.index() + other)
    }
}
impl std::ops::AddAssign<usize> for DefIndex {
    #[inline]
    fn add_assign(&mut self, other: usize) { *self = *self + other; }
}
impl rustc_index::Idx for DefIndex {
    #[inline]
    fn new(value: usize) -> Self { Self::from_usize(value) }
    #[inline]
    fn index(self) -> usize { self.as_usize() }
}
impl ::std::iter::Step for DefIndex {
    #[inline]
    fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
        <usize as
                ::std::iter::Step>::steps_between(&Self::index(*start),
            &Self::index(*end))
    }
    #[inline]
    fn forward_checked(start: Self, u: usize) -> Option<Self> {
        Self::index(start).checked_add(u).map(Self::from_usize)
    }
    #[inline]
    fn backward_checked(start: Self, u: usize) -> Option<Self> {
        Self::index(start).checked_sub(u).map(Self::from_usize)
    }
    #[inline]
    fn forward_overflowing(start: Self, u: usize) -> (Self, bool) {
        let (s, o) = Self::index(start).overflowing_add(u);
        (Self::from_usize(s), o)
    }
    #[inline]
    fn backward_overflowing(start: Self, u: usize) -> (Self, bool) {
        let (s, o) = Self::index(start).overflowing_sub(u);
        (Self::from_usize(s), o)
    }
}
impl ::std::cmp::Ord for DefIndex {
    #[inline]
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.as_u32().cmp(&other.as_u32())
    }
}
impl ::std::cmp::PartialOrd for DefIndex {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl From<DefIndex> for u32 {
    #[inline]
    fn from(v: DefIndex) -> u32 { v.as_u32() }
}
impl From<DefIndex> for usize {
    #[inline]
    fn from(v: DefIndex) -> usize { v.as_usize() }
}
impl From<usize> for DefIndex {
    #[inline]
    fn from(value: usize) -> Self { Self::from_usize(value) }
}
impl From<u32> for DefIndex {
    #[inline]
    fn from(value: u32) -> Self { Self::from_u32(value) }
}
impl ::std::cmp::Eq for DefIndex {}
impl ::std::cmp::PartialEq for DefIndex {
    fn eq(&self, other: &Self) -> bool { self.as_u32().eq(&other.as_u32()) }
}
impl ::std::marker::StructuralPartialEq for DefIndex {}
impl ::std::hash::Hash for DefIndex {
    fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
        self.as_u32().hash(state)
    }
}
impl ::std::fmt::Debug for DefIndex {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        fmt.write_fmt(format_args!("DefIndex({0})", self.as_u32()))
    }
}rustc_index::newtype_index! {
210    /// A DefIndex is an index into the hir-map for a crate, identifying a
211    /// particular definition. It should really be considered an interned
212    /// shorthand for a particular DefPath.
213    #[orderable]
214    #[debug_format = "DefIndex({})"]
215    pub struct DefIndex {
216        /// The crate root is always assigned index 0 by the AST Map code,
217        /// thanks to `NodeCollector::new`.
218        const CRATE_DEF_INDEX = 0;
219    }
220}
221
222/// A `DefId` identifies a particular *definition*, by combining a crate
223/// index and a def index.
224///
225/// You can create a `DefId` from a `LocalDefId` using `local_def_id.to_def_id()`.
226#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for DefId { }
#[automatically_derived]
impl ::core::clone::Clone for DefId {
    #[inline]
    fn clone(&self) -> DefId {
        let _: ::core::clone::AssertParamIsClone<DefIndex>;
        let _: ::core::clone::AssertParamIsClone<CrateNum>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for DefId { }
#[automatically_derived]
impl ::core::cmp::PartialEq for DefId {
    #[inline]
    fn eq(&self, other: &DefId) -> bool {
        self.index == other.index && self.krate == other.krate
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for DefId {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<DefIndex>;
        let _: ::core::cmp::AssertParamIsEq<CrateNum>;
    }
}Eq, #[automatically_derived]
impl ::core::marker::Copy for DefId { }Copy)]
227// On below-64 bit systems we can simply use the derived `Hash` impl
228#[cfg_attr(not(target_pointer_width = "64"), derive(Hash))]
229#[repr(C)]
230#[rustc_pass_by_value]
231// We guarantee field order. Note that the order is essential here, see below why.
232pub struct DefId {
233    // cfg-ing the order of fields so that the `DefIndex` which is high entropy always ends up in
234    // the lower bits no matter the endianness. This allows the compiler to turn that `Hash` impl
235    // into a direct call to `u64::hash(_)`.
236    #[cfg(not(all(target_pointer_width = "64", target_endian = "big")))]
237    pub index: DefIndex,
238    pub krate: CrateNum,
239    #[cfg(all(target_pointer_width = "64", target_endian = "big"))]
240    pub index: DefIndex,
241}
242
243// To ensure correctness of incremental compilation,
244// `DefId` must not implement `Ord` or `PartialOrd`.
245// See https://github.com/rust-lang/rust/issues/90317.
246impl !Ord for DefId {}
247impl !PartialOrd for DefId {}
248
249// On 64-bit systems, we can hash the whole `DefId` as one `u64` instead of two `u32`s. This
250// improves performance without impairing `FxHash` quality. So the below code gets compiled to a
251// noop on little endian systems because the memory layout of `DefId` is as follows:
252//
253// ```
254//     +-1--------------31-+-32-------------63-+
255//     ! index             ! krate             !
256//     +-------------------+-------------------+
257// ```
258//
259// The order here has direct impact on `FxHash` quality because we have far more `DefIndex` per
260// crate than we have `Crate`s within one compilation. Or in other words, this arrangement puts
261// more entropy in the low bits than the high bits. The reason this matters is that `FxHash`, which
262// is used throughout rustc, has problems distributing the entropy from the high bits, so reversing
263// the order would lead to a large number of collisions and thus far worse performance.
264//
265// On 64-bit big-endian systems, this compiles to a 64-bit rotation by 32 bits, which is still
266// faster than another `FxHash` round.
267#[cfg(target_pointer_width = "64")]
268impl Hash for DefId {
269    fn hash<H: Hasher>(&self, h: &mut H) {
270        (((self.krate.as_u32() as u64) << 32) | (self.index.as_u32() as u64)).hash(h)
271    }
272}
273
274impl DefId {
275    /// Makes a local `DefId` from the given `DefIndex`.
276    #[inline]
277    pub fn local(index: DefIndex) -> DefId {
278        DefId { krate: LOCAL_CRATE, index }
279    }
280
281    /// Returns whether the item is defined in the crate currently being compiled.
282    #[inline]
283    pub fn is_local(self) -> bool {
284        self.krate == LOCAL_CRATE
285    }
286
287    #[inline]
288    pub fn as_local(self) -> Option<LocalDefId> {
289        self.is_local().then(|| LocalDefId { local_def_index: self.index })
290    }
291
292    #[inline]
293    #[track_caller]
294    pub fn expect_local(self) -> LocalDefId {
295        // NOTE: `match` below is required to apply `#[track_caller]`,
296        // i.e. don't use closures.
297        match self.as_local() {
298            Some(local_def_id) => local_def_id,
299            None => {
    ::core::panicking::panic_fmt(format_args!("DefId::expect_local: `{0:?}` isn\'t local",
            self));
}panic!("DefId::expect_local: `{self:?}` isn't local"),
300        }
301    }
302
303    #[inline]
304    pub fn is_crate_root(self) -> bool {
305        self.index == CRATE_DEF_INDEX
306    }
307
308    #[inline]
309    pub fn as_crate_root(self) -> Option<CrateNum> {
310        self.is_crate_root().then_some(self.krate)
311    }
312
313    #[inline]
314    pub fn is_top_level_module(self) -> bool {
315        self.is_local() && self.is_crate_root()
316    }
317
318    #[inline]
319    pub fn to_raw_def_id(self) -> RawDefId {
320        // Field order must match `from_raw_def_id`.
321        RawDefId(self.krate.as_u32(), self.index.as_u32())
322    }
323
324    #[inline]
325    pub fn from_raw_def_id(RawDefId(a, b): RawDefId) -> DefId {
326        // Field order must match `to_raw_def_id`.
327        DefId { krate: a.into(), index: b.into() }
328    }
329}
330
331impl From<LocalDefId> for DefId {
332    fn from(local: LocalDefId) -> DefId {
333        local.to_def_id()
334    }
335}
336
337pub fn default_def_id_debug(def_id: DefId, f: &mut fmt::Formatter<'_>) -> fmt::Result {
338    f.debug_struct("DefId").field("krate", &def_id.krate).field("index", &def_id.index).finish()
339}
340
341pub static DEF_ID_DEBUG: AtomicRef<fn(DefId, &mut fmt::Formatter<'_>) -> fmt::Result> =
342    AtomicRef::new(&(default_def_id_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
343
344impl fmt::Debug for DefId {
345    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
346        (*DEF_ID_DEBUG)(*self, f)
347    }
348}
349
350pub type DefIdMap<T> = ::rustc_data_structures::unord::UnordMap<DefId, T>;
pub type DefIdSet = ::rustc_data_structures::unord::UnordSet<DefId>;
pub type DefIdMapEntry<'a, T> =
    ::rustc_data_structures::fx::StdEntry<'a, DefId, T>;rustc_data_structures::define_id_collections!(DefIdMap, DefIdSet, DefIdMapEntry, DefId);
351
352/// A `LocalDefId` is equivalent to a `DefId` with `krate == LOCAL_CRATE`. Since
353/// we encode this information in the type, we can ensure at compile time that
354/// no `DefId`s from upstream crates get thrown into the mix. There are quite a
355/// few cases where we know that only `DefId`s from the local crate are expected;
356/// a `DefId` from a different crate would signify a bug somewhere. This
357/// is when `LocalDefId` comes in handy.
358#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for LocalDefId { }
#[automatically_derived]
impl ::core::clone::Clone for LocalDefId {
    #[inline]
    fn clone(&self) -> LocalDefId {
        let _: ::core::clone::AssertParamIsClone<DefIndex>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for LocalDefId { }Copy, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for LocalDefId { }
#[automatically_derived]
impl ::core::cmp::PartialEq for LocalDefId {
    #[inline]
    fn eq(&self, other: &LocalDefId) -> bool {
        self.local_def_index == other.local_def_index
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for LocalDefId {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<DefIndex>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for LocalDefId {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.local_def_index, state)
    }
}Hash)]
359pub struct LocalDefId {
360    pub local_def_index: DefIndex,
361}
362
363// To ensure correctness of incremental compilation,
364// `LocalDefId` must not implement `Ord` or `PartialOrd`.
365// See https://github.com/rust-lang/rust/issues/90317.
366impl !Ord for LocalDefId {}
367impl !PartialOrd for LocalDefId {}
368
369pub const CRATE_DEF_ID: LocalDefId = LocalDefId { local_def_index: CRATE_DEF_INDEX };
370pub const CRATE_MOD_ID: LocalModId = LocalModId::new_unchecked(CRATE_DEF_ID);
371
372impl Idx for LocalDefId {
373    #[inline]
374    fn new(idx: usize) -> Self {
375        LocalDefId { local_def_index: Idx::new(idx) }
376    }
377    #[inline]
378    fn index(self) -> usize {
379        self.local_def_index.index()
380    }
381}
382
383impl LocalDefId {
384    #[inline]
385    pub fn to_def_id(self) -> DefId {
386        DefId { krate: LOCAL_CRATE, index: self.local_def_index }
387    }
388
389    #[inline]
390    pub fn is_top_level_module(self) -> bool {
391        self == CRATE_DEF_ID
392    }
393}
394
395impl fmt::Debug for LocalDefId {
396    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
397        self.to_def_id().fmt(f)
398    }
399}
400
401impl<E: SpanEncoder> Encodable<E> for LocalDefId {
402    fn encode(&self, s: &mut E) {
403        self.to_def_id().encode(s);
404    }
405}
406
407impl<D: SpanDecoder> Decodable<D> for LocalDefId {
408    fn decode(d: &mut D) -> LocalDefId {
409        DefId::decode(d).expect_local()
410    }
411}
412
413pub type LocalDefIdMap<T> =
    ::rustc_data_structures::unord::UnordMap<LocalDefId, T>;
pub type LocalDefIdSet = ::rustc_data_structures::unord::UnordSet<LocalDefId>;
pub type LocalDefIdMapEntry<'a, T> =
    ::rustc_data_structures::fx::StdEntry<'a, LocalDefId, T>;rustc_data_structures::define_id_collections!(
414    LocalDefIdMap,
415    LocalDefIdSet,
416    LocalDefIdMapEntry,
417    LocalDefId
418);
419
420impl StableHash for DefId {
421    #[inline]
422    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
423        self.to_stable_hash_key(hcx).stable_hash(hcx, hasher);
424    }
425}
426
427impl StableHash for LocalDefId {
428    #[inline]
429    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
430        self.to_stable_hash_key(hcx).local_hash().stable_hash(hcx, hasher);
431    }
432}
433
434impl StableHash for CrateNum {
435    #[inline]
436    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
437        self.as_def_id().to_stable_hash_key(hcx).stable_crate_id().stable_hash(hcx, hasher);
438    }
439}
440
441impl ToStableHashKey for DefId {
442    type KeyType = DefPathHash;
443
444    #[inline]
445    fn to_stable_hash_key<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx) -> DefPathHash {
446        DefPathHash(hcx.def_path_hash(self.to_raw_def_id()))
447    }
448}
449
450impl ToStableHashKey for LocalDefId {
451    type KeyType = DefPathHash;
452
453    #[inline]
454    fn to_stable_hash_key<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx) -> DefPathHash {
455        self.to_def_id().to_stable_hash_key(hcx)
456    }
457}
458
459#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ModId {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "ModId",
            &&self.0)
    }
}Debug, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ModId { }
#[automatically_derived]
impl ::core::clone::Clone for ModId {
    #[inline]
    fn clone(&self) -> ModId {
        let _: ::core::clone::AssertParamIsClone<DefId>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ModId { }Copy, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ModId { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ModId {
    #[inline]
    fn eq(&self, other: &ModId) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ModId {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<DefId>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for ModId {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for ModId {
            fn encode(&self, __encoder: &mut __E) {
                let ModId(ref __binding_0) = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for ModId {
            fn decode(__decoder: &mut __D) -> Self {
                ModId(::rustc_serialize::Decodable::decode(__decoder))
            }
        }
    };Decodable, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for ModId {
            #[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 {
                    ModId(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
460pub struct ModId(DefId);
461
462impl ModId {
463    #[inline]
464    pub const fn new_unchecked(def_id: DefId) -> Self {
465        Self(def_id)
466    }
467
468    #[inline]
469    pub fn to_def_id(self) -> DefId {
470        self.into()
471    }
472
473    #[inline]
474    pub fn is_local(self) -> bool {
475        self.0.is_local()
476    }
477
478    #[inline]
479    pub fn as_local(self) -> Option<LocalModId> {
480        self.0.as_local().map(LocalModId::new_unchecked)
481    }
482
483    pub fn expect_local(self) -> LocalModId {
484        LocalModId::new_unchecked(self.0.expect_local())
485    }
486
487    pub fn is_crate_root(self) -> bool {
488        self.0.is_crate_root()
489    }
490
491    pub fn is_top_level_module(self) -> bool {
492        self.0.is_top_level_module()
493    }
494}
495
496impl From<LocalModId> for ModId {
497    #[inline]
498    fn from(local: LocalModId) -> Self {
499        Self(local.0.to_def_id())
500    }
501}
502
503impl From<ModId> for DefId {
504    #[inline]
505    fn from(typed: ModId) -> Self {
506        typed.0
507    }
508}
509
510#[derive(#[automatically_derived]
impl ::core::fmt::Debug for LocalModId {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "LocalModId",
            &&self.0)
    }
}Debug, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for LocalModId { }
#[automatically_derived]
impl ::core::clone::Clone for LocalModId {
    #[inline]
    fn clone(&self) -> LocalModId {
        let _: ::core::clone::AssertParamIsClone<LocalDefId>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for LocalModId { }Copy, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for LocalModId { }
#[automatically_derived]
impl ::core::cmp::PartialEq for LocalModId {
    #[inline]
    fn eq(&self, other: &LocalModId) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for LocalModId {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<LocalDefId>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for LocalModId {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for LocalModId {
            fn encode(&self, __encoder: &mut __E) {
                let LocalModId(ref __binding_0) = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for LocalModId {
            fn decode(__decoder: &mut __D) -> Self {
                LocalModId(::rustc_serialize::Decodable::decode(__decoder))
            }
        }
    };Decodable, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for LocalModId {
            #[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 {
                    LocalModId(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
511pub struct LocalModId(LocalDefId);
512
513impl !Ord for LocalModId {}
514impl !PartialOrd for LocalModId {}
515
516impl LocalModId {
517    #[inline]
518    pub const fn new_unchecked(def_id: LocalDefId) -> Self {
519        Self(def_id)
520    }
521
522    pub fn is_top_level_module(self) -> bool {
523        self.0.is_top_level_module()
524    }
525
526    #[inline]
527    pub fn to_def_id(self) -> DefId {
528        self.0.into()
529    }
530
531    pub fn to_mod_id(self) -> ModId {
532        ModId::new_unchecked(self.0.to_def_id())
533    }
534
535    #[inline]
536    pub fn to_local_def_id(self) -> LocalDefId {
537        self.0
538    }
539}
540
541impl From<LocalModId> for LocalDefId {
542    #[inline]
543    fn from(typed: LocalModId) -> Self {
544        typed.0
545    }
546}
547
548impl From<LocalModId> for DefId {
549    #[inline]
550    fn from(typed: LocalModId) -> Self {
551        typed.0.into()
552    }
553}