]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/map/def_collector.rs
Rollup merge of #41135 - japaric:unstable-docs, 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, 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::Use(ref view_path) => {
113                 match view_path.node {
114                     ViewPathGlob(..) => {}
115
116                     // FIXME(eddyb) Should use the real name. Which namespace?
117                     ViewPathSimple(..) => {}
118                     ViewPathList(_, ref imports) => {
119                         for import in imports {
120                             self.create_def(import.node.id,
121                                             DefPathData::Misc,
122                                             ITEM_LIKE_SPACE);
123                         }
124                     }
125                 }
126                 DefPathData::Misc
127             }
128         };
129         let def = self.create_def(i.id, def_data, ITEM_LIKE_SPACE);
130
131         self.with_parent(def, |this| {
132             match i.node {
133                 ItemKind::Enum(ref enum_definition, _) => {
134                     for v in &enum_definition.variants {
135                         let variant_def_index =
136                             this.create_def(v.node.data.id(),
137                                             DefPathData::EnumVariant(v.node.name.name.as_str()),
138                                             REGULAR_SPACE);
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                             }
147
148                             if let Some(ref expr) = v.node.disr_expr {
149                                 this.visit_const_expr(expr);
150                             }
151                         });
152                     }
153                 }
154                 ItemKind::Struct(ref struct_def, _) | ItemKind::Union(ref struct_def, _) => {
155                     // If this is a tuple-like struct, register the constructor.
156                     if !struct_def.is_struct() {
157                         this.create_def(struct_def.id(),
158                                         DefPathData::StructCtor,
159                                         REGULAR_SPACE);
160                     }
161
162                     for (index, field) in struct_def.fields().iter().enumerate() {
163                         let name = field.ident.map(|ident| ident.name.as_str())
164                             .unwrap_or(Symbol::intern(&index.to_string()).as_str());
165                         this.create_def(field.id, DefPathData::Field(name), REGULAR_SPACE);
166                     }
167                 }
168                 _ => {}
169             }
170             visit::walk_item(this, i);
171         });
172     }
173
174     fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
175         let def = self.create_def(foreign_item.id,
176                                   DefPathData::ValueNs(foreign_item.ident.name.as_str()),
177                                   REGULAR_SPACE);
178
179         self.with_parent(def, |this| {
180             visit::walk_foreign_item(this, foreign_item);
181         });
182     }
183
184     fn visit_generics(&mut self, generics: &'a Generics) {
185         for ty_param in generics.ty_params.iter() {
186             self.create_def(ty_param.id,
187                             DefPathData::TypeParam(ty_param.ident.name.as_str()),
188                             REGULAR_SPACE);
189         }
190
191         visit::walk_generics(self, generics);
192     }
193
194     fn visit_trait_item(&mut self, ti: &'a TraitItem) {
195         let def_data = match ti.node {
196             TraitItemKind::Method(..) | TraitItemKind::Const(..) =>
197                 DefPathData::ValueNs(ti.ident.name.as_str()),
198             TraitItemKind::Type(..) => DefPathData::TypeNs(ti.ident.name.as_str()),
199             TraitItemKind::Macro(..) => return self.visit_macro_invoc(ti.id, false),
200         };
201
202         let def = self.create_def(ti.id, def_data, ITEM_LIKE_SPACE);
203         self.with_parent(def, |this| {
204             if let TraitItemKind::Const(_, Some(ref expr)) = ti.node {
205                 this.visit_const_expr(expr);
206             }
207
208             visit::walk_trait_item(this, ti);
209         });
210     }
211
212     fn visit_impl_item(&mut self, ii: &'a ImplItem) {
213         let def_data = match ii.node {
214             ImplItemKind::Method(..) | ImplItemKind::Const(..) =>
215                 DefPathData::ValueNs(ii.ident.name.as_str()),
216             ImplItemKind::Type(..) => DefPathData::TypeNs(ii.ident.name.as_str()),
217             ImplItemKind::Macro(..) => return self.visit_macro_invoc(ii.id, false),
218         };
219
220         let def = self.create_def(ii.id, def_data, ITEM_LIKE_SPACE);
221         self.with_parent(def, |this| {
222             if let ImplItemKind::Const(_, ref expr) = ii.node {
223                 this.visit_const_expr(expr);
224             }
225
226             visit::walk_impl_item(this, ii);
227         });
228     }
229
230     fn visit_pat(&mut self, pat: &'a Pat) {
231         let parent_def = self.parent_def;
232
233         match pat.node {
234             PatKind::Mac(..) => return self.visit_macro_invoc(pat.id, false),
235             PatKind::Ident(_, id, _) => {
236                 let def = self.create_def(pat.id,
237                                           DefPathData::Binding(id.node.name.as_str()),
238                                           REGULAR_SPACE);
239                 self.parent_def = Some(def);
240             }
241             _ => {}
242         }
243
244         visit::walk_pat(self, pat);
245         self.parent_def = parent_def;
246     }
247
248     fn visit_expr(&mut self, expr: &'a Expr) {
249         let parent_def = self.parent_def;
250
251         match expr.node {
252             ExprKind::Mac(..) => return self.visit_macro_invoc(expr.id, false),
253             ExprKind::Repeat(_, ref count) => self.visit_const_expr(count),
254             ExprKind::Closure(..) => {
255                 let def = self.create_def(expr.id,
256                                           DefPathData::ClosureExpr,
257                                           REGULAR_SPACE);
258                 self.parent_def = Some(def);
259             }
260             _ => {}
261         }
262
263         visit::walk_expr(self, expr);
264         self.parent_def = parent_def;
265     }
266
267     fn visit_ty(&mut self, ty: &'a Ty) {
268         match ty.node {
269             TyKind::Mac(..) => return self.visit_macro_invoc(ty.id, false),
270             TyKind::Array(_, ref length) => self.visit_const_expr(length),
271             TyKind::ImplTrait(..) => {
272                 self.create_def(ty.id, DefPathData::ImplTrait, REGULAR_SPACE);
273             }
274             TyKind::Typeof(ref expr) => self.visit_const_expr(expr),
275             _ => {}
276         }
277         visit::walk_ty(self, ty);
278     }
279
280     fn visit_lifetime_def(&mut self, def: &'a LifetimeDef) {
281         self.create_def(def.lifetime.id,
282                         DefPathData::LifetimeDef(def.lifetime.name.as_str()),
283                         REGULAR_SPACE);
284     }
285
286     fn visit_stmt(&mut self, stmt: &'a Stmt) {
287         match stmt.node {
288             StmtKind::Mac(..) => self.visit_macro_invoc(stmt.id, false),
289             _ => visit::walk_stmt(self, stmt),
290         }
291     }
292 }