]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/def_collector.rs
Rollup merge of #68357 - ollie27:rustdoc_test_errors, r=GuillaumeGomez
[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.node {
52             IsAsync::Async { 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.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             }
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_trait_item(&mut self, ti: &'a AssocItem) {
217         let def_data = match ti.kind {
218             AssocItemKind::Fn(..) | AssocItemKind::Const(..) => DefPathData::ValueNs(ti.ident.name),
219             AssocItemKind::TyAlias(..) => DefPathData::TypeNs(ti.ident.name),
220             AssocItemKind::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 AssocItem) {
228         let def_data = match ii.kind {
229             AssocItemKind::Fn(FnSig { ref header, ref decl }, ref body)
230                 if header.asyncness.node.is_async() =>
231             {
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(..) | AssocItemKind::Const(..) => DefPathData::ValueNs(ii.ident.name),
243             AssocItemKind::TyAlias(..) => DefPathData::TypeNs(ii.ident.name),
244             AssocItemKind::Macro(..) => return self.visit_macro_invoc(ii.id),
245         };
246
247         let def = self.create_def(ii.id, def_data, ii.span);
248         self.with_parent(def, |this| visit::walk_impl_item(this, ii));
249     }
250
251     fn visit_pat(&mut self, pat: &'a Pat) {
252         match pat.kind {
253             PatKind::Mac(..) => return self.visit_macro_invoc(pat.id),
254             _ => visit::walk_pat(self, pat),
255         }
256     }
257
258     fn visit_anon_const(&mut self, constant: &'a AnonConst) {
259         let def = self.create_def(constant.id, DefPathData::AnonConst, constant.value.span);
260         self.with_parent(def, |this| visit::walk_anon_const(this, constant));
261     }
262
263     fn visit_expr(&mut self, expr: &'a Expr) {
264         let parent_def = match expr.kind {
265             ExprKind::Mac(..) => return self.visit_macro_invoc(expr.id),
266             ExprKind::Closure(_, asyncness, ..) => {
267                 // Async closures desugar to closures inside of closures, so
268                 // we must create two defs.
269                 let closure_def = self.create_def(expr.id, DefPathData::ClosureExpr, expr.span);
270                 match asyncness {
271                     IsAsync::Async { closure_id, .. } => {
272                         self.create_def(closure_id, DefPathData::ClosureExpr, expr.span)
273                     }
274                     IsAsync::NotAsync => closure_def,
275                 }
276             }
277             ExprKind::Async(_, async_id, _) => {
278                 self.create_def(async_id, DefPathData::ClosureExpr, expr.span)
279             }
280             _ => self.parent_def,
281         };
282
283         self.with_parent(parent_def, |this| visit::walk_expr(this, expr));
284     }
285
286     fn visit_ty(&mut self, ty: &'a Ty) {
287         match ty.kind {
288             TyKind::Mac(..) => return self.visit_macro_invoc(ty.id),
289             TyKind::ImplTrait(node_id, _) => {
290                 self.create_def(node_id, DefPathData::ImplTrait, ty.span);
291             }
292             _ => {}
293         }
294         visit::walk_ty(self, ty);
295     }
296
297     fn visit_stmt(&mut self, stmt: &'a Stmt) {
298         match stmt.kind {
299             StmtKind::Mac(..) => self.visit_macro_invoc(stmt.id),
300             _ => visit::walk_stmt(self, stmt),
301         }
302     }
303
304     fn visit_token(&mut self, t: Token) {
305         if let token::Interpolated(nt) = t.kind {
306             if let token::NtExpr(ref expr) = *nt {
307                 if let ExprKind::Mac(..) = expr.kind {
308                     self.visit_macro_invoc(expr.id);
309                 }
310             }
311         }
312     }
313
314     fn visit_arm(&mut self, arm: &'a Arm) {
315         if arm.is_placeholder { self.visit_macro_invoc(arm.id) } else { visit::walk_arm(self, arm) }
316     }
317
318     fn visit_field(&mut self, f: &'a Field) {
319         if f.is_placeholder { self.visit_macro_invoc(f.id) } else { visit::walk_field(self, f) }
320     }
321
322     fn visit_field_pattern(&mut self, fp: &'a FieldPat) {
323         if fp.is_placeholder {
324             self.visit_macro_invoc(fp.id)
325         } else {
326             visit::walk_field_pattern(self, fp)
327         }
328     }
329
330     fn visit_param(&mut self, p: &'a Param) {
331         if p.is_placeholder { self.visit_macro_invoc(p.id) } else { visit::walk_param(self, p) }
332     }
333
334     // This method is called only when we are visiting an individual field
335     // after expanding an attribute on it.
336     fn visit_struct_field(&mut self, field: &'a StructField) {
337         self.collect_field(field, None);
338     }
339 }