1 use crate::HashStableContext;
2 use rustc_data_structures::fingerprint::Fingerprint;
3 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
4 use rustc_data_structures::AtomicRef;
5 use rustc_index::vec::Idx;
6 use rustc_macros::HashStable_Generic;
7 use rustc_serialize::{Decoder, Encoder};
8 use std::borrow::Borrow;
11 rustc_index::newtype_index! {
17 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
19 /// A special `CrateNum` that we use for the `tcx.rcache` when decoding from
20 /// the incr. comp. cache.
21 ReservedForIncrCompCache,
25 /// Item definitions in the currently-compiled crate would have the `CrateNum`
26 /// `LOCAL_CRATE` in their `DefId`.
27 pub const LOCAL_CRATE: CrateNum = CrateNum::Index(CrateId::from_u32(0));
29 impl Idx for CrateNum {
31 fn new(value: usize) -> Self {
32 CrateNum::Index(Idx::new(value))
36 fn index(self) -> usize {
38 CrateNum::Index(idx) => Idx::index(idx),
39 _ => panic!("Tried to get crate index of {:?}", self),
45 pub fn new(x: usize) -> CrateNum {
46 CrateNum::from_usize(x)
49 pub fn from_usize(x: usize) -> CrateNum {
50 CrateNum::Index(CrateId::from_usize(x))
53 pub fn from_u32(x: u32) -> CrateNum {
54 CrateNum::Index(CrateId::from_u32(x))
57 pub fn as_usize(self) -> usize {
59 CrateNum::Index(id) => id.as_usize(),
60 _ => panic!("tried to get index of non-standard crate {:?}", self),
64 pub fn as_u32(self) -> u32 {
66 CrateNum::Index(id) => id.as_u32(),
67 _ => panic!("tried to get index of non-standard crate {:?}", self),
71 pub fn as_def_id(&self) -> DefId {
72 DefId { krate: *self, index: CRATE_DEF_INDEX }
76 impl fmt::Display for CrateNum {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79 CrateNum::Index(id) => fmt::Display::fmt(&id.private, f),
80 CrateNum::ReservedForIncrCompCache => write!(f, "crate for decoding incr comp cache"),
85 /// As a local identifier, a `CrateNum` is only meaningful within its context, e.g. within a tcx.
86 /// Therefore, make sure to include the context when encode a `CrateNum`.
87 impl rustc_serialize::UseSpecializedEncodable for CrateNum {
88 fn default_encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
89 e.emit_u32(self.as_u32())
92 impl rustc_serialize::UseSpecializedDecodable for CrateNum {
93 fn default_decode<D: Decoder>(d: &mut D) -> Result<CrateNum, D::Error> {
94 Ok(CrateNum::from_u32(d.read_u32()?))
98 impl ::std::fmt::Debug for CrateNum {
99 fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
101 CrateNum::Index(id) => write!(fmt, "crate{}", id.private),
102 CrateNum::ReservedForIncrCompCache => write!(fmt, "crate for decoding incr comp cache"),
107 #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Debug, RustcEncodable, RustcDecodable)]
108 #[derive(HashStable_Generic)]
109 pub struct DefPathHash(pub Fingerprint);
111 impl Borrow<Fingerprint> for DefPathHash {
113 fn borrow(&self) -> &Fingerprint {
118 rustc_index::newtype_index! {
119 /// A DefIndex is an index into the hir-map for a crate, identifying a
120 /// particular definition. It should really be considered an interned
121 /// shorthand for a particular DefPath.
122 pub struct DefIndex {
123 DEBUG_FORMAT = "DefIndex({})",
125 /// The crate root is always assigned index 0 by the AST Map code,
126 /// thanks to `NodeCollector::new`.
127 const CRATE_DEF_INDEX = 0,
131 impl rustc_serialize::UseSpecializedEncodable for DefIndex {}
132 impl rustc_serialize::UseSpecializedDecodable for DefIndex {}
134 /// A `DefId` identifies a particular *definition*, by combining a crate
135 /// index and a def index.
137 /// You can create a `DefId` from a `LocalDefId` using `local_def_id.to_def_id()`.
138 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy)]
145 /// Makes a local `DefId` from the given `DefIndex`.
147 pub fn local(index: DefIndex) -> DefId {
148 DefId { krate: LOCAL_CRATE, index }
152 pub fn is_local(self) -> bool {
153 self.krate == LOCAL_CRATE
157 pub fn as_local(self) -> Option<LocalDefId> {
158 if self.is_local() { Some(LocalDefId { local_def_index: self.index }) } else { None }
162 pub fn expect_local(self) -> LocalDefId {
163 self.as_local().unwrap_or_else(|| panic!("DefId::expect_local: `{:?}` isn't local", self))
166 pub fn is_top_level_module(self) -> bool {
167 self.is_local() && self.index == CRATE_DEF_INDEX
171 impl rustc_serialize::UseSpecializedEncodable for DefId {
172 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
173 let krate = u64::from(self.krate.as_u32());
174 let index = u64::from(self.index.as_u32());
175 s.emit_u64((krate << 32) | index)
178 impl rustc_serialize::UseSpecializedDecodable for DefId {
179 fn default_decode<D: Decoder>(d: &mut D) -> Result<DefId, D::Error> {
180 let def_id = d.read_u64()?;
181 let krate = CrateNum::from_u32((def_id >> 32) as u32);
182 let index = DefIndex::from_u32((def_id & 0xffffffff) as u32);
183 Ok(DefId { krate, index })
187 pub fn default_def_id_debug(def_id: DefId, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188 f.debug_struct("DefId").field("krate", &def_id.krate).field("index", &def_id.index).finish()
191 pub static DEF_ID_DEBUG: AtomicRef<fn(DefId, &mut fmt::Formatter<'_>) -> fmt::Result> =
192 AtomicRef::new(&(default_def_id_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
194 impl fmt::Debug for DefId {
195 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196 (*DEF_ID_DEBUG)(*self, f)
200 rustc_data_structures::define_id_collections!(DefIdMap, DefIdSet, DefId);
202 /// A LocalDefId is equivalent to a DefId with `krate == LOCAL_CRATE`. Since
203 /// we encode this information in the type, we can ensure at compile time that
204 /// no DefIds from upstream crates get thrown into the mix. There are quite a
205 /// few cases where we know that only DefIds from the local crate are expected
206 /// and a DefId from a different crate would signify a bug somewhere. This
207 /// is when LocalDefId comes in handy.
208 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
209 pub struct LocalDefId {
210 pub local_def_index: DefIndex,
213 impl Idx for LocalDefId {
215 fn new(idx: usize) -> Self {
216 LocalDefId { local_def_index: Idx::new(idx) }
219 fn index(self) -> usize {
220 self.local_def_index.index()
226 pub fn to_def_id(self) -> DefId {
227 DefId { krate: LOCAL_CRATE, index: self.local_def_index }
231 pub fn is_top_level_module(self) -> bool {
232 self.local_def_index == CRATE_DEF_INDEX
236 impl fmt::Debug for LocalDefId {
237 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238 self.to_def_id().fmt(f)
242 impl rustc_serialize::UseSpecializedEncodable for LocalDefId {}
243 impl rustc_serialize::UseSpecializedDecodable for LocalDefId {}
245 impl<CTX: HashStableContext> HashStable<CTX> for DefId {
246 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
247 hcx.hash_def_id(*self, hasher)
251 impl<CTX: HashStableContext> HashStable<CTX> for CrateNum {
252 fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
253 hcx.hash_crate_num(*self, hasher)