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