]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/def_id.rs
Remove `CrateNum::Invalid`.
[rust.git] / src / librustc / hir / def_id.rs
1 use ty;
2 use hir::map::definitions::FIRST_FREE_HIGH_DEF_INDEX;
3 use rustc_data_structures::indexed_vec::Idx;
4 use serialize;
5 use std::fmt;
6 use std::u32;
7
8 newtype_index! {
9     pub struct CrateId {
10         ENCODABLE = custom
11     }
12 }
13
14 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
15 pub enum CrateNum {
16     /// Virtual crate for builtin macros
17     // FIXME(jseyfried): this is also used for custom derives until proc-macro crates get
18     // `CrateNum`s.
19     BuiltinMacros,
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 impl ::std::fmt::Debug for CrateNum {
27     fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
28         match self {
29             CrateNum::Index(id) => write!(fmt, "crate{}", id.private),
30             CrateNum::BuiltinMacros => write!(fmt, "builtin macros crate"),
31             CrateNum::ReservedForIncrCompCache => write!(fmt, "crate for decoding incr comp cache"),
32         }
33     }
34 }
35
36 /// Item definitions in the currently-compiled crate would have the CrateNum
37 /// LOCAL_CRATE in their DefId.
38 pub const LOCAL_CRATE: CrateNum = CrateNum::Index(CrateId::from_u32_const(0));
39
40
41 impl Idx for CrateNum {
42     #[inline]
43     fn new(value: usize) -> Self {
44         CrateNum::Index(Idx::new(value))
45     }
46
47     #[inline]
48     fn index(self) -> usize {
49         match self {
50             CrateNum::Index(idx) => Idx::index(idx),
51             _ => bug!("Tried to get crate index of {:?}", self),
52         }
53     }
54 }
55
56 impl CrateNum {
57     pub fn new(x: usize) -> CrateNum {
58         CrateNum::from_usize(x)
59     }
60
61     pub fn from_usize(x: usize) -> CrateNum {
62         CrateNum::Index(CrateId::from_usize(x))
63     }
64
65     pub fn from_u32(x: u32) -> CrateNum {
66         CrateNum::Index(CrateId::from_u32(x))
67     }
68
69     pub fn as_usize(self) -> usize {
70         match self {
71             CrateNum::Index(id) => id.as_usize(),
72             _ => bug!("tried to get index of nonstandard crate {:?}", self),
73         }
74     }
75
76     pub fn as_u32(self) -> u32 {
77         match self {
78             CrateNum::Index(id) => id.as_u32(),
79             _ => bug!("tried to get index of nonstandard crate {:?}", self),
80         }
81     }
82
83     pub fn as_def_id(&self) -> DefId { DefId { krate: *self, index: CRATE_DEF_INDEX } }
84 }
85
86 impl fmt::Display for CrateNum {
87     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88         match self {
89             CrateNum::Index(id) => fmt::Display::fmt(&id.private, f),
90             CrateNum::BuiltinMacros => write!(f, "builtin macros crate"),
91             CrateNum::ReservedForIncrCompCache => write!(f, "crate for decoding incr comp cache"),
92         }
93     }
94 }
95
96 impl serialize::UseSpecializedEncodable for CrateNum {}
97 impl serialize::UseSpecializedDecodable for CrateNum {}
98
99 /// A DefIndex is an index into the hir-map for a crate, identifying a
100 /// particular definition. It should really be considered an interned
101 /// shorthand for a particular DefPath.
102 ///
103 /// At the moment we are allocating the numerical values of DefIndexes from two
104 /// address spaces: DefIndexAddressSpace::Low and DefIndexAddressSpace::High.
105 /// This allows us to allocate the DefIndexes of all item-likes
106 /// (Items, TraitItems, and ImplItems) into one of these spaces and
107 /// consequently use a simple array for lookup tables keyed by DefIndex and
108 /// known to be densely populated. This is especially important for the HIR map.
109 ///
110 /// Since the DefIndex is mostly treated as an opaque ID, you probably
111 /// don't have to care about these address spaces.
112
113 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy)]
114 pub struct DefIndex(u32);
115
116 /// The crate root is always assigned index 0 by the AST Map code,
117 /// thanks to `NodeCollector::new`.
118 pub const CRATE_DEF_INDEX: DefIndex = DefIndex(0);
119
120 impl fmt::Debug for DefIndex {
121     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122         write!(f,
123                "DefIndex({}:{})",
124                self.address_space().index(),
125                self.as_array_index())
126     }
127 }
128
129 impl DefIndex {
130     #[inline]
131     pub fn address_space(&self) -> DefIndexAddressSpace {
132         match self.0 & 1 {
133             0 => DefIndexAddressSpace::Low,
134             1 => DefIndexAddressSpace::High,
135             _ => unreachable!()
136         }
137     }
138
139     /// Converts this DefIndex into a zero-based array index.
140     /// This index is the offset within the given DefIndexAddressSpace.
141     #[inline]
142     pub fn as_array_index(&self) -> usize {
143         (self.0 >> 1) as usize
144     }
145
146     #[inline]
147     pub fn from_array_index(i: usize, address_space: DefIndexAddressSpace) -> DefIndex {
148         DefIndex::from_raw_u32(((i << 1) | (address_space as usize)) as u32)
149     }
150
151     // Proc macros from a proc-macro crate have a kind of virtual DefIndex. This
152     // function maps the index of the macro within the crate (which is also the
153     // index of the macro in the CrateMetadata::proc_macros array) to the
154     // corresponding DefIndex.
155     pub fn from_proc_macro_index(proc_macro_index: usize) -> DefIndex {
156         // DefIndex for proc macros start from FIRST_FREE_HIGH_DEF_INDEX,
157         // because the first FIRST_FREE_HIGH_DEF_INDEX indexes are reserved
158         // for internal use.
159         let def_index = DefIndex::from_array_index(
160             proc_macro_index.checked_add(FIRST_FREE_HIGH_DEF_INDEX)
161                 .expect("integer overflow adding `proc_macro_index`"),
162             DefIndexAddressSpace::High);
163         assert!(def_index != CRATE_DEF_INDEX);
164         def_index
165     }
166
167     // This function is the reverse of from_proc_macro_index() above.
168     pub fn to_proc_macro_index(self: DefIndex) -> usize {
169         assert_eq!(self.address_space(), DefIndexAddressSpace::High);
170
171         self.as_array_index().checked_sub(FIRST_FREE_HIGH_DEF_INDEX)
172             .unwrap_or_else(|| {
173                 bug!("using local index {:?} as proc-macro index", self)
174             })
175     }
176
177     // Don't use this if you don't know about the DefIndex encoding.
178     pub fn from_raw_u32(x: u32) -> DefIndex {
179         DefIndex(x)
180     }
181
182     // Don't use this if you don't know about the DefIndex encoding.
183     pub fn as_raw_u32(&self) -> u32 {
184         self.0
185     }
186 }
187
188 impl serialize::UseSpecializedEncodable for DefIndex {}
189 impl serialize::UseSpecializedDecodable for DefIndex {}
190
191 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
192 pub enum DefIndexAddressSpace {
193     Low = 0,
194     High = 1,
195 }
196
197 impl DefIndexAddressSpace {
198     #[inline]
199     pub fn index(&self) -> usize {
200         *self as usize
201     }
202 }
203
204 /// A `DefId` identifies a particular *definition*, by combining a crate
205 /// index and a def index.
206 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy)]
207 pub struct DefId {
208     pub krate: CrateNum,
209     pub index: DefIndex,
210 }
211
212 impl fmt::Debug for DefId {
213     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214         write!(f, "DefId({}/{}:{}",
215                self.krate,
216                self.index.address_space().index(),
217                self.index.as_array_index())?;
218
219         ty::tls::with_opt(|opt_tcx| {
220             if let Some(tcx) = opt_tcx {
221                 write!(f, " ~ {}", tcx.def_path_debug_str(*self))?;
222             }
223             Ok(())
224         })?;
225
226         write!(f, ")")
227     }
228 }
229
230 impl DefId {
231     /// Make a local `DefId` with the given index.
232     #[inline]
233     pub fn local(index: DefIndex) -> DefId {
234         DefId { krate: LOCAL_CRATE, index: index }
235     }
236
237     #[inline]
238     pub fn is_local(self) -> bool {
239         self.krate == LOCAL_CRATE
240     }
241
242     #[inline]
243     pub fn to_local(self) -> LocalDefId {
244         LocalDefId::from_def_id(self)
245     }
246 }
247
248 impl serialize::UseSpecializedEncodable for DefId {}
249 impl serialize::UseSpecializedDecodable for DefId {}
250
251 /// A LocalDefId is equivalent to a DefId with `krate == LOCAL_CRATE`. Since
252 /// we encode this information in the type, we can ensure at compile time that
253 /// no DefIds from upstream crates get thrown into the mix. There are quite a
254 /// few cases where we know that only DefIds from the local crate are expected
255 /// and a DefId from a different crate would signify a bug somewhere. This
256 /// is when LocalDefId comes in handy.
257 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
258 pub struct LocalDefId(DefIndex);
259
260 impl LocalDefId {
261     #[inline]
262     pub fn from_def_id(def_id: DefId) -> LocalDefId {
263         assert!(def_id.is_local());
264         LocalDefId(def_id.index)
265     }
266
267     #[inline]
268     pub fn to_def_id(self) -> DefId {
269         DefId {
270             krate: LOCAL_CRATE,
271             index: self.0
272         }
273     }
274 }
275
276 impl fmt::Debug for LocalDefId {
277     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
278         self.to_def_id().fmt(f)
279     }
280 }
281
282 impl serialize::UseSpecializedEncodable for LocalDefId {}
283 impl serialize::UseSpecializedDecodable for LocalDefId {}