]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_span/src/def_id.rs
Rollup merge of #82645 - rkjnsn:patch-3, r=Mark-Simulacrum
[rust.git] / compiler / rustc_span / src / def_id.rs
1 use crate::HashStableContext;
2 use rustc_data_structures::fingerprint::Fingerprint;
3 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
4 use rustc_data_structures::AtomicRef;
5 use rustc_index::vec::Idx;
6 use rustc_macros::HashStable_Generic;
7 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
8 use std::borrow::Borrow;
9 use std::fmt;
10
11 rustc_index::newtype_index! {
12     pub struct CrateId {
13         ENCODABLE = custom
14     }
15 }
16
17 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
18 pub enum CrateNum {
19     /// A special `CrateNum` that we use for the `tcx.rcache` when decoding from
20     /// the incr. comp. cache.
21     ReservedForIncrCompCache,
22     Index(CrateId),
23 }
24
25 /// Item definitions in the currently-compiled crate would have the `CrateNum`
26 /// `LOCAL_CRATE` in their `DefId`.
27 pub const LOCAL_CRATE: CrateNum = CrateNum::Index(CrateId::from_u32(0));
28
29 impl Idx for CrateNum {
30     #[inline]
31     fn new(value: usize) -> Self {
32         CrateNum::Index(Idx::new(value))
33     }
34
35     #[inline]
36     fn index(self) -> usize {
37         match self {
38             CrateNum::Index(idx) => Idx::index(idx),
39             _ => panic!("Tried to get crate index of {:?}", self),
40         }
41     }
42 }
43
44 impl CrateNum {
45     pub fn new(x: usize) -> CrateNum {
46         CrateNum::from_usize(x)
47     }
48
49     pub fn from_usize(x: usize) -> CrateNum {
50         CrateNum::Index(CrateId::from_usize(x))
51     }
52
53     pub fn from_u32(x: u32) -> CrateNum {
54         CrateNum::Index(CrateId::from_u32(x))
55     }
56
57     pub fn as_usize(self) -> usize {
58         match self {
59             CrateNum::Index(id) => id.as_usize(),
60             _ => panic!("tried to get index of non-standard crate {:?}", self),
61         }
62     }
63
64     pub fn as_u32(self) -> u32 {
65         match self {
66             CrateNum::Index(id) => id.as_u32(),
67             _ => panic!("tried to get index of non-standard crate {:?}", self),
68         }
69     }
70
71     pub fn as_def_id(&self) -> DefId {
72         DefId { krate: *self, index: CRATE_DEF_INDEX }
73     }
74 }
75
76 impl fmt::Display for CrateNum {
77     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78         match self {
79             CrateNum::Index(id) => fmt::Display::fmt(&id.private, f),
80             CrateNum::ReservedForIncrCompCache => write!(f, "crate for decoding incr comp cache"),
81         }
82     }
83 }
84
85 /// As a local identifier, a `CrateNum` is only meaningful within its context, e.g. within a tcx.
86 /// Therefore, make sure to include the context when encode a `CrateNum`.
87 impl<E: Encoder> Encodable<E> for CrateNum {
88     default fn encode(&self, s: &mut E) -> Result<(), E::Error> {
89         s.emit_u32(self.as_u32())
90     }
91 }
92
93 impl<D: Decoder> Decodable<D> for CrateNum {
94     default fn decode(d: &mut D) -> Result<CrateNum, D::Error> {
95         Ok(CrateNum::from_u32(d.read_u32()?))
96     }
97 }
98
99 impl ::std::fmt::Debug for CrateNum {
100     fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
101         match self {
102             CrateNum::Index(id) => write!(fmt, "crate{}", id.private),
103             CrateNum::ReservedForIncrCompCache => write!(fmt, "crate for decoding incr comp cache"),
104         }
105     }
106 }
107
108 #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Debug)]
109 #[derive(HashStable_Generic, Encodable, Decodable)]
110 pub struct DefPathHash(pub Fingerprint);
111
112 impl Borrow<Fingerprint> for DefPathHash {
113     #[inline]
114     fn borrow(&self) -> &Fingerprint {
115         &self.0
116     }
117 }
118
119 rustc_index::newtype_index! {
120     /// A DefIndex is an index into the hir-map for a crate, identifying a
121     /// particular definition. It should really be considered an interned
122     /// shorthand for a particular DefPath.
123     pub struct DefIndex {
124         ENCODABLE = custom // (only encodable in metadata)
125
126         DEBUG_FORMAT = "DefIndex({})",
127         /// The crate root is always assigned index 0 by the AST Map code,
128         /// thanks to `NodeCollector::new`.
129         const CRATE_DEF_INDEX = 0,
130     }
131 }
132
133 impl<E: Encoder> Encodable<E> for DefIndex {
134     default fn encode(&self, _: &mut E) -> Result<(), E::Error> {
135         panic!("cannot encode `DefIndex` with `{}`", std::any::type_name::<E>());
136     }
137 }
138
139 impl<D: Decoder> Decodable<D> for DefIndex {
140     default fn decode(_: &mut D) -> Result<DefIndex, D::Error> {
141         panic!("cannot decode `DefIndex` with `{}`", std::any::type_name::<D>());
142     }
143 }
144
145 /// A `DefId` identifies a particular *definition*, by combining a crate
146 /// index and a def index.
147 ///
148 /// You can create a `DefId` from a `LocalDefId` using `local_def_id.to_def_id()`.
149 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy)]
150 pub struct DefId {
151     pub krate: CrateNum,
152     pub index: DefIndex,
153 }
154
155 impl DefId {
156     /// Makes a local `DefId` from the given `DefIndex`.
157     #[inline]
158     pub fn local(index: DefIndex) -> DefId {
159         DefId { krate: LOCAL_CRATE, index }
160     }
161
162     /// Returns whether the item is defined in the crate currently being compiled.
163     #[inline]
164     pub fn is_local(self) -> bool {
165         self.krate == LOCAL_CRATE
166     }
167
168     #[inline]
169     pub fn as_local(self) -> Option<LocalDefId> {
170         if self.is_local() { Some(LocalDefId { local_def_index: self.index }) } else { None }
171     }
172
173     #[inline]
174     pub fn expect_local(self) -> LocalDefId {
175         self.as_local().unwrap_or_else(|| panic!("DefId::expect_local: `{:?}` isn't local", self))
176     }
177
178     pub fn is_top_level_module(self) -> bool {
179         self.is_local() && self.index == CRATE_DEF_INDEX
180     }
181 }
182
183 impl<E: Encoder> Encodable<E> for DefId {
184     default fn encode(&self, s: &mut E) -> Result<(), E::Error> {
185         s.emit_struct("DefId", 2, |s| {
186             s.emit_struct_field("krate", 0, |s| self.krate.encode(s))?;
187
188             s.emit_struct_field("index", 1, |s| self.index.encode(s))
189         })
190     }
191 }
192
193 impl<D: Decoder> Decodable<D> for DefId {
194     default fn decode(d: &mut D) -> Result<DefId, D::Error> {
195         d.read_struct("DefId", 2, |d| {
196             Ok(DefId {
197                 krate: d.read_struct_field("krate", 0, Decodable::decode)?,
198                 index: d.read_struct_field("index", 1, Decodable::decode)?,
199             })
200         })
201     }
202 }
203
204 pub fn default_def_id_debug(def_id: DefId, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205     f.debug_struct("DefId").field("krate", &def_id.krate).field("index", &def_id.index).finish()
206 }
207
208 pub static DEF_ID_DEBUG: AtomicRef<fn(DefId, &mut fmt::Formatter<'_>) -> fmt::Result> =
209     AtomicRef::new(&(default_def_id_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
210
211 impl fmt::Debug for DefId {
212     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213         (*DEF_ID_DEBUG)(*self, f)
214     }
215 }
216
217 rustc_data_structures::define_id_collections!(DefIdMap, DefIdSet, DefId);
218
219 /// A LocalDefId is equivalent to a DefId with `krate == LOCAL_CRATE`. Since
220 /// we encode this information in the type, we can ensure at compile time that
221 /// no DefIds from upstream crates get thrown into the mix. There are quite a
222 /// few cases where we know that only DefIds from the local crate are expected
223 /// and a DefId from a different crate would signify a bug somewhere. This
224 /// is when LocalDefId comes in handy.
225 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
226 pub struct LocalDefId {
227     pub local_def_index: DefIndex,
228 }
229
230 pub const CRATE_DEF_ID: LocalDefId = LocalDefId { local_def_index: CRATE_DEF_INDEX };
231
232 impl Idx for LocalDefId {
233     #[inline]
234     fn new(idx: usize) -> Self {
235         LocalDefId { local_def_index: Idx::new(idx) }
236     }
237     #[inline]
238     fn index(self) -> usize {
239         self.local_def_index.index()
240     }
241 }
242
243 impl LocalDefId {
244     #[inline]
245     pub fn to_def_id(self) -> DefId {
246         DefId { krate: LOCAL_CRATE, index: self.local_def_index }
247     }
248
249     #[inline]
250     pub fn is_top_level_module(self) -> bool {
251         self.local_def_index == CRATE_DEF_INDEX
252     }
253 }
254
255 impl fmt::Debug for LocalDefId {
256     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257         self.to_def_id().fmt(f)
258     }
259 }
260
261 impl<E: Encoder> Encodable<E> for LocalDefId {
262     fn encode(&self, s: &mut E) -> Result<(), E::Error> {
263         self.to_def_id().encode(s)
264     }
265 }
266
267 impl<D: Decoder> Decodable<D> for LocalDefId {
268     fn decode(d: &mut D) -> Result<LocalDefId, D::Error> {
269         DefId::decode(d).map(|d| d.expect_local())
270     }
271 }
272
273 rustc_data_structures::define_id_collections!(LocalDefIdMap, LocalDefIdSet, LocalDefId);
274
275 impl<CTX: HashStableContext> HashStable<CTX> for DefId {
276     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
277         hcx.hash_def_id(*self, hasher)
278     }
279 }
280
281 impl<CTX: HashStableContext> HashStable<CTX> for CrateNum {
282     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
283         hcx.hash_crate_num(*self, hasher)
284     }
285 }