]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/map/def_collector.rs
af027e321c6a1da4e4f235e607d0898466eee3e0
[rust.git] / src / librustc / hir / map / def_collector.rs
1 // Copyright 2016 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::map::definitions::*;
12 use hir::def_id::{CRATE_DEF_INDEX, DefIndex, DefIndexAddressSpace};
13
14 use syntax::ast::*;
15 use syntax::ext::hygiene::Mark;
16 use syntax::visit;
17 use syntax::symbol::keywords;
18 use syntax::symbol::Symbol;
19
20 use hir::map::{ITEM_LIKE_SPACE, REGULAR_SPACE};
21
22 /// Creates def ids for nodes in the AST.
23 pub struct DefCollector<'a> {
24     definitions: &'a mut Definitions,
25     parent_def: Option<DefIndex>,
26     expansion: Mark,
27     pub visit_macro_invoc: Option<&'a mut FnMut(MacroInvocationData)>,
28 }
29
30 pub struct MacroInvocationData {
31     pub mark: Mark,
32     pub def_index: DefIndex,
33     pub const_expr: bool,
34 }
35
36 impl<'a> DefCollector<'a> {
37     pub fn new(definitions: &'a mut Definitions, expansion: Mark) -> Self {
38         DefCollector {
39             definitions,
40             expansion,
41             parent_def: None,
42             visit_macro_invoc: None,
43         }
44     }
45
46     pub fn collect_root(&mut self, crate_name: &str, crate_disambiguator: &str) {
47         let root = self.definitions.create_root_def(crate_name,
48                                                     crate_disambiguator);
49         assert_eq!(root, CRATE_DEF_INDEX);
50         self.parent_def = Some(root);
51     }
52
53     fn create_def(&mut self,
54                   node_id: NodeId,
55                   data: DefPathData,
56                   address_space: DefIndexAddressSpace)
57                   -> DefIndex {
58         let parent_def = self.parent_def.unwrap();
59         debug!("create_def(node_id={:?}, data={:?}, parent_def={:?})", node_id, data, parent_def);
60         self.definitions
61             .create_def_with_parent(parent_def, node_id, data, address_space, self.expansion)
62     }
63
64     pub fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_def: DefIndex, f: F) {
65         let parent = self.parent_def;
66         self.parent_def = Some(parent_def);
67         f(self);
68         self.parent_def = parent;
69     }
70
71     pub fn visit_const_expr(&mut self, expr: &Expr) {
72         match expr.node {
73             // Find the node which will be used after lowering.
74             ExprKind::Paren(ref inner) => return self.visit_const_expr(inner),
75             ExprKind::Mac(..) => return self.visit_macro_invoc(expr.id, true),
76             // FIXME(eddyb) Closures should have separate
77             // function definition IDs and expression IDs.
78             ExprKind::Closure(..) => return,
79             _ => {}
80         }
81
82         self.create_def(expr.id, DefPathData::Initializer, REGULAR_SPACE);
83     }
84
85     fn visit_macro_invoc(&mut self, id: NodeId, const_expr: bool) {
86         if let Some(ref mut visit) = self.visit_macro_invoc {
87             visit(MacroInvocationData {
88                 mark: id.placeholder_to_mark(),
89                 const_expr,
90                 def_index: self.parent_def.unwrap(),
91             })
92         }
93     }
94 }
95
96 impl<'a> visit::Visitor<'a> for DefCollector<'a> {
97     fn visit_item(&mut self, i: &'a Item) {
98         debug!("visit_item: {:?}", i);
99
100         // Pick the def data. This need not be unique, but the more
101         // information we encapsulate into
102         let def_data = match i.node {
103             ItemKind::DefaultImpl(..) | ItemKind::Impl(..) =>
104                 DefPathData::Impl,
105             ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) | ItemKind::Trait(..) |
106             ItemKind::ExternCrate(..) | ItemKind::ForeignMod(..) | ItemKind::Ty(..) =>
107                 DefPathData::TypeNs(i.ident.name.as_str()),
108             ItemKind::Mod(..) if i.ident == keywords::Invalid.ident() => {
109                 return visit::walk_item(self, i);
110             }
111             ItemKind::Mod(..) => DefPathData::Module(i.ident.name.as_str()),
112             ItemKind::Static(..) | ItemKind::Const(..) | ItemKind::Fn(..) =>
113                 DefPathData::ValueNs(i.ident.name.as_str()),
114             ItemKind::MacroDef(..) => DefPathData::MacroDef(i.ident.name.as_str()),
115             ItemKind::Mac(..) => return self.visit_macro_invoc(i.id, false),
116             ItemKind::GlobalAsm(..) => DefPathData::Misc,
117             ItemKind::Use(ref view_path) => {
118                 match view_path.node {
119                     ViewPathGlob(..) => {}
120
121                     // FIXME(eddyb) Should use the real name. Which namespace?
122                     ViewPathSimple(..) => {}
123                     ViewPathList(_, ref imports) => {
124                         for import in imports {
125                             self.create_def(import.node.id,
126                                             DefPathData::Misc,
127                                             ITEM_LIKE_SPACE);
128                         }
129                     }
130                 }
131                 DefPathData::Misc
132             }
133         };
134         let def = self.create_def(i.id, def_data, ITEM_LIKE_SPACE);
135
136         self.with_parent(def, |this| {
137             match i.node {
138                 ItemKind::Enum(ref enum_definition, _) => {
139                     for v in &enum_definition.variants {
140                         let variant_def_index =
141                             this.create_def(v.node.data.id(),
142                                             DefPathData::EnumVariant(v.node.name.name.as_str()),
143                                             REGULAR_SPACE);
144                         this.with_parent(variant_def_index, |this| {
145                             for (index, field) in v.node.data.fields().iter().enumerate() {
146                                 let name = field.ident.map(|ident| ident.name)
147                                     .unwrap_or_else(|| Symbol::intern(&index.to_string()));
148                                 this.create_def(field.id,
149                                                 DefPathData::Field(name.as_str()),
150                                                 REGULAR_SPACE);
151                             }
152
153                             if let Some(ref expr) = v.node.disr_expr {
154                                 this.visit_const_expr(expr);
155                             }
156                         });
157                     }
158                 }
159                 ItemKind::Struct(ref struct_def, _) | ItemKind::Union(ref struct_def, _) => {
160                     // If this is a tuple-like struct, register the constructor.
161                     if !struct_def.is_struct() {
162                         this.create_def(struct_def.id(),
163                                         DefPathData::StructCtor,
164                                         REGULAR_SPACE);
165                     }
166
167                     for (index, field) in struct_def.fields().iter().enumerate() {
168                         let name = field.ident.map(|ident| ident.name)
169                             .unwrap_or_else(|| Symbol::intern(&index.to_string()));
170                         this.create_def(field.id, DefPathData::Field(name.as_str()), REGULAR_SPACE);
171                     }
172                 }
173                 _ => {}
174             }
175             visit::walk_item(this, i);
176         });
177     }
178
179     fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
180         let def = self.create_def(foreign_item.id,
181                                   DefPathData::ValueNs(foreign_item.ident.name.as_str()),
182                                   REGULAR_SPACE);
183
184         self.with_parent(def, |this| {
185             visit::walk_foreign_item(this, foreign_item);
186         });
187     }
188
189     fn visit_generics(&mut self, generics: &'a Generics) {
190         for ty_param in generics.ty_params.iter() {
191             self.create_def(ty_param.id,
192                             DefPathData::TypeParam(ty_param.ident.name.as_str()),
193                             REGULAR_SPACE);
194         }
195
196         visit::walk_generics(self, generics);
197     }
198
199     fn visit_trait_item(&mut self, ti: &'a TraitItem) {
200         let def_data = match ti.node {
201             TraitItemKind::Method(..) | TraitItemKind::Const(..) =>
202                 DefPathData::ValueNs(ti.ident.name.as_str()),
203             TraitItemKind::Type(..) => DefPathData::TypeNs(ti.ident.name.as_str()),
204             TraitItemKind::Macro(..) => return self.visit_macro_invoc(ti.id, false),
205         };
206
207         let def = self.create_def(ti.id, def_data, ITEM_LIKE_SPACE);
208         self.with_parent(def, |this| {
209             if let TraitItemKind::Const(_, Some(ref expr)) = ti.node {
210                 this.visit_const_expr(expr);
211             }
212
213             visit::walk_trait_item(this, ti);
214         });
215     }
216
217     fn visit_impl_item(&mut self, ii: &'a ImplItem) {
218         let def_data = match ii.node {
219             ImplItemKind::Method(..) | ImplItemKind::Const(..) =>
220                 DefPathData::ValueNs(ii.ident.name.as_str()),
221             ImplItemKind::Type(..) => DefPathData::TypeNs(ii.ident.name.as_str()),
222             ImplItemKind::Macro(..) => return self.visit_macro_invoc(ii.id, false),
223         };
224
225         let def = self.create_def(ii.id, def_data, ITEM_LIKE_SPACE);
226         self.with_parent(def, |this| {
227             if let ImplItemKind::Const(_, ref expr) = ii.node {
228                 this.visit_const_expr(expr);
229             }
230
231             visit::walk_impl_item(this, ii);
232         });
233     }
234
235     fn visit_pat(&mut self, pat: &'a Pat) {
236         let parent_def = self.parent_def;
237
238         match pat.node {
239             PatKind::Mac(..) => return self.visit_macro_invoc(pat.id, false),
240             PatKind::Ident(_, id, _) => {
241                 let def = self.create_def(pat.id,
242                                           DefPathData::Binding(id.node.name.as_str()),
243                                           REGULAR_SPACE);
244                 self.parent_def = Some(def);
245             }
246             _ => {}
247         }
248
249         visit::walk_pat(self, pat);
250         self.parent_def = parent_def;
251     }
252
253     fn visit_expr(&mut self, expr: &'a Expr) {
254         let parent_def = self.parent_def;
255
256         match expr.node {
257             ExprKind::Mac(..) => return self.visit_macro_invoc(expr.id, false),
258             ExprKind::Repeat(_, ref count) => self.visit_const_expr(count),
259             ExprKind::Closure(..) => {
260                 let def = self.create_def(expr.id,
261                                           DefPathData::ClosureExpr,
262                                           REGULAR_SPACE);
263                 self.parent_def = Some(def);
264             }
265             _ => {}
266         }
267
268         visit::walk_expr(self, expr);
269         self.parent_def = parent_def;
270     }
271
272     fn visit_ty(&mut self, ty: &'a Ty) {
273         match ty.node {
274             TyKind::Mac(..) => return self.visit_macro_invoc(ty.id, false),
275             TyKind::Array(_, ref length) => self.visit_const_expr(length),
276             TyKind::ImplTrait(..) => {
277                 self.create_def(ty.id, DefPathData::ImplTrait, REGULAR_SPACE);
278             }
279             TyKind::Typeof(ref expr) => self.visit_const_expr(expr),
280             _ => {}
281         }
282         visit::walk_ty(self, ty);
283     }
284
285     fn visit_lifetime_def(&mut self, def: &'a LifetimeDef) {
286         self.create_def(def.lifetime.id,
287                         DefPathData::LifetimeDef(def.lifetime.ident.name.as_str()),
288                         REGULAR_SPACE);
289     }
290
291     fn visit_stmt(&mut self, stmt: &'a Stmt) {
292         match stmt.node {
293             StmtKind::Mac(..) => self.visit_macro_invoc(stmt.id, false),
294             _ => visit::walk_stmt(self, stmt),
295         }
296     }
297 }