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