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