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