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