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