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