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