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