]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/def_collector.rs
Rollup merge of #67404 - mark-i-m:split-1, r=matthewjasper
[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: Option<&'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                 if let Some(body) = body {
78                     visit::walk_block(this, body);
79                 }
80             })
81         })
82     }
83
84     fn collect_field(&mut self, field: &'a StructField, index: Option<usize>) {
85         let index = |this: &Self| index.unwrap_or_else(|| {
86             let node_id = NodeId::placeholder_from_expn_id(this.expansion);
87             this.definitions.placeholder_field_index(node_id)
88         });
89
90         if field.is_placeholder {
91             self.definitions.set_placeholder_field_index(field.id, index(self));
92             self.visit_macro_invoc(field.id);
93         } else {
94             let name = field.ident.map_or_else(|| sym::integer(index(self)), |ident| ident.name);
95             let def = self.create_def(field.id, DefPathData::ValueNs(name), field.span);
96             self.with_parent(def, |this| visit::walk_struct_field(this, field));
97         }
98     }
99
100     fn visit_macro_invoc(&mut self, id: NodeId) {
101         self.definitions.set_invocation_parent(id.placeholder_to_expn_id(), self.parent_def);
102     }
103 }
104
105 impl<'a> visit::Visitor<'a> for DefCollector<'a> {
106     fn visit_item(&mut self, i: &'a Item) {
107         debug!("visit_item: {:?}", i);
108
109         // Pick the def data. This need not be unique, but the more
110         // information we encapsulate into, the better
111         let def_data = match &i.kind {
112             ItemKind::Impl(..) => DefPathData::Impl,
113             ItemKind::Mod(..) if i.ident.name == kw::Invalid => {
114                 return visit::walk_item(self, i);
115             }
116             ItemKind::Mod(..) | ItemKind::Trait(..) | ItemKind::TraitAlias(..) |
117             ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) |
118             ItemKind::ExternCrate(..) | ItemKind::ForeignMod(..) |
119             ItemKind::TyAlias(..) => DefPathData::TypeNs(i.ident.name),
120             ItemKind::Fn(sig, generics, body) if sig.header.asyncness.node.is_async() => {
121                 return self.visit_async_fn(
122                     i.id,
123                     i.ident.name,
124                     i.span,
125                     &sig.header,
126                     generics,
127                     &sig.decl,
128                     Some(body),
129                 )
130             }
131             ItemKind::Static(..) | ItemKind::Const(..) | ItemKind::Fn(..) =>
132                 DefPathData::ValueNs(i.ident.name),
133             ItemKind::MacroDef(..) => DefPathData::MacroNs(i.ident.name),
134             ItemKind::Mac(..) => return self.visit_macro_invoc(i.id),
135             ItemKind::GlobalAsm(..) => DefPathData::Misc,
136             ItemKind::Use(..) => {
137                 return visit::walk_item(self, i);
138             }
139         };
140         let def = self.create_def(i.id, def_data, i.span);
141
142         self.with_parent(def, |this| {
143             match i.kind {
144                 ItemKind::Struct(ref struct_def, _) | ItemKind::Union(ref struct_def, _) => {
145                     // If this is a unit or tuple-like struct, register the constructor.
146                     if let Some(ctor_hir_id) = struct_def.ctor_id() {
147                         this.create_def(ctor_hir_id, DefPathData::Ctor, i.span);
148                     }
149                 }
150                 _ => {}
151             }
152             visit::walk_item(this, i);
153         });
154     }
155
156     fn visit_use_tree(&mut self, use_tree: &'a UseTree, id: NodeId, _nested: bool) {
157         self.create_def(id, DefPathData::Misc, use_tree.span);
158         visit::walk_use_tree(self, use_tree, id);
159     }
160
161     fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
162         if let ForeignItemKind::Macro(_) = foreign_item.kind {
163             return self.visit_macro_invoc(foreign_item.id);
164         }
165
166         let def = self.create_def(foreign_item.id,
167                                   DefPathData::ValueNs(foreign_item.ident.name),
168                                   foreign_item.span);
169
170         self.with_parent(def, |this| {
171             visit::walk_foreign_item(this, foreign_item);
172         });
173     }
174
175     fn visit_variant(&mut self, v: &'a Variant) {
176         if v.is_placeholder {
177             return self.visit_macro_invoc(v.id);
178         }
179         let def = self.create_def(v.id,
180                                   DefPathData::TypeNs(v.ident.name),
181                                   v.span);
182         self.with_parent(def, |this| {
183             if let Some(ctor_hir_id) = v.data.ctor_id() {
184                 this.create_def(ctor_hir_id, DefPathData::Ctor, v.span);
185             }
186             visit::walk_variant(this, v)
187         });
188     }
189
190     fn visit_variant_data(&mut self, data: &'a VariantData) {
191         // The assumption here is that non-`cfg` macro expansion cannot change field indices.
192         // It currently holds because only inert attributes are accepted on fields,
193         // and every such attribute expands into a single field after it's resolved.
194         for (index, field) in data.fields().iter().enumerate() {
195             self.collect_field(field, Some(index));
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 AssocItem) {
216         let def_data = match ti.kind {
217             AssocItemKind::Fn(..) | AssocItemKind::Const(..) => DefPathData::ValueNs(ti.ident.name),
218             AssocItemKind::TyAlias(..) => DefPathData::TypeNs(ti.ident.name),
219             AssocItemKind::Macro(..) => return self.visit_macro_invoc(ti.id),
220         };
221
222         let def = self.create_def(ti.id, def_data, ti.span);
223         self.with_parent(def, |this| visit::walk_trait_item(this, ti));
224     }
225
226     fn visit_impl_item(&mut self, ii: &'a AssocItem) {
227         let def_data = match ii.kind {
228             AssocItemKind::Fn(FnSig {
229                 ref header,
230                 ref decl,
231             }, ref body) if header.asyncness.node.is_async() => {
232                 return self.visit_async_fn(
233                     ii.id,
234                     ii.ident.name,
235                     ii.span,
236                     header,
237                     &ii.generics,
238                     decl,
239                     body.as_deref(),
240                 )
241             }
242             AssocItemKind::Fn(..) |
243             AssocItemKind::Const(..) => DefPathData::ValueNs(ii.ident.name),
244             AssocItemKind::TyAlias(..) => DefPathData::TypeNs(ii.ident.name),
245             AssocItemKind::Macro(..) => return self.visit_macro_invoc(ii.id),
246         };
247
248         let def = self.create_def(ii.id, def_data, ii.span);
249         self.with_parent(def, |this| visit::walk_impl_item(this, ii));
250     }
251
252     fn visit_pat(&mut self, pat: &'a Pat) {
253         match pat.kind {
254             PatKind::Mac(..) => return self.visit_macro_invoc(pat.id),
255             _ => visit::walk_pat(self, pat),
256         }
257     }
258
259     fn visit_anon_const(&mut self, constant: &'a AnonConst) {
260         let def = self.create_def(constant.id,
261                                   DefPathData::AnonConst,
262                                   constant.value.span);
263         self.with_parent(def, |this| visit::walk_anon_const(this, constant));
264     }
265
266     fn visit_expr(&mut self, expr: &'a Expr) {
267         let parent_def = match expr.kind {
268             ExprKind::Mac(..) => return self.visit_macro_invoc(expr.id),
269             ExprKind::Closure(_, asyncness, ..) => {
270                 // Async closures desugar to closures inside of closures, so
271                 // we must create two defs.
272                 let closure_def = self.create_def(expr.id, DefPathData::ClosureExpr, expr.span);
273                 match asyncness {
274                     IsAsync::Async { closure_id, .. } =>
275                         self.create_def(closure_id, DefPathData::ClosureExpr, expr.span),
276                     IsAsync::NotAsync => closure_def,
277                 }
278             }
279             ExprKind::Async(_, async_id, _) =>
280                 self.create_def(async_id, DefPathData::ClosureExpr, expr.span),
281             _ => self.parent_def,
282         };
283
284         self.with_parent(parent_def, |this| visit::walk_expr(this, expr));
285     }
286
287     fn visit_ty(&mut self, ty: &'a Ty) {
288         match ty.kind {
289             TyKind::Mac(..) => return self.visit_macro_invoc(ty.id),
290             TyKind::ImplTrait(node_id, _) => {
291                 self.create_def(node_id, DefPathData::ImplTrait, ty.span);
292             }
293             _ => {}
294         }
295         visit::walk_ty(self, ty);
296     }
297
298     fn visit_stmt(&mut self, stmt: &'a Stmt) {
299         match stmt.kind {
300             StmtKind::Mac(..) => self.visit_macro_invoc(stmt.id),
301             _ => visit::walk_stmt(self, stmt),
302         }
303     }
304
305     fn visit_token(&mut self, t: Token) {
306         if let token::Interpolated(nt) = t.kind {
307             if let token::NtExpr(ref expr) = *nt {
308                 if let ExprKind::Mac(..) = expr.kind {
309                     self.visit_macro_invoc(expr.id);
310                 }
311             }
312         }
313     }
314
315     fn visit_arm(&mut self, arm: &'a Arm) {
316         if arm.is_placeholder {
317             self.visit_macro_invoc(arm.id)
318         } else {
319             visit::walk_arm(self, arm)
320         }
321     }
322
323     fn visit_field(&mut self, f: &'a Field) {
324         if f.is_placeholder {
325             self.visit_macro_invoc(f.id)
326         } else {
327             visit::walk_field(self, f)
328         }
329     }
330
331     fn visit_field_pattern(&mut self, fp: &'a FieldPat) {
332         if fp.is_placeholder {
333             self.visit_macro_invoc(fp.id)
334         } else {
335             visit::walk_field_pattern(self, fp)
336         }
337     }
338
339     fn visit_param(&mut self, p: &'a Param) {
340         if p.is_placeholder {
341             self.visit_macro_invoc(p.id)
342         } else {
343             visit::walk_param(self, p)
344         }
345     }
346
347     // This method is called only when we are visiting an individual field
348     // after expanding an attribute on it.
349     fn visit_struct_field(&mut self, field: &'a StructField) {
350         self.collect_field(field, None);
351     }
352 }