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