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