]> git.proxmox.com Git - rustc.git/blob - src/librustc/hir/def.rs
New upstream version 1.34.2+dfsg1
[rustc.git] / src / librustc / hir / def.rs
1 use crate::hir::def_id::DefId;
2 use crate::util::nodemap::{NodeMap, DefIdMap};
3 use syntax::ast;
4 use syntax::ext::base::MacroKind;
5 use syntax_pos::Span;
6 use crate::hir;
7 use crate::ty;
8
9 use self::Namespace::*;
10
11 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
12 pub enum CtorKind {
13 /// Constructor function automatically created by a tuple struct/variant.
14 Fn,
15 /// Constructor constant automatically created by a unit struct/variant.
16 Const,
17 /// Unusable name in value namespace created by a struct variant.
18 Fictive,
19 }
20
21 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
22 pub enum NonMacroAttrKind {
23 /// Single-segment attribute defined by the language (`#[inline]`)
24 Builtin,
25 /// Multi-segment custom attribute living in a "tool module" (`#[rustfmt::skip]`).
26 Tool,
27 /// Single-segment custom attribute registered by a derive macro (`#[serde(default)]`).
28 DeriveHelper,
29 /// Single-segment custom attribute registered by a legacy plugin (`register_attribute`).
30 LegacyPluginHelper,
31 /// Single-segment custom attribute not registered in any way (`#[my_attr]`).
32 Custom,
33 }
34
35 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
36 pub enum Def {
37 // Type namespace
38 Mod(DefId),
39 Struct(DefId), // `DefId` refers to `NodeId` of the struct itself
40 Union(DefId),
41 Enum(DefId),
42 Variant(DefId),
43 Trait(DefId),
44 /// `existential type Foo: Bar;`
45 Existential(DefId),
46 /// `type Foo = Bar;`
47 TyAlias(DefId),
48 ForeignTy(DefId),
49 TraitAlias(DefId),
50 AssociatedTy(DefId),
51 /// `existential type Foo: Bar;`
52 AssociatedExistential(DefId),
53 PrimTy(hir::PrimTy),
54 TyParam(DefId),
55 SelfTy(Option<DefId> /* trait */, Option<DefId> /* impl */),
56 ToolMod, // e.g., `rustfmt` in `#[rustfmt::skip]`
57
58 // Value namespace
59 Fn(DefId),
60 Const(DefId),
61 ConstParam(DefId),
62 Static(DefId, bool /* is_mutbl */),
63 StructCtor(DefId, CtorKind), // `DefId` refers to `NodeId` of the struct's constructor
64 VariantCtor(DefId, CtorKind), // `DefId` refers to the enum variant
65 SelfCtor(DefId /* impl */), // `DefId` refers to the impl
66 Method(DefId),
67 AssociatedConst(DefId),
68
69 Local(ast::NodeId),
70 Upvar(ast::NodeId, // `NodeId` of closed over local
71 usize, // index in the `freevars` list of the closure
72 ast::NodeId), // expr node that creates the closure
73 Label(ast::NodeId),
74
75 // Macro namespace
76 Macro(DefId, MacroKind),
77 NonMacroAttr(NonMacroAttrKind), // e.g., `#[inline]` or `#[rustfmt::skip]`
78
79 // Both namespaces
80 Err,
81 }
82
83 /// The result of resolving a path before lowering to HIR.
84 /// `base_def` is definition of resolved part of the
85 /// path, `unresolved_segments` is the number of unresolved
86 /// segments.
87 ///
88 /// ```text
89 /// module::Type::AssocX::AssocY::MethodOrAssocType
90 /// ^~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
91 /// base_def unresolved_segments = 3
92 ///
93 /// <T as Trait>::AssocX::AssocY::MethodOrAssocType
94 /// ^~~~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~
95 /// base_def unresolved_segments = 2
96 /// ```
97 #[derive(Copy, Clone, Debug)]
98 pub struct PathResolution {
99 base_def: Def,
100 unresolved_segments: usize,
101 }
102
103 impl PathResolution {
104 pub fn new(def: Def) -> Self {
105 PathResolution { base_def: def, unresolved_segments: 0 }
106 }
107
108 pub fn with_unresolved_segments(def: Def, mut unresolved_segments: usize) -> Self {
109 if def == Def::Err { unresolved_segments = 0 }
110 PathResolution { base_def: def, unresolved_segments: unresolved_segments }
111 }
112
113 #[inline]
114 pub fn base_def(&self) -> Def {
115 self.base_def
116 }
117
118 #[inline]
119 pub fn unresolved_segments(&self) -> usize {
120 self.unresolved_segments
121 }
122 }
123
124 /// Different kinds of symbols don't influence each other.
125 ///
126 /// Therefore, they have a separate universe (namespace).
127 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
128 pub enum Namespace {
129 TypeNS,
130 ValueNS,
131 MacroNS,
132 }
133
134 impl Namespace {
135 pub fn descr(self) -> &'static str {
136 match self {
137 TypeNS => "type",
138 ValueNS => "value",
139 MacroNS => "macro",
140 }
141 }
142 }
143
144 /// Just a helper ‒ separate structure for each namespace.
145 #[derive(Copy, Clone, Default, Debug)]
146 pub struct PerNS<T> {
147 pub value_ns: T,
148 pub type_ns: T,
149 pub macro_ns: T,
150 }
151
152 impl<T> PerNS<T> {
153 pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> PerNS<U> {
154 PerNS {
155 value_ns: f(self.value_ns),
156 type_ns: f(self.type_ns),
157 macro_ns: f(self.macro_ns),
158 }
159 }
160 }
161
162 impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
163 type Output = T;
164
165 fn index(&self, ns: Namespace) -> &T {
166 match ns {
167 ValueNS => &self.value_ns,
168 TypeNS => &self.type_ns,
169 MacroNS => &self.macro_ns,
170 }
171 }
172 }
173
174 impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> {
175 fn index_mut(&mut self, ns: Namespace) -> &mut T {
176 match ns {
177 ValueNS => &mut self.value_ns,
178 TypeNS => &mut self.type_ns,
179 MacroNS => &mut self.macro_ns,
180 }
181 }
182 }
183
184 impl<T> PerNS<Option<T>> {
185 /// Returns `true` if all the items in this collection are `None`.
186 pub fn is_empty(&self) -> bool {
187 self.type_ns.is_none() && self.value_ns.is_none() && self.macro_ns.is_none()
188 }
189
190 /// Returns an iterator over the items which are `Some`.
191 pub fn present_items(self) -> impl Iterator<Item=T> {
192 use std::iter::once;
193
194 once(self.type_ns)
195 .chain(once(self.value_ns))
196 .chain(once(self.macro_ns))
197 .filter_map(|it| it)
198 }
199 }
200
201 /// Definition mapping
202 pub type DefMap = NodeMap<PathResolution>;
203
204 /// This is the replacement export map. It maps a module to all of the exports
205 /// within.
206 pub type ExportMap = DefIdMap<Vec<Export>>;
207
208 /// Map used to track the `use` statements within a scope, matching it with all the items in every
209 /// namespace.
210 pub type ImportMap = NodeMap<PerNS<Option<PathResolution>>>;
211
212 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
213 pub struct Export {
214 /// The name of the target.
215 pub ident: ast::Ident,
216 /// The definition of the target.
217 pub def: Def,
218 /// The span of the target definition.
219 pub span: Span,
220 /// The visibility of the export.
221 /// We include non-`pub` exports for hygienic macros that get used from extern crates.
222 pub vis: ty::Visibility,
223 }
224
225 impl CtorKind {
226 pub fn from_ast(vdata: &ast::VariantData) -> CtorKind {
227 match *vdata {
228 ast::VariantData::Tuple(..) => CtorKind::Fn,
229 ast::VariantData::Unit(..) => CtorKind::Const,
230 ast::VariantData::Struct(..) => CtorKind::Fictive,
231 }
232 }
233
234 pub fn from_hir(vdata: &hir::VariantData) -> CtorKind {
235 match *vdata {
236 hir::VariantData::Tuple(..) => CtorKind::Fn,
237 hir::VariantData::Unit(..) => CtorKind::Const,
238 hir::VariantData::Struct(..) => CtorKind::Fictive,
239 }
240 }
241 }
242
243 impl NonMacroAttrKind {
244 pub fn descr(self) -> &'static str {
245 match self {
246 NonMacroAttrKind::Builtin => "built-in attribute",
247 NonMacroAttrKind::Tool => "tool attribute",
248 NonMacroAttrKind::DeriveHelper => "derive helper attribute",
249 NonMacroAttrKind::LegacyPluginHelper => "legacy plugin helper attribute",
250 NonMacroAttrKind::Custom => "custom attribute",
251 }
252 }
253 }
254
255 impl Def {
256 /// Return the `DefId` of this `Def` if it has an id, else panic.
257 pub fn def_id(&self) -> DefId {
258 self.opt_def_id().unwrap_or_else(|| {
259 bug!("attempted .def_id() on invalid def: {:?}", self)
260 })
261 }
262
263 /// Return `Some(..)` with the `DefId` of this `Def` if it has a id, else `None`.
264 pub fn opt_def_id(&self) -> Option<DefId> {
265 match *self {
266 Def::Fn(id) | Def::Mod(id) | Def::Static(id, _) |
267 Def::Variant(id) | Def::VariantCtor(id, ..) | Def::Enum(id) |
268 Def::TyAlias(id) | Def::TraitAlias(id) |
269 Def::AssociatedTy(id) | Def::TyParam(id) | Def::ConstParam(id) | Def::Struct(id) |
270 Def::StructCtor(id, ..) |
271 Def::Union(id) | Def::Trait(id) | Def::Method(id) | Def::Const(id) |
272 Def::AssociatedConst(id) | Def::Macro(id, ..) |
273 Def::Existential(id) | Def::AssociatedExistential(id) | Def::ForeignTy(id) => {
274 Some(id)
275 }
276
277 Def::Local(..) |
278 Def::Upvar(..) |
279 Def::Label(..) |
280 Def::PrimTy(..) |
281 Def::SelfTy(..) |
282 Def::SelfCtor(..) |
283 Def::ToolMod |
284 Def::NonMacroAttr(..) |
285 Def::Err => {
286 None
287 }
288 }
289 }
290
291 /// Return the `DefId` of this `Def` if it represents a module.
292 pub fn mod_def_id(&self) -> Option<DefId> {
293 match *self {
294 Def::Mod(id) => Some(id),
295 _ => None,
296 }
297 }
298
299 /// A human readable name for the def kind ("function", "module", etc.).
300 pub fn kind_name(&self) -> &'static str {
301 match *self {
302 Def::Fn(..) => "function",
303 Def::Mod(..) => "module",
304 Def::Static(..) => "static",
305 Def::Variant(..) => "variant",
306 Def::VariantCtor(.., CtorKind::Fn) => "tuple variant",
307 Def::VariantCtor(.., CtorKind::Const) => "unit variant",
308 Def::VariantCtor(.., CtorKind::Fictive) => "struct variant",
309 Def::Enum(..) => "enum",
310 Def::Existential(..) => "existential type",
311 Def::TyAlias(..) => "type alias",
312 Def::TraitAlias(..) => "trait alias",
313 Def::AssociatedTy(..) => "associated type",
314 Def::AssociatedExistential(..) => "associated existential type",
315 Def::Struct(..) => "struct",
316 Def::StructCtor(.., CtorKind::Fn) => "tuple struct",
317 Def::StructCtor(.., CtorKind::Const) => "unit struct",
318 Def::StructCtor(.., CtorKind::Fictive) => bug!("impossible struct constructor"),
319 Def::SelfCtor(..) => "self constructor",
320 Def::Union(..) => "union",
321 Def::Trait(..) => "trait",
322 Def::ForeignTy(..) => "foreign type",
323 Def::Method(..) => "method",
324 Def::Const(..) => "constant",
325 Def::AssociatedConst(..) => "associated constant",
326 Def::TyParam(..) => "type parameter",
327 Def::ConstParam(..) => "const parameter",
328 Def::PrimTy(..) => "builtin type",
329 Def::Local(..) => "local variable",
330 Def::Upvar(..) => "closure capture",
331 Def::Label(..) => "label",
332 Def::SelfTy(..) => "self type",
333 Def::Macro(.., macro_kind) => macro_kind.descr(),
334 Def::ToolMod => "tool module",
335 Def::NonMacroAttr(attr_kind) => attr_kind.descr(),
336 Def::Err => "unresolved item",
337 }
338 }
339
340 /// An English article for the def.
341 pub fn article(&self) -> &'static str {
342 match *self {
343 Def::AssociatedTy(..) | Def::AssociatedConst(..) | Def::AssociatedExistential(..) |
344 Def::Enum(..) | Def::Existential(..) | Def::Err => "an",
345 Def::Macro(.., macro_kind) => macro_kind.article(),
346 _ => "a",
347 }
348 }
349 }