]> git.lizzy.rs Git - rust.git/blob - src/librustc_span/def_id.rs
Move librustc_hir/def_id.rs to librustc_span/def_id.rs
[rust.git] / src / librustc_span / def_id.rs
1 use crate::HashStableContext;
2 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
3 use rustc_data_structures::AtomicRef;
4 use rustc_index::vec::Idx;
5 use rustc_serialize::{Decoder, Encoder};
6 use std::fmt;
7 use std::{u32, u64};
8
9 rustc_index::newtype_index! {
10     pub struct CrateId {
11         ENCODABLE = custom
12     }
13 }
14
15 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
16 pub enum CrateNum {
17     /// A special `CrateNum` that we use for the `tcx.rcache` when decoding from
18     /// the incr. comp. cache.
19     ReservedForIncrCompCache,
20     Index(CrateId),
21 }
22
23 /// Item definitions in the currently-compiled crate would have the `CrateNum`
24 /// `LOCAL_CRATE` in their `DefId`.
25 pub const LOCAL_CRATE: CrateNum = CrateNum::Index(CrateId::from_u32_const(0));
26
27 impl Idx for CrateNum {
28     #[inline]
29     fn new(value: usize) -> Self {
30         CrateNum::Index(Idx::new(value))
31     }
32
33     #[inline]
34     fn index(self) -> usize {
35         match self {
36             CrateNum::Index(idx) => Idx::index(idx),
37             _ => panic!("Tried to get crate index of {:?}", self),
38         }
39     }
40 }
41
42 impl CrateNum {
43     pub fn new(x: usize) -> CrateNum {
44         CrateNum::from_usize(x)
45     }
46
47     pub fn from_usize(x: usize) -> CrateNum {
48         CrateNum::Index(CrateId::from_usize(x))
49     }
50
51     pub fn from_u32(x: u32) -> CrateNum {
52         CrateNum::Index(CrateId::from_u32(x))
53     }
54
55     pub fn as_usize(self) -> usize {
56         match self {
57             CrateNum::Index(id) => id.as_usize(),
58             _ => panic!("tried to get index of non-standard crate {:?}", self),
59         }
60     }
61
62     pub fn as_u32(self) -> u32 {
63         match self {
64             CrateNum::Index(id) => id.as_u32(),
65             _ => panic!("tried to get index of non-standard crate {:?}", self),
66         }
67     }
68
69     pub fn as_def_id(&self) -> DefId {
70         DefId { krate: *self, index: CRATE_DEF_INDEX }
71     }
72 }
73
74 impl fmt::Display for CrateNum {
75     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76         match self {
77             CrateNum::Index(id) => fmt::Display::fmt(&id.private, f),
78             CrateNum::ReservedForIncrCompCache => write!(f, "crate for decoding incr comp cache"),
79         }
80     }
81 }
82
83 /// As a local identifier, a `CrateNum` is only meaningful within its context, e.g. within a tcx.
84 /// Therefore, make sure to include the context when encode a `CrateNum`.
85 impl rustc_serialize::UseSpecializedEncodable for CrateNum {
86     fn default_encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
87         e.emit_u32(self.as_u32())
88     }
89 }
90 impl rustc_serialize::UseSpecializedDecodable for CrateNum {
91     fn default_decode<D: Decoder>(d: &mut D) -> Result<CrateNum, D::Error> {
92         Ok(CrateNum::from_u32(d.read_u32()?))
93     }
94 }
95
96 impl ::std::fmt::Debug for CrateNum {
97     fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
98         match self {
99             CrateNum::Index(id) => write!(fmt, "crate{}", id.private),
100             CrateNum::ReservedForIncrCompCache => write!(fmt, "crate for decoding incr comp cache"),
101         }
102     }
103 }
104
105 rustc_index::newtype_index! {
106     /// A DefIndex is an index into the hir-map for a crate, identifying a
107     /// particular definition. It should really be considered an interned
108     /// shorthand for a particular DefPath.
109     pub struct DefIndex {
110         DEBUG_FORMAT = "DefIndex({})",
111
112         /// The crate root is always assigned index 0 by the AST Map code,
113         /// thanks to `NodeCollector::new`.
114         const CRATE_DEF_INDEX = 0,
115     }
116 }
117
118 impl rustc_serialize::UseSpecializedEncodable for DefIndex {}
119 impl rustc_serialize::UseSpecializedDecodable for DefIndex {}
120
121 /// A `DefId` identifies a particular *definition*, by combining a crate
122 /// index and a def index.
123 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy)]
124 pub struct DefId {
125     pub krate: CrateNum,
126     pub index: DefIndex,
127 }
128
129 impl DefId {
130     /// Makes a local `DefId` from the given `DefIndex`.
131     #[inline]
132     pub fn local(index: DefIndex) -> DefId {
133         DefId { krate: LOCAL_CRATE, index: index }
134     }
135
136     #[inline]
137     pub fn is_local(self) -> bool {
138         self.krate == LOCAL_CRATE
139     }
140
141     #[inline]
142     pub fn to_local(self) -> LocalDefId {
143         LocalDefId::from_def_id(self)
144     }
145
146     pub fn is_top_level_module(self) -> bool {
147         self.is_local() && self.index == CRATE_DEF_INDEX
148     }
149 }
150
151 impl rustc_serialize::UseSpecializedEncodable for DefId {
152     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
153         let krate = u64::from(self.krate.as_u32());
154         let index = u64::from(self.index.as_u32());
155         s.emit_u64((krate << 32) | index)
156     }
157 }
158 impl rustc_serialize::UseSpecializedDecodable for DefId {
159     fn default_decode<D: Decoder>(d: &mut D) -> Result<DefId, D::Error> {
160         let def_id = d.read_u64()?;
161         let krate = CrateNum::from_u32((def_id >> 32) as u32);
162         let index = DefIndex::from_u32((def_id & 0xffffffff) as u32);
163         Ok(DefId { krate, index })
164     }
165 }
166
167 pub fn default_def_id_debug(def_id: DefId, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168     f.debug_struct("DefId").field("krate", &def_id.krate).field("index", &def_id.index).finish()
169 }
170
171 pub static DEF_ID_DEBUG: AtomicRef<fn(DefId, &mut fmt::Formatter<'_>) -> fmt::Result> =
172     AtomicRef::new(&(default_def_id_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
173
174 impl fmt::Debug for DefId {
175     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176         (*DEF_ID_DEBUG)(*self, f)
177     }
178 }
179
180 rustc_data_structures::define_id_collections!(DefIdMap, DefIdSet, DefId);
181
182 /// A LocalDefId is equivalent to a DefId with `krate == LOCAL_CRATE`. Since
183 /// we encode this information in the type, we can ensure at compile time that
184 /// no DefIds from upstream crates get thrown into the mix. There are quite a
185 /// few cases where we know that only DefIds from the local crate are expected
186 /// and a DefId from a different crate would signify a bug somewhere. This
187 /// is when LocalDefId comes in handy.
188 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
189 pub struct LocalDefId(DefIndex);
190
191 impl LocalDefId {
192     #[inline]
193     pub fn from_def_id(def_id: DefId) -> LocalDefId {
194         assert!(def_id.is_local());
195         LocalDefId(def_id.index)
196     }
197
198     #[inline]
199     pub fn to_def_id(self) -> DefId {
200         DefId { krate: LOCAL_CRATE, index: self.0 }
201     }
202 }
203
204 impl fmt::Debug for LocalDefId {
205     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206         self.to_def_id().fmt(f)
207     }
208 }
209
210 impl rustc_serialize::UseSpecializedEncodable for LocalDefId {}
211 impl rustc_serialize::UseSpecializedDecodable for LocalDefId {}
212
213 impl<CTX: HashStableContext> HashStable<CTX> for DefId {
214     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
215         hcx.hash_def_id(*self, hasher)
216     }
217 }