]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/map/def_collector.rs
Rollup merge of #41172 - Aaron1011:rustdoc-overflow, r=frewsxcv
[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, crate_name: &str, crate_disambiguator: &str) {
44         let root = self.definitions.create_root_def(crate_name,
45                                                     crate_disambiguator);
46         assert_eq!(root, CRATE_DEF_INDEX);
47         self.parent_def = Some(root);
48     }
49
50     fn create_def(&mut self,
51                   node_id: NodeId,
52                   data: DefPathData,
53                   address_space: DefIndexAddressSpace)
54                   -> DefIndex {
55         let parent_def = self.parent_def.unwrap();
56         debug!("create_def(node_id={:?}, data={:?}, parent_def={:?})", node_id, data, parent_def);
57         self.definitions.create_def_with_parent(parent_def, node_id, data, address_space)
58     }
59
60     pub fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_def: DefIndex, f: F) {
61         let parent = self.parent_def;
62         self.parent_def = Some(parent_def);
63         f(self);
64         self.parent_def = parent;
65     }
66
67     pub fn visit_const_expr(&mut self, expr: &Expr) {
68         match expr.node {
69             // Find the node which will be used after lowering.
70             ExprKind::Paren(ref inner) => return self.visit_const_expr(inner),
71             ExprKind::Mac(..) => return self.visit_macro_invoc(expr.id, true),
72             // FIXME(eddyb) Closures should have separate
73             // function definition IDs and expression IDs.
74             ExprKind::Closure(..) => return,
75             _ => {}
76         }
77
78         self.create_def(expr.id, DefPathData::Initializer, REGULAR_SPACE);
79     }
80
81     fn visit_macro_invoc(&mut self, id: NodeId, const_expr: bool) {
82         if let Some(ref mut visit) = self.visit_macro_invoc {
83             visit(MacroInvocationData {
84                 mark: id.placeholder_to_mark(),
85                 const_expr: const_expr,
86                 def_index: self.parent_def.unwrap(),
87             })
88         }
89     }
90 }
91
92 impl<'a> visit::Visitor<'a> for DefCollector<'a> {
93     fn visit_item(&mut self, i: &'a Item) {
94         debug!("visit_item: {:?}", i);
95
96         // Pick the def data. This need not be unique, but the more
97         // information we encapsulate into
98         let def_data = match i.node {
99             ItemKind::DefaultImpl(..) | ItemKind::Impl(..) =>
100                 DefPathData::Impl,
101             ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) | ItemKind::Trait(..) |
102             ItemKind::ExternCrate(..) | ItemKind::ForeignMod(..) | ItemKind::Ty(..) =>
103                 DefPathData::TypeNs(i.ident.name.as_str()),
104             ItemKind::Mod(..) if i.ident == keywords::Invalid.ident() => {
105                 return visit::walk_item(self, i);
106             }
107             ItemKind::Mod(..) => DefPathData::Module(i.ident.name.as_str()),
108             ItemKind::Static(..) | ItemKind::Const(..) | ItemKind::Fn(..) =>
109                 DefPathData::ValueNs(i.ident.name.as_str()),
110             ItemKind::MacroDef(..) => DefPathData::MacroDef(i.ident.name.as_str()),
111             ItemKind::Mac(..) => return self.visit_macro_invoc(i.id, false),
112             ItemKind::GlobalAsm(..) => DefPathData::Misc,
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,
122                                             DefPathData::Misc,
123                                             ITEM_LIKE_SPACE);
124                         }
125                     }
126                 }
127                 DefPathData::Misc
128             }
129         };
130         let def = self.create_def(i.id, def_data, ITEM_LIKE_SPACE);
131
132         self.with_parent(def, |this| {
133             match i.node {
134                 ItemKind::Enum(ref enum_definition, _) => {
135                     for v in &enum_definition.variants {
136                         let variant_def_index =
137                             this.create_def(v.node.data.id(),
138                                             DefPathData::EnumVariant(v.node.name.name.as_str()),
139                                             REGULAR_SPACE);
140                         this.with_parent(variant_def_index, |this| {
141                             for (index, field) in v.node.data.fields().iter().enumerate() {
142                                 let name = field.ident.map(|ident| ident.name)
143                                     .unwrap_or_else(|| Symbol::intern(&index.to_string()));
144                                 this.create_def(field.id,
145                                                 DefPathData::Field(name.as_str()),
146                                                 REGULAR_SPACE);
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                     }
162
163                     for (index, field) in struct_def.fields().iter().enumerate() {
164                         let name = field.ident.map(|ident| ident.name.as_str())
165                             .unwrap_or(Symbol::intern(&index.to_string()).as_str());
166                         this.create_def(field.id, DefPathData::Field(name), REGULAR_SPACE);
167                     }
168                 }
169                 _ => {}
170             }
171             visit::walk_item(this, i);
172         });
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_generics(&mut self, generics: &'a Generics) {
186         for ty_param in generics.ty_params.iter() {
187             self.create_def(ty_param.id,
188                             DefPathData::TypeParam(ty_param.ident.name.as_str()),
189                             REGULAR_SPACE);
190         }
191
192         visit::walk_generics(self, generics);
193     }
194
195     fn visit_trait_item(&mut self, ti: &'a TraitItem) {
196         let def_data = match ti.node {
197             TraitItemKind::Method(..) | TraitItemKind::Const(..) =>
198                 DefPathData::ValueNs(ti.ident.name.as_str()),
199             TraitItemKind::Type(..) => DefPathData::TypeNs(ti.ident.name.as_str()),
200             TraitItemKind::Macro(..) => return self.visit_macro_invoc(ti.id, false),
201         };
202
203         let def = self.create_def(ti.id, def_data, ITEM_LIKE_SPACE);
204         self.with_parent(def, |this| {
205             if let TraitItemKind::Const(_, Some(ref expr)) = ti.node {
206                 this.visit_const_expr(expr);
207             }
208
209             visit::walk_trait_item(this, ti);
210         });
211     }
212
213     fn visit_impl_item(&mut self, ii: &'a ImplItem) {
214         let def_data = match ii.node {
215             ImplItemKind::Method(..) | ImplItemKind::Const(..) =>
216                 DefPathData::ValueNs(ii.ident.name.as_str()),
217             ImplItemKind::Type(..) => DefPathData::TypeNs(ii.ident.name.as_str()),
218             ImplItemKind::Macro(..) => return self.visit_macro_invoc(ii.id, false),
219         };
220
221         let def = self.create_def(ii.id, def_data, ITEM_LIKE_SPACE);
222         self.with_parent(def, |this| {
223             if let ImplItemKind::Const(_, ref expr) = ii.node {
224                 this.visit_const_expr(expr);
225             }
226
227             visit::walk_impl_item(this, ii);
228         });
229     }
230
231     fn visit_pat(&mut self, pat: &'a Pat) {
232         let parent_def = self.parent_def;
233
234         match pat.node {
235             PatKind::Mac(..) => return self.visit_macro_invoc(pat.id, false),
236             PatKind::Ident(_, id, _) => {
237                 let def = self.create_def(pat.id,
238                                           DefPathData::Binding(id.node.name.as_str()),
239                                           REGULAR_SPACE);
240                 self.parent_def = Some(def);
241             }
242             _ => {}
243         }
244
245         visit::walk_pat(self, pat);
246         self.parent_def = parent_def;
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_lifetime_def(&mut self, def: &'a LifetimeDef) {
282         self.create_def(def.lifetime.id,
283                         DefPathData::LifetimeDef(def.lifetime.name.as_str()),
284                         REGULAR_SPACE);
285     }
286
287     fn visit_stmt(&mut self, stmt: &'a Stmt) {
288         match stmt.node {
289             StmtKind::Mac(..) => self.visit_macro_invoc(stmt.id, false),
290             _ => visit::walk_stmt(self, stmt),
291         }
292     }
293 }