]> git.lizzy.rs Git - rust.git/blob - src/librustc_span/def_id.rs
Update `visit_item_likes_in_module`
[rust.git] / src / librustc_span / def_id.rs
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;
9 use std::fmt;
10 use std::{u32, u64};
11
12 rustc_index::newtype_index! {
13     pub struct CrateId {
14         ENCODABLE = custom
15     }
16 }
17
18 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
19 pub enum CrateNum {
20     /// A special `CrateNum` that we use for the `tcx.rcache` when decoding from
21     /// the incr. comp. cache.
22     ReservedForIncrCompCache,
23     Index(CrateId),
24 }
25
26 /// Item definitions in the currently-compiled crate would have the `CrateNum`
27 /// `LOCAL_CRATE` in their `DefId`.
28 pub const LOCAL_CRATE: CrateNum = CrateNum::Index(CrateId::from_u32_const(0));
29
30 impl Idx for CrateNum {
31     #[inline]
32     fn new(value: usize) -> Self {
33         CrateNum::Index(Idx::new(value))
34     }
35
36     #[inline]
37     fn index(self) -> usize {
38         match self {
39             CrateNum::Index(idx) => Idx::index(idx),
40             _ => panic!("Tried to get crate index of {:?}", self),
41         }
42     }
43 }
44
45 impl CrateNum {
46     pub fn new(x: usize) -> CrateNum {
47         CrateNum::from_usize(x)
48     }
49
50     pub fn from_usize(x: usize) -> CrateNum {
51         CrateNum::Index(CrateId::from_usize(x))
52     }
53
54     pub fn from_u32(x: u32) -> CrateNum {
55         CrateNum::Index(CrateId::from_u32(x))
56     }
57
58     pub fn as_usize(self) -> usize {
59         match self {
60             CrateNum::Index(id) => id.as_usize(),
61             _ => panic!("tried to get index of non-standard crate {:?}", self),
62         }
63     }
64
65     pub fn as_u32(self) -> u32 {
66         match self {
67             CrateNum::Index(id) => id.as_u32(),
68             _ => panic!("tried to get index of non-standard crate {:?}", self),
69         }
70     }
71
72     pub fn as_def_id(&self) -> DefId {
73         DefId { krate: *self, index: CRATE_DEF_INDEX }
74     }
75 }
76
77 impl fmt::Display for CrateNum {
78     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79         match self {
80             CrateNum::Index(id) => fmt::Display::fmt(&id.private, f),
81             CrateNum::ReservedForIncrCompCache => write!(f, "crate for decoding incr comp cache"),
82         }
83     }
84 }
85
86 /// As a local identifier, a `CrateNum` is only meaningful within its context, e.g. within a tcx.
87 /// Therefore, make sure to include the context when encode a `CrateNum`.
88 impl rustc_serialize::UseSpecializedEncodable for CrateNum {
89     fn default_encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
90         e.emit_u32(self.as_u32())
91     }
92 }
93 impl rustc_serialize::UseSpecializedDecodable for CrateNum {
94     fn default_decode<D: Decoder>(d: &mut D) -> Result<CrateNum, D::Error> {
95         Ok(CrateNum::from_u32(d.read_u32()?))
96     }
97 }
98
99 impl ::std::fmt::Debug for CrateNum {
100     fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
101         match self {
102             CrateNum::Index(id) => write!(fmt, "crate{}", id.private),
103             CrateNum::ReservedForIncrCompCache => write!(fmt, "crate for decoding incr comp cache"),
104         }
105     }
106 }
107
108 #[derive(
109     Copy,
110     Clone,
111     Hash,
112     PartialEq,
113     Eq,
114     PartialOrd,
115     Ord,
116     Debug,
117     RustcEncodable,
118     RustcDecodable,
119     HashStable_Generic
120 )]
121 pub struct DefPathHash(pub Fingerprint);
122
123 impl Borrow<Fingerprint> for DefPathHash {
124     #[inline]
125     fn borrow(&self) -> &Fingerprint {
126         &self.0
127     }
128 }
129
130 rustc_index::newtype_index! {
131     /// A DefIndex is an index into the hir-map for a crate, identifying a
132     /// particular definition. It should really be considered an interned
133     /// shorthand for a particular DefPath.
134     pub struct DefIndex {
135         DEBUG_FORMAT = "DefIndex({})",
136
137         /// The crate root is always assigned index 0 by the AST Map code,
138         /// thanks to `NodeCollector::new`.
139         const CRATE_DEF_INDEX = 0,
140     }
141 }
142
143 impl rustc_serialize::UseSpecializedEncodable for DefIndex {}
144 impl rustc_serialize::UseSpecializedDecodable for DefIndex {}
145
146 /// A `DefId` identifies a particular *definition*, by combining a crate
147 /// index and a def index.
148 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy)]
149 pub struct DefId {
150     pub krate: CrateNum,
151     pub index: DefIndex,
152 }
153
154 impl DefId {
155     /// Makes a local `DefId` from the given `DefIndex`.
156     #[inline]
157     pub fn local(index: DefIndex) -> DefId {
158         DefId { krate: LOCAL_CRATE, index }
159     }
160
161     #[inline]
162     pub fn is_local(self) -> bool {
163         self.krate == LOCAL_CRATE
164     }
165
166     #[inline]
167     pub fn to_local(self) -> LocalDefId {
168         LocalDefId::from_def_id(self)
169     }
170
171     pub fn is_top_level_module(self) -> bool {
172         self.is_local() && self.index == CRATE_DEF_INDEX
173     }
174 }
175
176 impl rustc_serialize::UseSpecializedEncodable for DefId {
177     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
178         let krate = u64::from(self.krate.as_u32());
179         let index = u64::from(self.index.as_u32());
180         s.emit_u64((krate << 32) | index)
181     }
182 }
183 impl rustc_serialize::UseSpecializedDecodable for DefId {
184     fn default_decode<D: Decoder>(d: &mut D) -> Result<DefId, D::Error> {
185         let def_id = d.read_u64()?;
186         let krate = CrateNum::from_u32((def_id >> 32) as u32);
187         let index = DefIndex::from_u32((def_id & 0xffffffff) as u32);
188         Ok(DefId { krate, index })
189     }
190 }
191
192 pub fn default_def_id_debug(def_id: DefId, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193     f.debug_struct("DefId").field("krate", &def_id.krate).field("index", &def_id.index).finish()
194 }
195
196 pub static DEF_ID_DEBUG: AtomicRef<fn(DefId, &mut fmt::Formatter<'_>) -> fmt::Result> =
197     AtomicRef::new(&(default_def_id_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
198
199 impl fmt::Debug for DefId {
200     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201         (*DEF_ID_DEBUG)(*self, f)
202     }
203 }
204
205 rustc_data_structures::define_id_collections!(DefIdMap, DefIdSet, DefId);
206
207 /// A LocalDefId is equivalent to a DefId with `krate == LOCAL_CRATE`. Since
208 /// we encode this information in the type, we can ensure at compile time that
209 /// no DefIds from upstream crates get thrown into the mix. There are quite a
210 /// few cases where we know that only DefIds from the local crate are expected
211 /// and a DefId from a different crate would signify a bug somewhere. This
212 /// is when LocalDefId comes in handy.
213 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
214 pub struct LocalDefId(DefIndex);
215
216 impl LocalDefId {
217     #[inline]
218     pub fn from_def_id(def_id: DefId) -> LocalDefId {
219         assert!(def_id.is_local());
220         LocalDefId(def_id.index)
221     }
222
223     #[inline]
224     pub fn to_def_id(self) -> DefId {
225         DefId { krate: LOCAL_CRATE, index: self.0 }
226     }
227 }
228
229 impl fmt::Debug for LocalDefId {
230     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231         self.to_def_id().fmt(f)
232     }
233 }
234
235 impl rustc_serialize::UseSpecializedEncodable for LocalDefId {}
236 impl rustc_serialize::UseSpecializedDecodable for LocalDefId {}
237
238 impl<CTX: HashStableContext> HashStable<CTX> for DefId {
239     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
240         hcx.hash_def_id(*self, hasher)
241     }
242 }