]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/map/def_collector.rs
syntax::parser::token -> syntax::token
[rust.git] / src / librustc / hir / map / def_collector.rs
1 use crate::hir::map::definitions::*;
2 use crate::hir::def_id::DefIndex;
3
4 use syntax::ast::*;
5 use syntax::visit;
6 use syntax::symbol::{kw, sym};
7 use syntax::token::{self, Token};
8 use syntax_pos::hygiene::ExpnId;
9 use syntax_pos::Span;
10
11 /// Creates `DefId`s for nodes in the AST.
12 pub struct DefCollector<'a> {
13     definitions: &'a mut Definitions,
14     parent_def: DefIndex,
15     expansion: ExpnId,
16 }
17
18 impl<'a> DefCollector<'a> {
19     pub fn new(definitions: &'a mut Definitions, expansion: ExpnId) -> Self {
20         let parent_def = definitions.invocation_parent(expansion);
21         DefCollector { definitions, parent_def, expansion }
22     }
23
24     fn create_def(&mut self,
25                   node_id: NodeId,
26                   data: DefPathData,
27                   span: Span)
28                   -> DefIndex {
29         let parent_def = self.parent_def;
30         debug!("create_def(node_id={:?}, data={:?}, parent_def={:?})", node_id, data, parent_def);
31         self.definitions.create_def_with_parent(parent_def, node_id, data, self.expansion, span)
32     }
33
34     fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_def: DefIndex, f: F) {
35         let orig_parent_def = std::mem::replace(&mut self.parent_def, parent_def);
36         f(self);
37         self.parent_def = orig_parent_def;
38     }
39
40     fn visit_async_fn(
41         &mut self,
42         id: NodeId,
43         name: Name,
44         span: Span,
45         header: &FnHeader,
46         generics: &'a Generics,
47         decl: &'a FnDecl,
48         body: &'a Block,
49     ) {
50         let (closure_id, return_impl_trait_id) = match header.asyncness.node {
51             IsAsync::Async {
52                 closure_id,
53                 return_impl_trait_id,
54             } => (closure_id, return_impl_trait_id),
55             _ => unreachable!(),
56         };
57
58         // For async functions, we need to create their inner defs inside of a
59         // closure to match their desugared representation.
60         let fn_def_data = DefPathData::ValueNs(name);
61         let fn_def = self.create_def(id, fn_def_data, span);
62         return self.with_parent(fn_def, |this| {
63             this.create_def(return_impl_trait_id, DefPathData::ImplTrait, span);
64
65             visit::walk_generics(this, generics);
66             visit::walk_fn_decl(this, decl);
67
68             let closure_def = this.create_def(
69                 closure_id, DefPathData::ClosureExpr, span,
70             );
71             this.with_parent(closure_def, |this| {
72                 visit::walk_block(this, body);
73             })
74         })
75     }
76
77     fn collect_field(&mut self, field: &'a StructField, index: Option<usize>) {
78         if field.is_placeholder {
79             self.visit_macro_invoc(field.id);
80         } else {
81             let name = field.ident.map(|ident| ident.name)
82                 .or_else(|| index.map(sym::integer))
83                 .unwrap_or_else(|| {
84                     let node_id = NodeId::placeholder_from_expn_id(self.expansion);
85                     sym::integer(self.definitions.placeholder_field_indices[&node_id])
86                 });
87             let def = self.create_def(field.id, DefPathData::ValueNs(name), field.span);
88             self.with_parent(def, |this| visit::walk_struct_field(this, field));
89         }
90     }
91
92     fn visit_macro_invoc(&mut self, id: NodeId) {
93         self.definitions.set_invocation_parent(id.placeholder_to_expn_id(), self.parent_def);
94     }
95 }
96
97 impl<'a> visit::Visitor<'a> for DefCollector<'a> {
98     fn visit_item(&mut self, i: &'a Item) {
99         debug!("visit_item: {:?}", i);
100
101         // Pick the def data. This need not be unique, but the more
102         // information we encapsulate into, the better
103         let def_data = match i.kind {
104             ItemKind::Impl(..) => DefPathData::Impl,
105             ItemKind::Mod(..) if i.ident.name == kw::Invalid => {
106                 return visit::walk_item(self, i);
107             }
108             ItemKind::Mod(..) | ItemKind::Trait(..) | ItemKind::TraitAlias(..) |
109             ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) |
110             ItemKind::OpaqueTy(..) | ItemKind::ExternCrate(..) | ItemKind::ForeignMod(..) |
111             ItemKind::TyAlias(..) => DefPathData::TypeNs(i.ident.name),
112             ItemKind::Fn(
113                 ref decl,
114                 ref header,
115                 ref generics,
116                 ref body,
117             ) if header.asyncness.node.is_async() => {
118                 return self.visit_async_fn(
119                     i.id,
120                     i.ident.name,
121                     i.span,
122                     header,
123                     generics,
124                     decl,
125                     body,
126                 )
127             }
128             ItemKind::Static(..) | ItemKind::Const(..) | ItemKind::Fn(..) =>
129                 DefPathData::ValueNs(i.ident.name),
130             ItemKind::MacroDef(..) => DefPathData::MacroNs(i.ident.name),
131             ItemKind::Mac(..) => return self.visit_macro_invoc(i.id),
132             ItemKind::GlobalAsm(..) => DefPathData::Misc,
133             ItemKind::Use(..) => {
134                 return visit::walk_item(self, i);
135             }
136         };
137         let def = self.create_def(i.id, def_data, i.span);
138
139         self.with_parent(def, |this| {
140             match i.kind {
141                 ItemKind::Struct(ref struct_def, _) | ItemKind::Union(ref struct_def, _) => {
142                     // If this is a unit or tuple-like struct, register the constructor.
143                     if let Some(ctor_hir_id) = struct_def.ctor_id() {
144                         this.create_def(ctor_hir_id, DefPathData::Ctor, i.span);
145                     }
146                 }
147                 _ => {}
148             }
149             visit::walk_item(this, i);
150         });
151     }
152
153     fn visit_use_tree(&mut self, use_tree: &'a UseTree, id: NodeId, _nested: bool) {
154         self.create_def(id, DefPathData::Misc, use_tree.span);
155         visit::walk_use_tree(self, use_tree, id);
156     }
157
158     fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
159         if let ForeignItemKind::Macro(_) = foreign_item.kind {
160             return self.visit_macro_invoc(foreign_item.id);
161         }
162
163         let def = self.create_def(foreign_item.id,
164                                   DefPathData::ValueNs(foreign_item.ident.name),
165                                   foreign_item.span);
166
167         self.with_parent(def, |this| {
168             visit::walk_foreign_item(this, foreign_item);
169         });
170     }
171
172     fn visit_variant(&mut self, v: &'a Variant) {
173         if v.is_placeholder {
174             return self.visit_macro_invoc(v.id);
175         }
176         let def = self.create_def(v.id,
177                                   DefPathData::TypeNs(v.ident.name),
178                                   v.span);
179         self.with_parent(def, |this| {
180             if let Some(ctor_hir_id) = v.data.ctor_id() {
181                 this.create_def(ctor_hir_id, DefPathData::Ctor, v.span);
182             }
183             visit::walk_variant(this, v)
184         });
185     }
186
187     fn visit_variant_data(&mut self, data: &'a VariantData) {
188         // The assumption here is that non-`cfg` macro expansion cannot change field indices.
189         // It currently holds because only inert attributes are accepted on fields,
190         // and every such attribute expands into a single field after it's resolved.
191         for (index, field) in data.fields().iter().enumerate() {
192             self.collect_field(field, Some(index));
193             if field.is_placeholder && field.ident.is_none() {
194                 self.definitions.placeholder_field_indices.insert(field.id, index);
195             }
196         }
197     }
198
199     fn visit_generic_param(&mut self, param: &'a GenericParam) {
200         if param.is_placeholder {
201             self.visit_macro_invoc(param.id);
202             return;
203         }
204         let name = param.ident.name;
205         let def_path_data = match param.kind {
206             GenericParamKind::Lifetime { .. } => DefPathData::LifetimeNs(name),
207             GenericParamKind::Type { .. } => DefPathData::TypeNs(name),
208             GenericParamKind::Const { .. } => DefPathData::ValueNs(name),
209         };
210         self.create_def(param.id, def_path_data, param.ident.span);
211
212         visit::walk_generic_param(self, param);
213     }
214
215     fn visit_trait_item(&mut self, ti: &'a TraitItem) {
216         let def_data = match ti.kind {
217             TraitItemKind::Method(..) | TraitItemKind::Const(..) =>
218                 DefPathData::ValueNs(ti.ident.name),
219             TraitItemKind::Type(..) => {
220                 DefPathData::TypeNs(ti.ident.name)
221             },
222             TraitItemKind::Macro(..) => return self.visit_macro_invoc(ti.id),
223         };
224
225         let def = self.create_def(ti.id, def_data, ti.span);
226         self.with_parent(def, |this| visit::walk_trait_item(this, ti));
227     }
228
229     fn visit_impl_item(&mut self, ii: &'a ImplItem) {
230         let def_data = match ii.kind {
231             ImplItemKind::Method(MethodSig {
232                 ref header,
233                 ref decl,
234             }, ref body) if header.asyncness.node.is_async() => {
235                 return self.visit_async_fn(
236                     ii.id,
237                     ii.ident.name,
238                     ii.span,
239                     header,
240                     &ii.generics,
241                     decl,
242                     body,
243                 )
244             }
245             ImplItemKind::Method(..) |
246             ImplItemKind::Const(..) => DefPathData::ValueNs(ii.ident.name),
247             ImplItemKind::TyAlias(..) |
248             ImplItemKind::OpaqueTy(..) => DefPathData::TypeNs(ii.ident.name),
249             ImplItemKind::Macro(..) => return self.visit_macro_invoc(ii.id),
250         };
251
252         let def = self.create_def(ii.id, def_data, ii.span);
253         self.with_parent(def, |this| visit::walk_impl_item(this, ii));
254     }
255
256     fn visit_pat(&mut self, pat: &'a Pat) {
257         match pat.kind {
258             PatKind::Mac(..) => return self.visit_macro_invoc(pat.id),
259             _ => visit::walk_pat(self, pat),
260         }
261     }
262
263     fn visit_anon_const(&mut self, constant: &'a AnonConst) {
264         let def = self.create_def(constant.id,
265                                   DefPathData::AnonConst,
266                                   constant.value.span);
267         self.with_parent(def, |this| visit::walk_anon_const(this, constant));
268     }
269
270     fn visit_expr(&mut self, expr: &'a Expr) {
271         let parent_def = match expr.kind {
272             ExprKind::Mac(..) => return self.visit_macro_invoc(expr.id),
273             ExprKind::Closure(_, asyncness, ..) => {
274                 // Async closures desugar to closures inside of closures, so
275                 // we must create two defs.
276                 let closure_def = self.create_def(expr.id, DefPathData::ClosureExpr, expr.span);
277                 match asyncness {
278                     IsAsync::Async { closure_id, .. } =>
279                         self.create_def(closure_id, DefPathData::ClosureExpr, expr.span),
280                     IsAsync::NotAsync => closure_def,
281                 }
282             }
283             ExprKind::Async(_, async_id, _) =>
284                 self.create_def(async_id, DefPathData::ClosureExpr, expr.span),
285             _ => self.parent_def,
286         };
287
288         self.with_parent(parent_def, |this| visit::walk_expr(this, expr));
289     }
290
291     fn visit_ty(&mut self, ty: &'a Ty) {
292         match ty.kind {
293             TyKind::Mac(..) => return self.visit_macro_invoc(ty.id),
294             TyKind::ImplTrait(node_id, _) => {
295                 self.create_def(node_id, DefPathData::ImplTrait, ty.span);
296             }
297             _ => {}
298         }
299         visit::walk_ty(self, ty);
300     }
301
302     fn visit_stmt(&mut self, stmt: &'a Stmt) {
303         match stmt.kind {
304             StmtKind::Mac(..) => self.visit_macro_invoc(stmt.id),
305             _ => visit::walk_stmt(self, stmt),
306         }
307     }
308
309     fn visit_token(&mut self, t: Token) {
310         if let token::Interpolated(nt) = t.kind {
311             if let token::NtExpr(ref expr) = *nt {
312                 if let ExprKind::Mac(..) = expr.kind {
313                     self.visit_macro_invoc(expr.id);
314                 }
315             }
316         }
317     }
318
319     fn visit_arm(&mut self, arm: &'a Arm) {
320         if arm.is_placeholder {
321             self.visit_macro_invoc(arm.id)
322         } else {
323             visit::walk_arm(self, arm)
324         }
325     }
326
327     fn visit_field(&mut self, f: &'a Field) {
328         if f.is_placeholder {
329             self.visit_macro_invoc(f.id)
330         } else {
331             visit::walk_field(self, f)
332         }
333     }
334
335     fn visit_field_pattern(&mut self, fp: &'a FieldPat) {
336         if fp.is_placeholder {
337             self.visit_macro_invoc(fp.id)
338         } else {
339             visit::walk_field_pattern(self, fp)
340         }
341     }
342
343     fn visit_param(&mut self, p: &'a Param) {
344         if p.is_placeholder {
345             self.visit_macro_invoc(p.id)
346         } else {
347             visit::walk_param(self, p)
348         }
349     }
350
351     // This method is called only when we are visiting an individual field
352     // after expanding an attribute on it.
353     fn visit_struct_field(&mut self, field: &'a StructField) {
354         self.collect_field(field, None);
355     }
356 }