]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/map/def_collector.rs
c1de6c15d41b3797e95d586a5c8b572ec4adae71
[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 }
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                   span: Span)
62                   -> DefIndex {
63         let parent_def = self.parent_def.unwrap();
64         debug!("create_def(node_id={:?}, data={:?}, parent_def={:?})", node_id, data, parent_def);
65         self.definitions
66             .create_def_with_parent(parent_def, node_id, data, address_space, self.expansion, span)
67     }
68
69     pub fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_def: DefIndex, f: F) {
70         let parent = self.parent_def;
71         self.parent_def = Some(parent_def);
72         f(self);
73         self.parent_def = parent;
74     }
75
76     fn visit_async_fn(
77         &mut self,
78         id: NodeId,
79         async_node_id: NodeId,
80         return_impl_trait_id: NodeId,
81         name: Name,
82         span: Span,
83         visit_fn: impl FnOnce(&mut DefCollector<'a>)
84     ) {
85         // For async functions, we need to create their inner defs inside of a
86         // closure to match their desugared representation.
87         let fn_def_data = DefPathData::ValueNs(name.as_interned_str());
88         let fn_def = self.create_def(id, fn_def_data, ITEM_LIKE_SPACE, span);
89         return self.with_parent(fn_def, |this| {
90             this.create_def(return_impl_trait_id, DefPathData::ImplTrait, REGULAR_SPACE, span);
91             let closure_def = this.create_def(async_node_id,
92                                   DefPathData::ClosureExpr,
93                                   REGULAR_SPACE,
94                                   span);
95             this.with_parent(closure_def, visit_fn)
96         })
97     }
98
99     fn visit_macro_invoc(&mut self, id: NodeId) {
100         if let Some(ref mut visit) = self.visit_macro_invoc {
101             visit(MacroInvocationData {
102                 mark: id.placeholder_to_mark(),
103                 def_index: self.parent_def.unwrap(),
104             })
105         }
106     }
107 }
108
109 impl<'a> visit::Visitor<'a> for DefCollector<'a> {
110     fn visit_item(&mut self, i: &'a Item) {
111         debug!("visit_item: {:?}", i);
112
113         // Pick the def data. This need not be unique, but the more
114         // information we encapsulate into, the better
115         let def_data = match i.node {
116             ItemKind::Impl(..) => DefPathData::Impl,
117             ItemKind::Trait(..) => DefPathData::Trait(i.ident.as_interned_str()),
118             ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) |
119             ItemKind::TraitAlias(..) |
120             ItemKind::ExternCrate(..) | ItemKind::ForeignMod(..) | ItemKind::Ty(..) =>
121                 DefPathData::TypeNs(i.ident.as_interned_str()),
122             ItemKind::Mod(..) if i.ident == keywords::Invalid.ident() => {
123                 return visit::walk_item(self, i);
124             }
125             ItemKind::Fn(_, FnHeader { asyncness: IsAsync::Async {
126                 closure_id,
127                 return_impl_trait_id,
128             }, .. }, ..) => {
129                 return self.visit_async_fn(
130                     i.id,
131                     closure_id,
132                     return_impl_trait_id,
133                     i.ident.name,
134                     i.span,
135                     |this| visit::walk_item(this, i)
136                 )
137             }
138             ItemKind::Mod(..) => DefPathData::Module(i.ident.as_interned_str()),
139             ItemKind::Static(..) | ItemKind::Const(..) | ItemKind::Fn(..) =>
140                 DefPathData::ValueNs(i.ident.as_interned_str()),
141             ItemKind::MacroDef(..) => DefPathData::MacroDef(i.ident.as_interned_str()),
142             ItemKind::Mac(..) => return self.visit_macro_invoc(i.id),
143             ItemKind::GlobalAsm(..) => DefPathData::Misc,
144             ItemKind::Use(..) => {
145                 return visit::walk_item(self, i);
146             }
147         };
148         let def = self.create_def(i.id, def_data, ITEM_LIKE_SPACE, i.span);
149
150         self.with_parent(def, |this| {
151             match i.node {
152                 ItemKind::Struct(ref struct_def, _) | ItemKind::Union(ref struct_def, _) => {
153                     // If this is a tuple-like struct, register the constructor.
154                     if !struct_def.is_struct() {
155                         this.create_def(struct_def.id(),
156                                         DefPathData::StructCtor,
157                                         REGULAR_SPACE,
158                                         i.span);
159                     }
160                 }
161                 _ => {}
162             }
163             visit::walk_item(this, i);
164         });
165     }
166
167     fn visit_use_tree(&mut self, use_tree: &'a UseTree, id: NodeId, _nested: bool) {
168         self.create_def(id, DefPathData::Misc, ITEM_LIKE_SPACE, use_tree.span);
169         visit::walk_use_tree(self, use_tree, id);
170     }
171
172     fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
173         if let ForeignItemKind::Macro(_) = foreign_item.node {
174             return self.visit_macro_invoc(foreign_item.id);
175         }
176
177         let def = self.create_def(foreign_item.id,
178                                   DefPathData::ValueNs(foreign_item.ident.as_interned_str()),
179                                   REGULAR_SPACE,
180                                   foreign_item.span);
181
182         self.with_parent(def, |this| {
183             visit::walk_foreign_item(this, foreign_item);
184         });
185     }
186
187     fn visit_variant(&mut self, v: &'a Variant, g: &'a Generics, item_id: NodeId) {
188         let def = self.create_def(v.node.data.id(),
189                                   DefPathData::EnumVariant(v.node.ident.as_interned_str()),
190                                   REGULAR_SPACE,
191                                   v.span);
192         self.with_parent(def, |this| visit::walk_variant(this, v, g, item_id));
193     }
194
195     fn visit_variant_data(&mut self, data: &'a VariantData, _: Ident,
196                           _: &'a Generics, _: NodeId, _: Span) {
197         for (index, field) in data.fields().iter().enumerate() {
198             let name = field.ident.map(|ident| ident.name)
199                 .unwrap_or_else(|| Symbol::intern(&index.to_string()));
200             let def = self.create_def(field.id,
201                                       DefPathData::Field(name.as_interned_str()),
202                                       REGULAR_SPACE,
203                                       field.span);
204             self.with_parent(def, |this| this.visit_struct_field(field));
205         }
206     }
207
208     fn visit_generic_param(&mut self, param: &'a GenericParam) {
209         let name = param.ident.as_interned_str();
210         let def_path_data = match param.kind {
211             GenericParamKind::Lifetime { .. } => DefPathData::LifetimeParam(name),
212             GenericParamKind::Type { .. } => DefPathData::TypeParam(name),
213         };
214         self.create_def(param.id, def_path_data, REGULAR_SPACE, param.ident.span);
215
216         visit::walk_generic_param(self, param);
217     }
218
219     fn visit_trait_item(&mut self, ti: &'a TraitItem) {
220         let def_data = match ti.node {
221             TraitItemKind::Method(..) | TraitItemKind::Const(..) =>
222                 DefPathData::ValueNs(ti.ident.as_interned_str()),
223             TraitItemKind::Type(..) => {
224                 DefPathData::AssocTypeInTrait(ti.ident.as_interned_str())
225             },
226             TraitItemKind::Macro(..) => return self.visit_macro_invoc(ti.id),
227         };
228
229         let def = self.create_def(ti.id, def_data, ITEM_LIKE_SPACE, ti.span);
230         self.with_parent(def, |this| visit::walk_trait_item(this, ti));
231     }
232
233     fn visit_impl_item(&mut self, ii: &'a ImplItem) {
234         let def_data = match ii.node {
235             ImplItemKind::Method(MethodSig {
236                 header: FnHeader { asyncness: IsAsync::Async {
237                     closure_id,
238                     return_impl_trait_id,
239                 }, .. }, ..
240             }, ..) => {
241                 return self.visit_async_fn(
242                     ii.id,
243                     closure_id,
244                     return_impl_trait_id,
245                     ii.ident.name,
246                     ii.span,
247                     |this| visit::walk_impl_item(this, ii)
248                 )
249             }
250             ImplItemKind::Method(..) | ImplItemKind::Const(..) =>
251                 DefPathData::ValueNs(ii.ident.as_interned_str()),
252             ImplItemKind::Type(..) => DefPathData::AssocTypeInImpl(ii.ident.as_interned_str()),
253             ImplItemKind::Macro(..) => return self.visit_macro_invoc(ii.id),
254         };
255
256         let def = self.create_def(ii.id, def_data, ITEM_LIKE_SPACE, ii.span);
257         self.with_parent(def, |this| visit::walk_impl_item(this, ii));
258     }
259
260     fn visit_pat(&mut self, pat: &'a Pat) {
261         match pat.node {
262             PatKind::Mac(..) => return self.visit_macro_invoc(pat.id),
263             _ => visit::walk_pat(self, pat),
264         }
265     }
266
267     fn visit_anon_const(&mut self, constant: &'a AnonConst) {
268         let def = self.create_def(constant.id,
269                                   DefPathData::AnonConst,
270                                   REGULAR_SPACE,
271                                   constant.value.span);
272         self.with_parent(def, |this| visit::walk_anon_const(this, constant));
273     }
274
275     fn visit_expr(&mut self, expr: &'a Expr) {
276         let parent_def = self.parent_def;
277
278         match expr.node {
279             ExprKind::Mac(..) => return self.visit_macro_invoc(expr.id),
280             ExprKind::Closure(_, asyncness, ..) => {
281                 let closure_def = self.create_def(expr.id,
282                                           DefPathData::ClosureExpr,
283                                           REGULAR_SPACE,
284                                           expr.span);
285                 self.parent_def = Some(closure_def);
286
287                 // Async closures desugar to closures inside of closures, so
288                 // we must create two defs.
289                 if let IsAsync::Async { closure_id, .. } = asyncness {
290                     let async_def = self.create_def(closure_id,
291                                                     DefPathData::ClosureExpr,
292                                                     REGULAR_SPACE,
293                                                     expr.span);
294                     self.parent_def = Some(async_def);
295                 }
296             }
297             ExprKind::Async(_, async_id, _) => {
298                 let async_def = self.create_def(async_id,
299                                                 DefPathData::ClosureExpr,
300                                                 REGULAR_SPACE,
301                                                 expr.span);
302                 self.parent_def = Some(async_def);
303             }
304             _ => {}
305         };
306
307         visit::walk_expr(self, expr);
308         self.parent_def = parent_def;
309     }
310
311     fn visit_ty(&mut self, ty: &'a Ty) {
312         match ty.node {
313             TyKind::Mac(..) => return self.visit_macro_invoc(ty.id),
314             TyKind::ImplTrait(node_id, _) => {
315                 self.create_def(node_id, DefPathData::ImplTrait, REGULAR_SPACE, ty.span);
316             }
317             _ => {}
318         }
319         visit::walk_ty(self, ty);
320     }
321
322     fn visit_stmt(&mut self, stmt: &'a Stmt) {
323         match stmt.node {
324             StmtKind::Mac(..) => self.visit_macro_invoc(stmt.id),
325             _ => visit::walk_stmt(self, stmt),
326         }
327     }
328
329     fn visit_token(&mut self, t: Token) {
330         if let Token::Interpolated(nt) = t {
331             match nt.0 {
332                 token::NtExpr(ref expr) => {
333                     if let ExprKind::Mac(..) = expr.node {
334                         self.visit_macro_invoc(expr.id);
335                     }
336                 }
337                 _ => {}
338             }
339         }
340     }
341 }