]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/def.rs
5d9d4deb0abc9e95793aa303ce1a621980cc0b1c
[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 attriubte 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,  // node id 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     pub fn kind_name(&self) -> &'static str {
133         if self.unresolved_segments != 0 {
134             "associated item"
135         } else {
136             self.base_def.kind_name()
137         }
138     }
139 }
140
141 /// Different kinds of symbols don't influence each other.
142 ///
143 /// Therefore, they have a separate universe (namespace).
144 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
145 pub enum Namespace {
146     TypeNS,
147     ValueNS,
148     MacroNS,
149 }
150
151 impl Namespace {
152     pub fn descr(self) -> &'static str {
153         match self {
154             TypeNS => "type",
155             ValueNS => "value",
156             MacroNS => "macro",
157         }
158     }
159 }
160
161 /// Just a helper ‒ separate structure for each namespace.
162 #[derive(Copy, Clone, Default, Debug)]
163 pub struct PerNS<T> {
164     pub value_ns: T,
165     pub type_ns: T,
166     pub macro_ns: T,
167 }
168
169 impl<T> PerNS<T> {
170     pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> PerNS<U> {
171         PerNS {
172             value_ns: f(self.value_ns),
173             type_ns: f(self.type_ns),
174             macro_ns: f(self.macro_ns),
175         }
176     }
177 }
178
179 impl<T> ::std::ops::Index<Namespace> for PerNS<T> {
180     type Output = T;
181     fn index(&self, ns: Namespace) -> &T {
182         match ns {
183             ValueNS => &self.value_ns,
184             TypeNS => &self.type_ns,
185             MacroNS => &self.macro_ns,
186         }
187     }
188 }
189
190 impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> {
191     fn index_mut(&mut self, ns: Namespace) -> &mut T {
192         match ns {
193             ValueNS => &mut self.value_ns,
194             TypeNS => &mut self.type_ns,
195             MacroNS => &mut self.macro_ns,
196         }
197     }
198 }
199
200 impl<T> PerNS<Option<T>> {
201     /// Returns whether all the items in this collection are `None`.
202     pub fn is_empty(&self) -> bool {
203         self.type_ns.is_none() && self.value_ns.is_none() && self.macro_ns.is_none()
204     }
205
206     /// Returns an iterator over the items which are `Some`.
207     pub fn present_items(self) -> impl Iterator<Item=T> {
208         use std::iter::once;
209
210         once(self.type_ns)
211             .chain(once(self.value_ns))
212             .chain(once(self.macro_ns))
213             .filter_map(|it| it)
214     }
215 }
216
217 /// Definition mapping
218 pub type DefMap = NodeMap<PathResolution>;
219
220 /// This is the replacement export map. It maps a module to all of the exports
221 /// within.
222 pub type ExportMap = DefIdMap<Vec<Export>>;
223
224 /// Map used to track the `use` statements within a scope, matching it with all the items in every
225 /// namespace.
226 pub type ImportMap = NodeMap<PerNS<Option<PathResolution>>>;
227
228 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
229 pub struct Export {
230     /// The name of the target.
231     pub ident: ast::Ident,
232     /// The definition of the target.
233     pub def: Def,
234     /// The span of the target definition.
235     pub span: Span,
236     /// The visibility of the export.
237     /// We include non-`pub` exports for hygienic macros that get used from extern crates.
238     pub vis: ty::Visibility,
239 }
240
241 impl CtorKind {
242     pub fn from_ast(vdata: &ast::VariantData) -> CtorKind {
243         match *vdata {
244             ast::VariantData::Tuple(..) => CtorKind::Fn,
245             ast::VariantData::Unit(..) => CtorKind::Const,
246             ast::VariantData::Struct(..) => CtorKind::Fictive,
247         }
248     }
249     pub fn from_hir(vdata: &hir::VariantData) -> CtorKind {
250         match *vdata {
251             hir::VariantData::Tuple(..) => CtorKind::Fn,
252             hir::VariantData::Unit(..) => CtorKind::Const,
253             hir::VariantData::Struct(..) => CtorKind::Fictive,
254         }
255     }
256 }
257
258 impl NonMacroAttrKind {
259     fn descr(self) -> &'static str {
260         match self {
261             NonMacroAttrKind::Builtin => "built-in attribute",
262             NonMacroAttrKind::Tool => "tool attribute",
263             NonMacroAttrKind::DeriveHelper => "derive helper attribute",
264             NonMacroAttrKind::LegacyPluginHelper => "legacy plugin helper attribute",
265             NonMacroAttrKind::Custom => "custom attribute",
266         }
267     }
268 }
269
270 impl Def {
271     pub fn def_id(&self) -> 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             Def::SelfCtor(id) => {
281                 id
282             }
283
284             Def::Local(..) |
285             Def::Upvar(..) |
286             Def::Label(..)  |
287             Def::PrimTy(..) |
288             Def::SelfTy(..) |
289             Def::ToolMod |
290             Def::NonMacroAttr(..) |
291             Def::Err => {
292                 bug!("attempted .def_id() on invalid def: {:?}", self)
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 }