]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_resolve/src/def_collector.rs
Rollup merge of #106739 - WaffleLapkin:astconv, r=estebank
[rust.git] / compiler / rustc_resolve / src / def_collector.rs
1 use crate::{ImplTraitContext, Resolver};
2 use rustc_ast::visit::{self, FnKind};
3 use rustc_ast::*;
4 use rustc_expand::expand::AstFragment;
5 use rustc_hir::def_id::LocalDefId;
6 use rustc_hir::definitions::*;
7 use rustc_span::hygiene::LocalExpnId;
8 use rustc_span::symbol::sym;
9 use rustc_span::Span;
10
11 pub(crate) fn collect_definitions(
12     resolver: &mut Resolver<'_>,
13     fragment: &AstFragment,
14     expansion: LocalExpnId,
15 ) {
16     let (parent_def, impl_trait_context) = resolver.invocation_parents[&expansion];
17     fragment.visit_with(&mut DefCollector { resolver, parent_def, expansion, impl_trait_context });
18 }
19
20 /// Creates `DefId`s for nodes in the AST.
21 struct DefCollector<'a, 'b> {
22     resolver: &'a mut Resolver<'b>,
23     parent_def: LocalDefId,
24     impl_trait_context: ImplTraitContext,
25     expansion: LocalExpnId,
26 }
27
28 impl<'a, 'b> DefCollector<'a, 'b> {
29     fn create_def(&mut self, node_id: NodeId, data: DefPathData, span: Span) -> LocalDefId {
30         let parent_def = self.parent_def;
31         debug!("create_def(node_id={:?}, data={:?}, parent_def={:?})", node_id, data, parent_def);
32         self.resolver.create_def(
33             parent_def,
34             node_id,
35             data,
36             self.expansion.to_expn_id(),
37             span.with_parent(None),
38         )
39     }
40
41     fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_def: LocalDefId, f: F) {
42         let orig_parent_def = std::mem::replace(&mut self.parent_def, parent_def);
43         f(self);
44         self.parent_def = orig_parent_def;
45     }
46
47     fn with_impl_trait<F: FnOnce(&mut Self)>(
48         &mut self,
49         impl_trait_context: ImplTraitContext,
50         f: F,
51     ) {
52         let orig_itc = std::mem::replace(&mut self.impl_trait_context, impl_trait_context);
53         f(self);
54         self.impl_trait_context = orig_itc;
55     }
56
57     fn collect_field(&mut self, field: &'a FieldDef, index: Option<usize>) {
58         let index = |this: &Self| {
59             index.unwrap_or_else(|| {
60                 let node_id = NodeId::placeholder_from_expn_id(this.expansion);
61                 this.resolver.placeholder_field_indices[&node_id]
62             })
63         };
64
65         if field.is_placeholder {
66             let old_index = self.resolver.placeholder_field_indices.insert(field.id, index(self));
67             assert!(old_index.is_none(), "placeholder field index is reset for a node ID");
68             self.visit_macro_invoc(field.id);
69         } else {
70             let name = field.ident.map_or_else(|| sym::integer(index(self)), |ident| ident.name);
71             let def = self.create_def(field.id, DefPathData::ValueNs(name), field.span);
72             self.with_parent(def, |this| visit::walk_field_def(this, field));
73         }
74     }
75
76     fn visit_macro_invoc(&mut self, id: NodeId) {
77         let id = id.placeholder_to_expn_id();
78         let old_parent =
79             self.resolver.invocation_parents.insert(id, (self.parent_def, self.impl_trait_context));
80         assert!(old_parent.is_none(), "parent `LocalDefId` is reset for an invocation");
81     }
82 }
83
84 impl<'a, 'b> visit::Visitor<'a> for DefCollector<'a, 'b> {
85     fn visit_item(&mut self, i: &'a Item) {
86         debug!("visit_item: {:?}", i);
87
88         // Pick the def data. This need not be unique, but the more
89         // information we encapsulate into, the better
90         let def_data = match &i.kind {
91             ItemKind::Impl { .. } => DefPathData::Impl,
92             ItemKind::ForeignMod(..) => DefPathData::ForeignMod,
93             ItemKind::Mod(..)
94             | ItemKind::Trait(..)
95             | ItemKind::TraitAlias(..)
96             | ItemKind::Enum(..)
97             | ItemKind::Struct(..)
98             | ItemKind::Union(..)
99             | ItemKind::ExternCrate(..)
100             | ItemKind::TyAlias(..) => DefPathData::TypeNs(i.ident.name),
101             ItemKind::Static(..) | ItemKind::Const(..) | ItemKind::Fn(..) => {
102                 DefPathData::ValueNs(i.ident.name)
103             }
104             ItemKind::MacroDef(..) => DefPathData::MacroNs(i.ident.name),
105             ItemKind::MacCall(..) => {
106                 visit::walk_item(self, i);
107                 return self.visit_macro_invoc(i.id);
108             }
109             ItemKind::GlobalAsm(..) => DefPathData::GlobalAsm,
110             ItemKind::Use(..) => {
111                 return visit::walk_item(self, i);
112             }
113         };
114         let def = self.create_def(i.id, def_data, i.span);
115
116         self.with_parent(def, |this| {
117             this.with_impl_trait(ImplTraitContext::Existential, |this| {
118                 match i.kind {
119                     ItemKind::Struct(ref struct_def, _) | ItemKind::Union(ref struct_def, _) => {
120                         // If this is a unit or tuple-like struct, register the constructor.
121                         if let Some(ctor_node_id) = struct_def.ctor_node_id() {
122                             this.create_def(ctor_node_id, DefPathData::Ctor, i.span);
123                         }
124                     }
125                     _ => {}
126                 }
127                 visit::walk_item(this, i);
128             })
129         });
130     }
131
132     fn visit_fn(&mut self, fn_kind: FnKind<'a>, span: Span, _: NodeId) {
133         if let FnKind::Fn(_, _, sig, _, generics, body) = fn_kind {
134             if let Async::Yes { closure_id, .. } = sig.header.asyncness {
135                 self.visit_generics(generics);
136
137                 // For async functions, we need to create their inner defs inside of a
138                 // closure to match their desugared representation. Besides that,
139                 // we must mirror everything that `visit::walk_fn` below does.
140                 self.visit_fn_header(&sig.header);
141                 for param in &sig.decl.inputs {
142                     self.visit_param(param);
143                 }
144                 self.visit_fn_ret_ty(&sig.decl.output);
145                 // If this async fn has no body (i.e. it's an async fn signature in a trait)
146                 // then the closure_def will never be used, and we should avoid generating a
147                 // def-id for it.
148                 if let Some(body) = body {
149                     let closure_def = self.create_def(closure_id, DefPathData::ClosureExpr, span);
150                     self.with_parent(closure_def, |this| this.visit_block(body));
151                 }
152                 return;
153             }
154         }
155
156         visit::walk_fn(self, fn_kind);
157     }
158
159     fn visit_use_tree(&mut self, use_tree: &'a UseTree, id: NodeId, _nested: bool) {
160         self.create_def(id, DefPathData::Use, use_tree.span);
161         visit::walk_use_tree(self, use_tree, id);
162     }
163
164     fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
165         if let ForeignItemKind::MacCall(_) = foreign_item.kind {
166             return self.visit_macro_invoc(foreign_item.id);
167         }
168
169         let def = self.create_def(
170             foreign_item.id,
171             DefPathData::ValueNs(foreign_item.ident.name),
172             foreign_item.span,
173         );
174
175         self.with_parent(def, |this| {
176             visit::walk_foreign_item(this, foreign_item);
177         });
178     }
179
180     fn visit_variant(&mut self, v: &'a Variant) {
181         if v.is_placeholder {
182             return self.visit_macro_invoc(v.id);
183         }
184         let def = self.create_def(v.id, DefPathData::TypeNs(v.ident.name), v.span);
185         self.with_parent(def, |this| {
186             if let Some(ctor_node_id) = v.data.ctor_node_id() {
187                 this.create_def(ctor_node_id, DefPathData::Ctor, v.span);
188             }
189             visit::walk_variant(this, v)
190         });
191     }
192
193     fn visit_variant_data(&mut self, data: &'a VariantData) {
194         // The assumption here is that non-`cfg` macro expansion cannot change field indices.
195         // It currently holds because only inert attributes are accepted on fields,
196         // and every such attribute expands into a single field after it's resolved.
197         for (index, field) in data.fields().iter().enumerate() {
198             self.collect_field(field, Some(index));
199         }
200     }
201
202     fn visit_generic_param(&mut self, param: &'a GenericParam) {
203         if param.is_placeholder {
204             self.visit_macro_invoc(param.id);
205             return;
206         }
207         let name = param.ident.name;
208         let def_path_data = match param.kind {
209             GenericParamKind::Lifetime { .. } => DefPathData::LifetimeNs(name),
210             GenericParamKind::Type { .. } => DefPathData::TypeNs(name),
211             GenericParamKind::Const { .. } => DefPathData::ValueNs(name),
212         };
213         self.create_def(param.id, def_path_data, param.ident.span);
214
215         // impl-Trait can happen inside generic parameters, like
216         // ```
217         // fn foo<U: Iterator<Item = impl Clone>>() {}
218         // ```
219         //
220         // In that case, the impl-trait is lowered as an additional generic parameter.
221         self.with_impl_trait(ImplTraitContext::Universal(self.parent_def), |this| {
222             visit::walk_generic_param(this, param)
223         });
224     }
225
226     fn visit_assoc_item(&mut self, i: &'a AssocItem, ctxt: visit::AssocCtxt) {
227         let def_data = match &i.kind {
228             AssocItemKind::Fn(..) | AssocItemKind::Const(..) => DefPathData::ValueNs(i.ident.name),
229             AssocItemKind::Type(..) => DefPathData::TypeNs(i.ident.name),
230             AssocItemKind::MacCall(..) => return self.visit_macro_invoc(i.id),
231         };
232
233         let def = self.create_def(i.id, def_data, i.span);
234         self.with_parent(def, |this| visit::walk_assoc_item(this, i, ctxt));
235     }
236
237     fn visit_pat(&mut self, pat: &'a Pat) {
238         match pat.kind {
239             PatKind::MacCall(..) => self.visit_macro_invoc(pat.id),
240             _ => visit::walk_pat(self, pat),
241         }
242     }
243
244     fn visit_anon_const(&mut self, constant: &'a AnonConst) {
245         let def = self.create_def(constant.id, DefPathData::AnonConst, constant.value.span);
246         self.with_parent(def, |this| visit::walk_anon_const(this, constant));
247     }
248
249     fn visit_expr(&mut self, expr: &'a Expr) {
250         let parent_def = match expr.kind {
251             ExprKind::MacCall(..) => return self.visit_macro_invoc(expr.id),
252             ExprKind::Closure(ref closure) => {
253                 // Async closures desugar to closures inside of closures, so
254                 // we must create two defs.
255                 let closure_def = self.create_def(expr.id, DefPathData::ClosureExpr, expr.span);
256                 match closure.asyncness {
257                     Async::Yes { closure_id, .. } => {
258                         self.create_def(closure_id, DefPathData::ClosureExpr, expr.span)
259                     }
260                     Async::No => closure_def,
261                 }
262             }
263             ExprKind::Async(_, async_id, _) => {
264                 self.create_def(async_id, DefPathData::ClosureExpr, expr.span)
265             }
266             _ => self.parent_def,
267         };
268
269         self.with_parent(parent_def, |this| visit::walk_expr(this, expr));
270     }
271
272     fn visit_ty(&mut self, ty: &'a Ty) {
273         match ty.kind {
274             TyKind::MacCall(..) => self.visit_macro_invoc(ty.id),
275             _ => visit::walk_ty(self, ty),
276         }
277     }
278
279     fn visit_stmt(&mut self, stmt: &'a Stmt) {
280         match stmt.kind {
281             StmtKind::MacCall(..) => self.visit_macro_invoc(stmt.id),
282             _ => visit::walk_stmt(self, stmt),
283         }
284     }
285
286     fn visit_arm(&mut self, arm: &'a Arm) {
287         if arm.is_placeholder { self.visit_macro_invoc(arm.id) } else { visit::walk_arm(self, arm) }
288     }
289
290     fn visit_expr_field(&mut self, f: &'a ExprField) {
291         if f.is_placeholder {
292             self.visit_macro_invoc(f.id)
293         } else {
294             visit::walk_expr_field(self, f)
295         }
296     }
297
298     fn visit_pat_field(&mut self, fp: &'a PatField) {
299         if fp.is_placeholder {
300             self.visit_macro_invoc(fp.id)
301         } else {
302             visit::walk_pat_field(self, fp)
303         }
304     }
305
306     fn visit_param(&mut self, p: &'a Param) {
307         if p.is_placeholder {
308             self.visit_macro_invoc(p.id)
309         } else {
310             self.with_impl_trait(ImplTraitContext::Universal(self.parent_def), |this| {
311                 visit::walk_param(this, p)
312             })
313         }
314     }
315
316     // This method is called only when we are visiting an individual field
317     // after expanding an attribute on it.
318     fn visit_field_def(&mut self, field: &'a FieldDef) {
319         self.collect_field(field, None);
320     }
321
322     fn visit_crate(&mut self, krate: &'a Crate) {
323         if krate.is_placeholder {
324             self.visit_macro_invoc(krate.id)
325         } else {
326             visit::walk_crate(self, krate)
327         }
328     }
329 }