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.
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.
12 use hir::map::definitions::FIRST_FREE_HIGH_DEF_INDEX;
13 use rustc_data_structures::indexed_vec::Idx;
24 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
26 /// Virtual crate for builtin macros
27 // FIXME(jseyfried): this is also used for custom derives until proc-macro crates get
30 /// A CrateNum value that indicates that something is wrong.
32 /// A special CrateNum that we use for the tcx.rcache when decoding from
33 /// the incr. comp. cache.
34 ReservedForIncrCompCache,
38 impl ::std::fmt::Debug for CrateNum {
39 fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
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"),
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));
54 impl Idx for CrateNum {
56 fn new(value: usize) -> Self {
57 CrateNum::Index(Idx::new(value))
61 fn index(self) -> usize {
63 CrateNum::Index(idx) => Idx::index(idx),
64 _ => bug!("Tried to get crate index of {:?}", self),
70 pub fn new(x: usize) -> CrateNum {
71 CrateNum::from_usize(x)
74 pub fn from_usize(x: usize) -> CrateNum {
75 CrateNum::Index(CrateId::from_usize(x))
78 pub fn from_u32(x: u32) -> CrateNum {
79 CrateNum::Index(CrateId::from_u32(x))
82 pub fn as_usize(self) -> usize {
84 CrateNum::Index(id) => id.as_usize(),
85 _ => bug!("tried to get index of nonstandard crate {:?}", self),
89 pub fn as_u32(self) -> u32 {
91 CrateNum::Index(id) => id.as_u32(),
92 _ => bug!("tried to get index of nonstandard crate {:?}", self),
96 pub fn as_def_id(&self) -> DefId { DefId { krate: *self, index: CRATE_DEF_INDEX } }
99 impl fmt::Display for CrateNum {
100 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
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"),
110 impl serialize::UseSpecializedEncodable for CrateNum {}
111 impl serialize::UseSpecializedDecodable for CrateNum {}
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.
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.
124 /// Since the DefIndex is mostly treated as an opaque ID, you probably
125 /// don't have to care about these address spaces.
127 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy)]
128 pub struct DefIndex(u32);
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);
135 impl fmt::Debug for DefIndex {
136 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
139 self.address_space().index(),
140 self.as_array_index())
146 pub fn address_space(&self) -> DefIndexAddressSpace {
148 0 => DefIndexAddressSpace::Low,
149 1 => DefIndexAddressSpace::High,
154 /// Converts this DefIndex into a zero-based array index.
155 /// This index is the offset within the given DefIndexAddressSpace.
157 pub fn as_array_index(&self) -> usize {
158 (self.0 >> 1) as usize
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)
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
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);
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);
186 self.as_array_index().checked_sub(FIRST_FREE_HIGH_DEF_INDEX)
188 bug!("using local index {:?} as proc-macro index", self)
192 // Don't use this if you don't know about the DefIndex encoding.
193 pub fn from_raw_u32(x: u32) -> DefIndex {
197 // Don't use this if you don't know about the DefIndex encoding.
198 pub fn as_raw_u32(&self) -> u32 {
203 impl serialize::UseSpecializedEncodable for DefIndex {}
204 impl serialize::UseSpecializedDecodable for DefIndex {}
206 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
207 pub enum DefIndexAddressSpace {
212 impl DefIndexAddressSpace {
214 pub fn index(&self) -> usize {
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)]
227 impl fmt::Debug for DefId {
228 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
229 write!(f, "DefId({:?}/{}:{}",
231 self.index.address_space().index(),
232 self.index.as_array_index())?;
234 ty::tls::with_opt(|opt_tcx| {
235 if let Some(tcx) = opt_tcx {
236 write!(f, " ~ {}", tcx.def_path_debug_str(*self))?;
246 /// Make a local `DefId` with the given index.
248 pub fn local(index: DefIndex) -> DefId {
249 DefId { krate: LOCAL_CRATE, index: index }
253 pub fn is_local(self) -> bool {
254 self.krate == LOCAL_CRATE
258 pub fn to_local(self) -> LocalDefId {
259 LocalDefId::from_def_id(self)
263 impl serialize::UseSpecializedEncodable for DefId {}
264 impl serialize::UseSpecializedDecodable for DefId {}
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);
277 pub fn from_def_id(def_id: DefId) -> LocalDefId {
278 assert!(def_id.is_local());
279 LocalDefId(def_id.index)
283 pub fn to_def_id(self) -> DefId {
291 impl fmt::Debug for LocalDefId {
292 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
293 self.to_def_id().fmt(f)
297 impl serialize::UseSpecializedEncodable for LocalDefId {}
298 impl serialize::UseSpecializedDecodable for LocalDefId {}