]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/def_id.rs
newtype_index: Support simpler serializable override, custom derive, and fix mir_opt...
[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::{self, Encoder, Decoder};
15
16 use std::fmt;
17 use std::u32;
18
19 newtype_index!(CrateNum nopub
20     {
21         derive[Debug]
22         ENCODABLE = custom
23
24         /// Item definitions in the currently-compiled crate would have the CrateNum
25         /// LOCAL_CRATE in their DefId.
26         const LOCAL_CRATE = 0,
27
28         /// Virtual crate for builtin macros
29         // FIXME(jseyfried): this is also used for custom derives until proc-macro crates get
30         // `CrateNum`s.
31         const BUILTIN_MACROS_CRATE = u32::MAX,
32
33         /// A CrateNum value that indicates that something is wrong.
34         const INVALID_CRATE = u32::MAX - 1,
35     });
36
37 impl CrateNum {
38     pub fn new(x: usize) -> CrateNum {
39         assert!(x < (u32::MAX as usize));
40         CrateNum(x as u32)
41     }
42
43     pub fn from_u32(x: u32) -> CrateNum {
44         CrateNum(x)
45     }
46
47     pub fn as_usize(&self) -> usize {
48         self.0 as usize
49     }
50
51     pub fn as_u32(&self) -> u32 {
52         self.0
53     }
54
55     pub fn as_def_id(&self) -> DefId { DefId { krate: *self, index: CRATE_DEF_INDEX } }
56 }
57
58 impl fmt::Display for CrateNum {
59     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
60         fmt::Display::fmt(&self.0, f)
61     }
62 }
63
64 impl serialize::UseSpecializedEncodable for CrateNum {
65     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
66         s.emit_u32(self.0)
67     }
68 }
69
70 impl serialize::UseSpecializedDecodable for CrateNum {
71     fn default_decode<D: Decoder>(d: &mut D) -> Result<CrateNum, D::Error> {
72         d.read_u32().map(CrateNum)
73     }
74 }
75
76 /// A DefIndex is an index into the hir-map for a crate, identifying a
77 /// particular definition. It should really be considered an interned
78 /// shorthand for a particular DefPath.
79 ///
80 /// At the moment we are allocating the numerical values of DefIndexes into two
81 /// ranges: the "low" range (starting at zero) and the "high" range (starting at
82 /// DEF_INDEX_HI_START). This allows us to allocate the DefIndexes of all
83 /// item-likes (Items, TraitItems, and ImplItems) into one of these ranges and
84 /// consequently use a simple array for lookup tables keyed by DefIndex and
85 /// known to be densely populated. This is especially important for the HIR map.
86 ///
87 /// Since the DefIndex is mostly treated as an opaque ID, you probably
88 /// don't have to care about these ranges.
89 #[derive(Clone, Eq, Ord, PartialOrd, PartialEq, RustcEncodable,
90            RustcDecodable, Hash, Copy)]
91 pub struct DefIndex(u32);
92
93 impl Idx for DefIndex {
94     fn new(value: usize) -> Self {
95         assert!(value < (u32::MAX) as usize);
96         DefIndex(value as u32)
97     }
98
99     fn index(self) -> usize {
100         self.0 as usize
101     }
102 }
103
104 impl fmt::Debug for DefIndex {
105     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
106         write!(f,
107                "DefIndex({}:{})",
108                self.address_space().index(),
109                self.as_array_index())
110     }
111 }
112
113 impl DefIndex {
114     #[inline]
115     pub fn new(x: usize) -> DefIndex {
116         assert!(x < (u32::MAX as usize));
117         DefIndex(x as u32)
118     }
119
120     #[inline]
121     pub fn from_u32(x: u32) -> DefIndex {
122         DefIndex(x)
123     }
124
125     #[inline]
126     pub fn as_usize(&self) -> usize {
127         self.0 as usize
128     }
129
130     #[inline]
131     pub fn as_u32(&self) -> u32 {
132         self.0
133     }
134
135     #[inline]
136     pub fn address_space(&self) -> DefIndexAddressSpace {
137         if self.0 < DEF_INDEX_HI_START.0 {
138             DefIndexAddressSpace::Low
139         } else {
140             DefIndexAddressSpace::High
141         }
142     }
143
144     /// Converts this DefIndex into a zero-based array index.
145     /// This index is the offset within the given "range" of the DefIndex,
146     /// that is, if the DefIndex is part of the "high" range, the resulting
147     /// index will be (DefIndex - DEF_INDEX_HI_START).
148     #[inline]
149     pub fn as_array_index(&self) -> usize {
150         (self.0 & !DEF_INDEX_HI_START.0) as usize
151     }
152
153     pub fn from_array_index(i: usize, address_space: DefIndexAddressSpace) -> DefIndex {
154         DefIndex::new(address_space.start() + i)
155     }
156 }
157
158 /// The start of the "high" range of DefIndexes.
159 const DEF_INDEX_HI_START: DefIndex = DefIndex(1 << 31);
160
161 /// The crate root is always assigned index 0 by the AST Map code,
162 /// thanks to `NodeCollector::new`.
163 pub const CRATE_DEF_INDEX: DefIndex = DefIndex(0);
164
165 #[derive(Copy, Clone, Eq, PartialEq, Hash)]
166 pub enum DefIndexAddressSpace {
167     Low = 0,
168     High = 1,
169 }
170
171 impl DefIndexAddressSpace {
172     #[inline]
173     pub fn index(&self) -> usize {
174         *self as usize
175     }
176
177     #[inline]
178     pub fn start(&self) -> usize {
179         self.index() * DEF_INDEX_HI_START.as_usize()
180     }
181 }
182
183 /// A DefId identifies a particular *definition*, by combining a crate
184 /// index and a def index.
185 #[derive(Clone, Eq, Ord, PartialOrd, PartialEq, RustcEncodable, RustcDecodable, Hash, Copy)]
186 pub struct DefId {
187     pub krate: CrateNum,
188     pub index: DefIndex,
189 }
190
191 impl fmt::Debug for DefId {
192     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
193         write!(f, "DefId {{ krate: {:?}, index: {:?}",
194                self.krate, self.index)?;
195
196         ty::tls::with_opt(|opt_tcx| {
197             if let Some(tcx) = opt_tcx {
198                 write!(f, " => {}", tcx.def_path_debug_str(*self))?;
199             }
200             Ok(())
201         })?;
202
203         write!(f, " }}")
204     }
205 }
206
207
208 impl DefId {
209     /// Make a local `DefId` with the given index.
210     pub fn local(index: DefIndex) -> DefId {
211         DefId { krate: LOCAL_CRATE, index: index }
212     }
213
214     pub fn is_local(&self) -> bool {
215         self.krate == LOCAL_CRATE
216     }
217 }