]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/def_collector.rs
Rollup merge of #66641 - VirrageS:master, r=Centril
[rust.git] / src / librustc_resolve / def_collector.rs
1 use log::debug;
2 use rustc::hir::map::definitions::*;
3 use rustc::hir::def_id::DefIndex;
4 use syntax::ast::*;
5 use syntax::visit;
6 use syntax::symbol::{kw, sym};
7 use syntax::token::{self, Token};
8 use syntax_expand::expand::AstFragment;
9 use syntax_pos::hygiene::ExpnId;
10 use syntax_pos::Span;
11
12 crate fn collect_definitions(
13     definitions: &mut Definitions,
14     fragment: &AstFragment,
15     expansion: ExpnId,
16 ) {
17     let parent_def = definitions.invocation_parent(expansion);
18     fragment.visit_with(&mut DefCollector { definitions, parent_def, expansion });
19 }
20
21 /// Creates `DefId`s for nodes in the AST.
22 struct DefCollector<'a> {
23     definitions: &'a mut Definitions,
24     parent_def: DefIndex,
25     expansion: ExpnId,
26 }
27
28 impl<'a> DefCollector<'a> {
29     fn create_def(&mut self,
30                   node_id: NodeId,
31                   data: DefPathData,
32                   span: Span)
33                   -> DefIndex {
34         let parent_def = self.parent_def;
35         debug!("create_def(node_id={:?}, data={:?}, parent_def={:?})", node_id, data, parent_def);
36         self.definitions.create_def_with_parent(parent_def, node_id, data, self.expansion, span)
37     }
38
39     fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_def: DefIndex, f: F) {
40         let orig_parent_def = std::mem::replace(&mut self.parent_def, parent_def);
41         f(self);
42         self.parent_def = orig_parent_def;
43     }
44
45     fn visit_async_fn(
46         &mut self,
47         id: NodeId,
48         name: Name,
49         span: Span,
50         header: &FnHeader,
51         generics: &'a Generics,
52         decl: &'a FnDecl,
53         body: &'a Block,
54     ) {
55         let (closure_id, return_impl_trait_id) = match header.asyncness.node {
56             IsAsync::Async {
57                 closure_id,
58                 return_impl_trait_id,
59             } => (closure_id, return_impl_trait_id),
60             _ => unreachable!(),
61         };
62
63         // For async functions, we need to create their inner defs inside of a
64         // closure to match their desugared representation.
65         let fn_def_data = DefPathData::ValueNs(name);
66         let fn_def = self.create_def(id, fn_def_data, span);
67         return self.with_parent(fn_def, |this| {
68             this.create_def(return_impl_trait_id, DefPathData::ImplTrait, span);
69
70             visit::walk_generics(this, generics);
71             visit::walk_fn_decl(this, decl);
72
73             let closure_def = this.create_def(
74                 closure_id, DefPathData::ClosureExpr, span,
75             );
76             this.with_parent(closure_def, |this| {
77                 visit::walk_block(this, body);
78             })
79         })
80     }
81
82     fn collect_field(&mut self, field: &'a StructField, index: Option<usize>) {
83         if field.is_placeholder {
84             self.visit_macro_invoc(field.id);
85         } else {
86             let name = field.ident.map(|ident| ident.name)
87                 .or_else(|| index.map(sym::integer))
88                 .unwrap_or_else(|| {
89                     let node_id = NodeId::placeholder_from_expn_id(self.expansion);
90                     sym::integer(self.definitions.placeholder_field_index(node_id))
91                 });
92             let def = self.create_def(field.id, DefPathData::ValueNs(name), field.span);
93             self.with_parent(def, |this| visit::walk_struct_field(this, field));
94         }
95     }
96
97     fn visit_macro_invoc(&mut self, id: NodeId) {
98         self.definitions.set_invocation_parent(id.placeholder_to_expn_id(), self.parent_def);
99     }
100 }
101
102 impl<'a> visit::Visitor<'a> for DefCollector<'a> {
103     fn visit_item(&mut self, i: &'a Item) {
104         debug!("visit_item: {:?}", i);
105
106         // Pick the def data. This need not be unique, but the more
107         // information we encapsulate into, the better
108         let def_data = match &i.kind {
109             ItemKind::Impl(..) => DefPathData::Impl,
110             ItemKind::Mod(..) if i.ident.name == kw::Invalid => {
111                 return visit::walk_item(self, i);
112             }
113             ItemKind::Mod(..) | ItemKind::Trait(..) | ItemKind::TraitAlias(..) |
114             ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) |
115             ItemKind::ExternCrate(..) | ItemKind::ForeignMod(..) |
116             ItemKind::TyAlias(..) => DefPathData::TypeNs(i.ident.name),
117             ItemKind::Fn(sig, generics, body) if sig.header.asyncness.node.is_async() => {
118                 return self.visit_async_fn(
119                     i.id,
120                     i.ident.name,
121                     i.span,
122                     &sig.header,
123                     generics,
124                     &sig.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.set_placeholder_field_index(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(FnSig {
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(..) => DefPathData::TypeNs(ii.ident.name),
248             ImplItemKind::Macro(..) => return self.visit_macro_invoc(ii.id),
249         };
250
251         let def = self.create_def(ii.id, def_data, ii.span);
252         self.with_parent(def, |this| visit::walk_impl_item(this, ii));
253     }
254
255     fn visit_pat(&mut self, pat: &'a Pat) {
256         match pat.kind {
257             PatKind::Mac(..) => return self.visit_macro_invoc(pat.id),
258             _ => visit::walk_pat(self, pat),
259         }
260     }
261
262     fn visit_anon_const(&mut self, constant: &'a AnonConst) {
263         let def = self.create_def(constant.id,
264                                   DefPathData::AnonConst,
265                                   constant.value.span);
266         self.with_parent(def, |this| visit::walk_anon_const(this, constant));
267     }
268
269     fn visit_expr(&mut self, expr: &'a Expr) {
270         let parent_def = match expr.kind {
271             ExprKind::Mac(..) => return self.visit_macro_invoc(expr.id),
272             ExprKind::Closure(_, asyncness, ..) => {
273                 // Async closures desugar to closures inside of closures, so
274                 // we must create two defs.
275                 let closure_def = self.create_def(expr.id, DefPathData::ClosureExpr, expr.span);
276                 match asyncness {
277                     IsAsync::Async { closure_id, .. } =>
278                         self.create_def(closure_id, DefPathData::ClosureExpr, expr.span),
279                     IsAsync::NotAsync => closure_def,
280                 }
281             }
282             ExprKind::Async(_, async_id, _) =>
283                 self.create_def(async_id, DefPathData::ClosureExpr, expr.span),
284             _ => self.parent_def,
285         };
286
287         self.with_parent(parent_def, |this| visit::walk_expr(this, expr));
288     }
289
290     fn visit_ty(&mut self, ty: &'a Ty) {
291         match ty.kind {
292             TyKind::Mac(..) => return self.visit_macro_invoc(ty.id),
293             TyKind::ImplTrait(node_id, _) => {
294                 self.create_def(node_id, DefPathData::ImplTrait, ty.span);
295             }
296             _ => {}
297         }
298         visit::walk_ty(self, ty);
299     }
300
301     fn visit_stmt(&mut self, stmt: &'a Stmt) {
302         match stmt.kind {
303             StmtKind::Mac(..) => self.visit_macro_invoc(stmt.id),
304             _ => visit::walk_stmt(self, stmt),
305         }
306     }
307
308     fn visit_token(&mut self, t: Token) {
309         if let token::Interpolated(nt) = t.kind {
310             if let token::NtExpr(ref expr) = *nt {
311                 if let ExprKind::Mac(..) = expr.kind {
312                     self.visit_macro_invoc(expr.id);
313                 }
314             }
315         }
316     }
317
318     fn visit_arm(&mut self, arm: &'a Arm) {
319         if arm.is_placeholder {
320             self.visit_macro_invoc(arm.id)
321         } else {
322             visit::walk_arm(self, arm)
323         }
324     }
325
326     fn visit_field(&mut self, f: &'a Field) {
327         if f.is_placeholder {
328             self.visit_macro_invoc(f.id)
329         } else {
330             visit::walk_field(self, f)
331         }
332     }
333
334     fn visit_field_pattern(&mut self, fp: &'a FieldPat) {
335         if fp.is_placeholder {
336             self.visit_macro_invoc(fp.id)
337         } else {
338             visit::walk_field_pattern(self, fp)
339         }
340     }
341
342     fn visit_param(&mut self, p: &'a Param) {
343         if p.is_placeholder {
344             self.visit_macro_invoc(p.id)
345         } else {
346             visit::walk_param(self, p)
347         }
348     }
349
350     // This method is called only when we are visiting an individual field
351     // after expanding an attribute on it.
352     fn visit_struct_field(&mut self, field: &'a StructField) {
353         self.collect_field(field, None);
354     }
355 }