3 use crate::hir::map::definitions::FIRST_FREE_HIGH_DEF_INDEX;
4 use rustc_data_structures::indexed_vec::Idx;
15 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
17 /// Virtual crate for builtin macros
18 // FIXME(jseyfried): this is also used for custom derives until proc-macro crates get
21 /// A special CrateNum that we use for the tcx.rcache when decoding from
22 /// the incr. comp. cache.
23 ReservedForIncrCompCache,
27 impl ::std::fmt::Debug for CrateNum {
28 fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
30 CrateNum::Index(id) => write!(fmt, "crate{}", id.private),
31 CrateNum::BuiltinMacros => write!(fmt, "builtin macros crate"),
32 CrateNum::ReservedForIncrCompCache => write!(fmt, "crate for decoding incr comp cache"),
37 /// Item definitions in the currently-compiled crate would have the CrateNum
38 /// LOCAL_CRATE in their DefId.
39 pub const LOCAL_CRATE: CrateNum = CrateNum::Index(CrateId::from_u32_const(0));
42 impl Idx for CrateNum {
44 fn new(value: usize) -> Self {
45 CrateNum::Index(Idx::new(value))
49 fn index(self) -> usize {
51 CrateNum::Index(idx) => Idx::index(idx),
52 _ => bug!("Tried to get crate index of {:?}", self),
58 pub fn new(x: usize) -> CrateNum {
59 CrateNum::from_usize(x)
62 pub fn from_usize(x: usize) -> CrateNum {
63 CrateNum::Index(CrateId::from_usize(x))
66 pub fn from_u32(x: u32) -> CrateNum {
67 CrateNum::Index(CrateId::from_u32(x))
70 pub fn as_usize(self) -> usize {
72 CrateNum::Index(id) => id.as_usize(),
73 _ => bug!("tried to get index of nonstandard crate {:?}", self),
77 pub fn as_u32(self) -> u32 {
79 CrateNum::Index(id) => id.as_u32(),
80 _ => bug!("tried to get index of nonstandard crate {:?}", self),
84 pub fn as_def_id(&self) -> DefId { DefId { krate: *self, index: CRATE_DEF_INDEX } }
87 impl fmt::Display for CrateNum {
88 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 CrateNum::Index(id) => fmt::Display::fmt(&id.private, f),
91 CrateNum::BuiltinMacros => write!(f, "builtin macros crate"),
92 CrateNum::ReservedForIncrCompCache => write!(f, "crate for decoding incr comp cache"),
97 impl serialize::UseSpecializedEncodable for CrateNum {}
98 impl serialize::UseSpecializedDecodable for CrateNum {}
100 /// A DefIndex is an index into the hir-map for a crate, identifying a
101 /// particular definition. It should really be considered an interned
102 /// shorthand for a particular DefPath.
104 /// At the moment we are allocating the numerical values of DefIndexes from two
105 /// address spaces: DefIndexAddressSpace::Low and DefIndexAddressSpace::High.
106 /// This allows us to allocate the DefIndexes of all item-likes
107 /// (Items, TraitItems, and ImplItems) into one of these spaces and
108 /// consequently use a simple array for lookup tables keyed by DefIndex and
109 /// known to be densely populated. This is especially important for the HIR map.
111 /// Since the DefIndex is mostly treated as an opaque ID, you probably
112 /// don't have to care about these address spaces.
114 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy)]
115 pub struct DefIndex(u32);
117 /// The crate root is always assigned index 0 by the AST Map code,
118 /// thanks to `NodeCollector::new`.
119 pub const CRATE_DEF_INDEX: DefIndex = DefIndex(0);
121 impl fmt::Debug for DefIndex {
122 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125 self.address_space().index(),
126 self.as_array_index())
132 pub fn address_space(&self) -> DefIndexAddressSpace {
134 0 => DefIndexAddressSpace::Low,
135 1 => DefIndexAddressSpace::High,
140 /// Converts this DefIndex into a zero-based array index.
141 /// This index is the offset within the given DefIndexAddressSpace.
143 pub fn as_array_index(&self) -> usize {
144 (self.0 >> 1) as usize
148 pub fn from_array_index(i: usize, address_space: DefIndexAddressSpace) -> DefIndex {
149 DefIndex::from_raw_u32(((i << 1) | (address_space as usize)) as u32)
152 // Proc macros from a proc-macro crate have a kind of virtual DefIndex. This
153 // function maps the index of the macro within the crate (which is also the
154 // index of the macro in the CrateMetadata::proc_macros array) to the
155 // corresponding DefIndex.
156 pub fn from_proc_macro_index(proc_macro_index: usize) -> DefIndex {
157 // DefIndex for proc macros start from FIRST_FREE_HIGH_DEF_INDEX,
158 // because the first FIRST_FREE_HIGH_DEF_INDEX indexes are reserved
160 let def_index = DefIndex::from_array_index(
161 proc_macro_index.checked_add(FIRST_FREE_HIGH_DEF_INDEX)
162 .expect("integer overflow adding `proc_macro_index`"),
163 DefIndexAddressSpace::High);
164 assert!(def_index != CRATE_DEF_INDEX);
168 // This function is the reverse of from_proc_macro_index() above.
169 pub fn to_proc_macro_index(self: DefIndex) -> usize {
170 assert_eq!(self.address_space(), DefIndexAddressSpace::High);
172 self.as_array_index().checked_sub(FIRST_FREE_HIGH_DEF_INDEX)
174 bug!("using local index {:?} as proc-macro index", self)
178 // Don't use this if you don't know about the DefIndex encoding.
179 pub fn from_raw_u32(x: u32) -> DefIndex {
183 // Don't use this if you don't know about the DefIndex encoding.
184 pub fn as_raw_u32(&self) -> u32 {
189 impl serialize::UseSpecializedEncodable for DefIndex {}
190 impl serialize::UseSpecializedDecodable for DefIndex {}
192 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
193 pub enum DefIndexAddressSpace {
198 impl DefIndexAddressSpace {
200 pub fn index(&self) -> usize {
205 /// A `DefId` identifies a particular *definition*, by combining a crate
206 /// index and a def index.
207 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy)]
213 impl fmt::Debug for DefId {
214 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215 write!(f, "DefId({}/{}:{}",
217 self.index.address_space().index(),
218 self.index.as_array_index())?;
220 ty::tls::with_opt(|opt_tcx| {
221 if let Some(tcx) = opt_tcx {
222 write!(f, " ~ {}", tcx.def_path_debug_str(*self))?;
232 /// Makes a local `DefId` from the given `DefIndex`.
234 pub fn local(index: DefIndex) -> DefId {
235 DefId { krate: LOCAL_CRATE, index: index }
239 pub fn is_local(self) -> bool {
240 self.krate == LOCAL_CRATE
244 pub fn to_local(self) -> LocalDefId {
245 LocalDefId::from_def_id(self)
248 pub fn describe_as_module(&self, tcx: TyCtxt<'_, '_, '_>) -> String {
249 if self.is_local() && self.index == CRATE_DEF_INDEX {
250 format!("top-level module")
252 format!("module `{}`", tcx.item_path_str(*self))
257 impl serialize::UseSpecializedEncodable for DefId {}
258 impl serialize::UseSpecializedDecodable for DefId {}
260 /// A LocalDefId is equivalent to a DefId with `krate == LOCAL_CRATE`. Since
261 /// we encode this information in the type, we can ensure at compile time that
262 /// no DefIds from upstream crates get thrown into the mix. There are quite a
263 /// few cases where we know that only DefIds from the local crate are expected
264 /// and a DefId from a different crate would signify a bug somewhere. This
265 /// is when LocalDefId comes in handy.
266 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
267 pub struct LocalDefId(DefIndex);
271 pub fn from_def_id(def_id: DefId) -> LocalDefId {
272 assert!(def_id.is_local());
273 LocalDefId(def_id.index)
277 pub fn to_def_id(self) -> DefId {
285 impl fmt::Debug for LocalDefId {
286 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287 self.to_def_id().fmt(f)
291 impl serialize::UseSpecializedEncodable for LocalDefId {}
292 impl serialize::UseSpecializedDecodable for LocalDefId {}