]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/def_id.rs
Rollup merge of #54989 - Munksgaard:fix-htmldocck-typos, r=tmandry
[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 impl fmt::Debug for DefIndex {
135     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136         write!(f,
137                "DefIndex({}:{})",
138                self.address_space().index(),
139                self.as_array_index())
140     }
141 }
142
143 impl DefIndex {
144     #[inline]
145     pub fn address_space(&self) -> DefIndexAddressSpace {
146         match self.0 & 1 {
147             0 => DefIndexAddressSpace::Low,
148             1 => DefIndexAddressSpace::High,
149             _ => unreachable!()
150         }
151     }
152
153     /// Converts this DefIndex into a zero-based array index.
154     /// This index is the offset within the given DefIndexAddressSpace.
155     #[inline]
156     pub fn as_array_index(&self) -> usize {
157         (self.0 >> 1) as usize
158     }
159
160     #[inline]
161     pub fn from_array_index(i: usize, address_space: DefIndexAddressSpace) -> DefIndex {
162         DefIndex::from_raw_u32(((i << 1) | (address_space as usize)) as u32)
163     }
164
165     // Proc macros from a proc-macro crate have a kind of virtual DefIndex. This
166     // function maps the index of the macro within the crate (which is also the
167     // index of the macro in the CrateMetadata::proc_macros array) to the
168     // corresponding DefIndex.
169     pub fn from_proc_macro_index(proc_macro_index: usize) -> DefIndex {
170         // DefIndex for proc macros start from FIRST_FREE_HIGH_DEF_INDEX,
171         // because the first FIRST_FREE_HIGH_DEF_INDEX indexes are reserved
172         // for internal use.
173         let def_index = DefIndex::from_array_index(
174             proc_macro_index.checked_add(FIRST_FREE_HIGH_DEF_INDEX)
175                 .expect("integer overflow adding `proc_macro_index`"),
176             DefIndexAddressSpace::High);
177         assert!(def_index != CRATE_DEF_INDEX);
178         def_index
179     }
180
181     // This function is the reverse of from_proc_macro_index() above.
182     pub fn to_proc_macro_index(self: DefIndex) -> usize {
183         assert_eq!(self.address_space(), DefIndexAddressSpace::High);
184
185         self.as_array_index().checked_sub(FIRST_FREE_HIGH_DEF_INDEX)
186             .unwrap_or_else(|| {
187                 bug!("using local index {:?} as proc-macro index", self)
188             })
189     }
190
191     // Don't use this if you don't know about the DefIndex encoding.
192     pub fn from_raw_u32(x: u32) -> DefIndex {
193         DefIndex(x)
194     }
195
196     // Don't use this if you don't know about the DefIndex encoding.
197     pub fn as_raw_u32(&self) -> u32 {
198         self.0
199     }
200 }
201
202 impl serialize::UseSpecializedEncodable for DefIndex {}
203 impl serialize::UseSpecializedDecodable for DefIndex {}
204
205 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
206 pub enum DefIndexAddressSpace {
207     Low = 0,
208     High = 1,
209 }
210
211 impl DefIndexAddressSpace {
212     #[inline]
213     pub fn index(&self) -> usize {
214         *self as usize
215     }
216 }
217
218 /// A `DefId` identifies a particular *definition*, by combining a crate
219 /// index and a def index.
220 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy)]
221 pub struct DefId {
222     pub krate: CrateNum,
223     pub index: DefIndex,
224 }
225
226 impl fmt::Debug for DefId {
227     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228         write!(f, "DefId({:?}/{}:{}",
229                self.krate.index(),
230                self.index.address_space().index(),
231                self.index.as_array_index())?;
232
233         ty::tls::with_opt(|opt_tcx| {
234             if let Some(tcx) = opt_tcx {
235                 write!(f, " ~ {}", tcx.def_path_debug_str(*self))?;
236             }
237             Ok(())
238         })?;
239
240         write!(f, ")")
241     }
242 }
243
244 impl DefId {
245     /// Make a local `DefId` with the given index.
246     #[inline]
247     pub fn local(index: DefIndex) -> DefId {
248         DefId { krate: LOCAL_CRATE, index: index }
249     }
250
251     #[inline]
252     pub fn is_local(self) -> bool {
253         self.krate == LOCAL_CRATE
254     }
255
256     #[inline]
257     pub fn to_local(self) -> LocalDefId {
258         LocalDefId::from_def_id(self)
259     }
260 }
261
262 impl serialize::UseSpecializedEncodable for DefId {}
263 impl serialize::UseSpecializedDecodable for DefId {}
264
265 /// A LocalDefId is equivalent to a DefId with `krate == LOCAL_CRATE`. Since
266 /// we encode this information in the type, we can ensure at compile time that
267 /// no DefIds from upstream crates get thrown into the mix. There are quite a
268 /// few cases where we know that only DefIds from the local crate are expected
269 /// and a DefId from a different crate would signify a bug somewhere. This
270 /// is when LocalDefId comes in handy.
271 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
272 pub struct LocalDefId(DefIndex);
273
274 impl LocalDefId {
275     #[inline]
276     pub fn from_def_id(def_id: DefId) -> LocalDefId {
277         assert!(def_id.is_local());
278         LocalDefId(def_id.index)
279     }
280
281     #[inline]
282     pub fn to_def_id(self) -> DefId {
283         DefId {
284             krate: LOCAL_CRATE,
285             index: self.0
286         }
287     }
288 }
289
290 impl fmt::Debug for LocalDefId {
291     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
292         self.to_def_id().fmt(f)
293     }
294 }
295
296 impl serialize::UseSpecializedEncodable for LocalDefId {}
297 impl serialize::UseSpecializedDecodable for LocalDefId {}