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