]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/def_id.rs
Auto merge of #65429 - Timmmm:withoptions, r=Mark-Simulacrum
[rust.git] / src / librustc / hir / def_id.rs
1 use crate::ty::{self, TyCtxt};
2 use rustc_index::vec::Idx;
3 use std::fmt;
4 use std::u32;
5
6 rustc_index::newtype_index! {
7     pub struct CrateId {
8         ENCODABLE = custom
9     }
10 }
11
12 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
13 pub enum CrateNum {
14     /// A special `CrateNum` that we use for the `tcx.rcache` when decoding from
15     /// the incr. comp. cache.
16     ReservedForIncrCompCache,
17     Index(CrateId),
18 }
19
20 impl ::std::fmt::Debug for CrateNum {
21     fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
22         match self {
23             CrateNum::Index(id) => write!(fmt, "crate{}", id.private),
24             CrateNum::ReservedForIncrCompCache => write!(fmt, "crate for decoding incr comp cache"),
25         }
26     }
27 }
28
29 /// Item definitions in the currently-compiled crate would have the `CrateNum`
30 /// `LOCAL_CRATE` in their `DefId`.
31 pub const LOCAL_CRATE: CrateNum = CrateNum::Index(CrateId::from_u32_const(0));
32
33 impl Idx for CrateNum {
34     #[inline]
35     fn new(value: usize) -> Self {
36         CrateNum::Index(Idx::new(value))
37     }
38
39     #[inline]
40     fn index(self) -> usize {
41         match self {
42             CrateNum::Index(idx) => Idx::index(idx),
43             _ => bug!("Tried to get crate index of {:?}", self),
44         }
45     }
46 }
47
48 impl CrateNum {
49     pub fn new(x: usize) -> CrateNum {
50         CrateNum::from_usize(x)
51     }
52
53     pub fn from_usize(x: usize) -> CrateNum {
54         CrateNum::Index(CrateId::from_usize(x))
55     }
56
57     pub fn from_u32(x: u32) -> CrateNum {
58         CrateNum::Index(CrateId::from_u32(x))
59     }
60
61     pub fn as_usize(self) -> usize {
62         match self {
63             CrateNum::Index(id) => id.as_usize(),
64             _ => bug!("tried to get index of non-standard crate {:?}", self),
65         }
66     }
67
68     pub fn as_u32(self) -> u32 {
69         match self {
70             CrateNum::Index(id) => id.as_u32(),
71             _ => bug!("tried to get index of non-standard crate {:?}", self),
72         }
73     }
74
75     pub fn as_def_id(&self) -> DefId { DefId { krate: *self, index: CRATE_DEF_INDEX } }
76 }
77
78 impl fmt::Display for CrateNum {
79     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80         match self {
81             CrateNum::Index(id) => fmt::Display::fmt(&id.private, f),
82             CrateNum::ReservedForIncrCompCache => write!(f, "crate for decoding incr comp cache"),
83         }
84     }
85 }
86
87 impl rustc_serialize::UseSpecializedEncodable for CrateNum {}
88 impl rustc_serialize::UseSpecializedDecodable for CrateNum {}
89
90 rustc_index::newtype_index! {
91     /// A DefIndex is an index into the hir-map for a crate, identifying a
92     /// particular definition. It should really be considered an interned
93     /// shorthand for a particular DefPath.
94     pub struct DefIndex {
95         DEBUG_FORMAT = "DefIndex({})",
96
97         /// The crate root is always assigned index 0 by the AST Map code,
98         /// thanks to `NodeCollector::new`.
99         const CRATE_DEF_INDEX = 0,
100     }
101 }
102
103 impl rustc_serialize::UseSpecializedEncodable for DefIndex {}
104 impl rustc_serialize::UseSpecializedDecodable for DefIndex {}
105
106 /// A `DefId` identifies a particular *definition*, by combining a crate
107 /// index and a def index.
108 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy)]
109 pub struct DefId {
110     pub krate: CrateNum,
111     pub index: DefIndex,
112 }
113
114 impl fmt::Debug for DefId {
115     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116         write!(f, "DefId({}:{}", self.krate, self.index.index())?;
117
118         ty::tls::with_opt(|opt_tcx| {
119             if let Some(tcx) = opt_tcx {
120                 write!(f, " ~ {}", tcx.def_path_debug_str(*self))?;
121             }
122             Ok(())
123         })?;
124
125         write!(f, ")")
126     }
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 describe_as_module(&self, tcx: TyCtxt<'_>) -> String {
147         if self.is_local() && self.index == CRATE_DEF_INDEX {
148             format!("top-level module")
149         } else {
150             format!("module `{}`", tcx.def_path_str(*self))
151         }
152     }
153 }
154
155 impl rustc_serialize::UseSpecializedEncodable for DefId {}
156 impl rustc_serialize::UseSpecializedDecodable for DefId {}
157
158 /// A LocalDefId is equivalent to a DefId with `krate == LOCAL_CRATE`. Since
159 /// we encode this information in the type, we can ensure at compile time that
160 /// no DefIds from upstream crates get thrown into the mix. There are quite a
161 /// few cases where we know that only DefIds from the local crate are expected
162 /// and a DefId from a different crate would signify a bug somewhere. This
163 /// is when LocalDefId comes in handy.
164 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
165 pub struct LocalDefId(DefIndex);
166
167 impl LocalDefId {
168     #[inline]
169     pub fn from_def_id(def_id: DefId) -> LocalDefId {
170         assert!(def_id.is_local());
171         LocalDefId(def_id.index)
172     }
173
174     #[inline]
175     pub fn to_def_id(self) -> DefId {
176         DefId {
177             krate: LOCAL_CRATE,
178             index: self.0
179         }
180     }
181 }
182
183 impl fmt::Debug for LocalDefId {
184     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185         self.to_def_id().fmt(f)
186     }
187 }
188
189 impl rustc_serialize::UseSpecializedEncodable for LocalDefId {}
190 impl rustc_serialize::UseSpecializedDecodable for LocalDefId {}