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