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