]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/def_id.rs
057d878a0ab8dc58b64959adc08fa5daa68471c6
[rust.git] / src / librustc / hir / def_id.rs
1 use crate::ty::{self, TyCtxt};
2 use crate::hir::map::definitions::FIRST_FREE_DEF_INDEX;
3 use rustc_data_structures::indexed_vec::Idx;
4 use serialize;
5 use std::fmt;
6 use std::u32;
7
8 newtype_index! {
9     pub struct CrateId {
10         ENCODABLE = custom
11     }
12 }
13
14 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
15 pub enum CrateNum {
16     /// Virtual crate for builtin macros
17     // FIXME(jseyfried): this is also used for custom derives until proc-macro crates get
18     // `CrateNum`s.
19     BuiltinMacros,
20     /// A special CrateNum that we use for the tcx.rcache when decoding from
21     /// the incr. comp. cache.
22     ReservedForIncrCompCache,
23     Index(CrateId),
24 }
25
26 impl ::std::fmt::Debug for CrateNum {
27     fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
28         match self {
29             CrateNum::Index(id) => write!(fmt, "crate{}", id.private),
30             CrateNum::BuiltinMacros => write!(fmt, "builtin macros crate"),
31             CrateNum::ReservedForIncrCompCache => write!(fmt, "crate for decoding incr comp cache"),
32         }
33     }
34 }
35
36 /// Item definitions in the currently-compiled crate would have the CrateNum
37 /// LOCAL_CRATE in their DefId.
38 pub const LOCAL_CRATE: CrateNum = CrateNum::Index(CrateId::from_u32_const(0));
39
40
41 impl Idx for CrateNum {
42     #[inline]
43     fn new(value: usize) -> Self {
44         CrateNum::Index(Idx::new(value))
45     }
46
47     #[inline]
48     fn index(self) -> usize {
49         match self {
50             CrateNum::Index(idx) => Idx::index(idx),
51             _ => bug!("Tried to get crate index of {:?}", self),
52         }
53     }
54 }
55
56 impl CrateNum {
57     pub fn new(x: usize) -> CrateNum {
58         CrateNum::from_usize(x)
59     }
60
61     pub fn from_usize(x: usize) -> CrateNum {
62         CrateNum::Index(CrateId::from_usize(x))
63     }
64
65     pub fn from_u32(x: u32) -> CrateNum {
66         CrateNum::Index(CrateId::from_u32(x))
67     }
68
69     pub fn as_usize(self) -> usize {
70         match self {
71             CrateNum::Index(id) => id.as_usize(),
72             _ => bug!("tried to get index of non-standard crate {:?}", self),
73         }
74     }
75
76     pub fn as_u32(self) -> u32 {
77         match self {
78             CrateNum::Index(id) => id.as_u32(),
79             _ => bug!("tried to get index of non-standard crate {:?}", self),
80         }
81     }
82
83     pub fn as_def_id(&self) -> DefId { DefId { krate: *self, index: CRATE_DEF_INDEX } }
84 }
85
86 impl fmt::Display for CrateNum {
87     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88         match self {
89             CrateNum::Index(id) => fmt::Display::fmt(&id.private, f),
90             CrateNum::BuiltinMacros => write!(f, "builtin macros crate"),
91             CrateNum::ReservedForIncrCompCache => write!(f, "crate for decoding incr comp cache"),
92         }
93     }
94 }
95
96 impl serialize::UseSpecializedEncodable for CrateNum {}
97 impl serialize::UseSpecializedDecodable for CrateNum {}
98
99 newtype_index! {
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.
103     pub struct DefIndex {
104         DEBUG_FORMAT = "DefIndex({})",
105
106         /// The crate root is always assigned index 0 by the AST Map code,
107         /// thanks to `NodeCollector::new`.
108         const CRATE_DEF_INDEX = 0,
109     }
110 }
111
112 impl DefIndex {
113     // Proc macros from a proc-macro crate have a kind of virtual DefIndex. This
114     // function maps the index of the macro within the crate (which is also the
115     // index of the macro in the CrateMetadata::proc_macros array) to the
116     // corresponding DefIndex.
117     pub fn from_proc_macro_index(proc_macro_index: usize) -> DefIndex {
118         // DefIndex for proc macros start from FIRST_FREE_DEF_INDEX,
119         // because the first FIRST_FREE_DEF_INDEX indexes are reserved
120         // for internal use.
121         let def_index = DefIndex::from(
122             proc_macro_index.checked_add(FIRST_FREE_DEF_INDEX)
123                 .expect("integer overflow adding `proc_macro_index`"));
124         assert!(def_index != CRATE_DEF_INDEX);
125         def_index
126     }
127
128     // This function is the reverse of from_proc_macro_index() above.
129     pub fn to_proc_macro_index(self: DefIndex) -> usize {
130         self.index().checked_sub(FIRST_FREE_DEF_INDEX)
131             .unwrap_or_else(|| {
132                 bug!("using local index {:?} as proc-macro index", self)
133             })
134     }
135 }
136
137 impl serialize::UseSpecializedEncodable for DefIndex {}
138 impl serialize::UseSpecializedDecodable for DefIndex {}
139
140 /// A `DefId` identifies a particular *definition*, by combining a crate
141 /// index and a def index.
142 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy)]
143 pub struct DefId {
144     pub krate: CrateNum,
145     pub index: DefIndex,
146 }
147
148 impl fmt::Debug for DefId {
149     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150         write!(f, "DefId({}:{}", self.krate, self.index.index())?;
151
152         ty::tls::with_opt(|opt_tcx| {
153             if let Some(tcx) = opt_tcx {
154                 write!(f, " ~ {}", tcx.def_path_debug_str(*self))?;
155             }
156             Ok(())
157         })?;
158
159         write!(f, ")")
160     }
161 }
162
163 impl DefId {
164     /// Makes a local `DefId` from the given `DefIndex`.
165     #[inline]
166     pub fn local(index: DefIndex) -> DefId {
167         DefId { krate: LOCAL_CRATE, index: index }
168     }
169
170     #[inline]
171     pub fn is_local(self) -> bool {
172         self.krate == LOCAL_CRATE
173     }
174
175     #[inline]
176     pub fn to_local(self) -> LocalDefId {
177         LocalDefId::from_def_id(self)
178     }
179
180     pub fn describe_as_module(&self, tcx: TyCtxt<'_>) -> String {
181         if self.is_local() && self.index == CRATE_DEF_INDEX {
182             format!("top-level module")
183         } else {
184             format!("module `{}`", tcx.def_path_str(*self))
185         }
186     }
187 }
188
189 impl serialize::UseSpecializedEncodable for DefId {}
190 impl serialize::UseSpecializedDecodable for DefId {}
191
192 /// A LocalDefId is equivalent to a DefId with `krate == LOCAL_CRATE`. Since
193 /// we encode this information in the type, we can ensure at compile time that
194 /// no DefIds from upstream crates get thrown into the mix. There are quite a
195 /// few cases where we know that only DefIds from the local crate are expected
196 /// and a DefId from a different crate would signify a bug somewhere. This
197 /// is when LocalDefId comes in handy.
198 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
199 pub struct LocalDefId(DefIndex);
200
201 impl LocalDefId {
202     #[inline]
203     pub fn from_def_id(def_id: DefId) -> LocalDefId {
204         assert!(def_id.is_local());
205         LocalDefId(def_id.index)
206     }
207
208     #[inline]
209     pub fn to_def_id(self) -> DefId {
210         DefId {
211             krate: LOCAL_CRATE,
212             index: self.0
213         }
214     }
215 }
216
217 impl fmt::Debug for LocalDefId {
218     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219         self.to_def_id().fmt(f)
220     }
221 }
222
223 impl serialize::UseSpecializedEncodable for LocalDefId {}
224 impl serialize::UseSpecializedDecodable for LocalDefId {}