]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/map/def_collector.rs
0fa0d1ea00c95a953a5a2a528aaf2e3ea7d04664
[rust.git] / src / librustc / hir / map / def_collector.rs
1 use crate::hir::map::definitions::*;
2 use crate::hir::def_id::{CRATE_DEF_INDEX, DefIndex};
3 use crate::session::CrateDisambiguator;
4
5 use syntax::ast::*;
6 use syntax::ext::hygiene::Mark;
7 use syntax::visit;
8 use syntax::symbol::{kw, sym};
9 use syntax::parse::token::{self, Token};
10 use syntax_pos::Span;
11
12 /// Creates `DefId`s for nodes in the AST.
13 pub struct DefCollector<'a> {
14     definitions: &'a mut Definitions,
15     parent_def: Option<DefIndex>,
16     expansion: Mark,
17     pub visit_macro_invoc: Option<&'a mut dyn FnMut(MacroInvocationData)>,
18 }
19
20 pub struct MacroInvocationData {
21     pub mark: Mark,
22     pub def_index: DefIndex,
23 }
24
25 impl<'a> DefCollector<'a> {
26     pub fn new(definitions: &'a mut Definitions, expansion: Mark) -> Self {
27         DefCollector {
28             definitions,
29             expansion,
30             parent_def: None,
31             visit_macro_invoc: None,
32         }
33     }
34
35     pub fn collect_root(&mut self,
36                         crate_name: &str,
37                         crate_disambiguator: CrateDisambiguator) {
38         let root = self.definitions.create_root_def(crate_name,
39                                                     crate_disambiguator);
40         assert_eq!(root, CRATE_DEF_INDEX);
41         self.parent_def = Some(root);
42     }
43
44     fn create_def(&mut self,
45                   node_id: NodeId,
46                   data: DefPathData,
47                   span: Span)
48                   -> DefIndex {
49         let parent_def = self.parent_def.unwrap();
50         debug!("create_def(node_id={:?}, data={:?}, parent_def={:?})", node_id, data, parent_def);
51         self.definitions
52             .create_def_with_parent(parent_def, node_id, data, self.expansion, span)
53     }
54
55     pub fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_def: DefIndex, f: F) {
56         let parent = self.parent_def;
57         self.parent_def = Some(parent_def);
58         f(self);
59         self.parent_def = parent;
60     }
61
62     fn visit_async_fn(
63         &mut self,
64         id: NodeId,
65         name: Name,
66         span: Span,
67         header: &FnHeader,
68         generics: &'a Generics,
69         decl: &'a FnDecl,
70         body: &'a Block,
71     ) {
72         let (closure_id, return_impl_trait_id) = match header.asyncness.node {
73             IsAsync::Async {
74                 closure_id,
75                 return_impl_trait_id,
76             } => (closure_id, return_impl_trait_id),
77             _ => unreachable!(),
78         };
79
80         // For async functions, we need to create their inner defs inside of a
81         // closure to match their desugared representation.
82         let fn_def_data = DefPathData::ValueNs(name.as_interned_str());
83         let fn_def = self.create_def(id, fn_def_data, span);
84         return self.with_parent(fn_def, |this| {
85             this.create_def(return_impl_trait_id, DefPathData::ImplTrait, span);
86
87             visit::walk_generics(this, generics);
88             visit::walk_fn_decl(this, decl);
89
90             let closure_def = this.create_def(
91                 closure_id, DefPathData::ClosureExpr, span,
92             );
93             this.with_parent(closure_def, |this| {
94                 visit::walk_block(this, body);
95             })
96         })
97     }
98
99     fn visit_macro_invoc(&mut self, id: NodeId) {
100         if let Some(ref mut visit) = self.visit_macro_invoc {
101             visit(MacroInvocationData {
102                 mark: id.placeholder_to_mark(),
103                 def_index: self.parent_def.unwrap(),
104             })
105         }
106     }
107 }
108
109 impl<'a> visit::Visitor<'a> for DefCollector<'a> {
110     fn visit_item(&mut self, i: &'a Item) {
111         debug!("visit_item: {:?}", i);
112
113         // Pick the def data. This need not be unique, but the more
114         // information we encapsulate into, the better
115         let def_data = match i.node {
116             ItemKind::Impl(..) => DefPathData::Impl,
117             ItemKind::Mod(..) if i.ident.name == kw::Invalid => {
118                 return visit::walk_item(self, i);
119             }
120             ItemKind::Mod(..) | ItemKind::Trait(..) | ItemKind::TraitAlias(..) |
121             ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) |
122             ItemKind::Existential(..) | ItemKind::ExternCrate(..) | ItemKind::ForeignMod(..) |
123             ItemKind::Ty(..) => DefPathData::TypeNs(i.ident.as_interned_str()),
124             ItemKind::Fn(
125                 ref decl,
126                 ref header,
127                 ref generics,
128                 ref body,
129             ) if header.asyncness.node.is_async() => {
130                 return self.visit_async_fn(
131                     i.id,
132                     i.ident.name,
133                     i.span,
134                     header,
135                     generics,
136                     decl,
137                     body,
138                 )
139             }
140             ItemKind::Static(..) | ItemKind::Const(..) | ItemKind::Fn(..) =>
141                 DefPathData::ValueNs(i.ident.as_interned_str()),
142             ItemKind::MacroDef(..) => DefPathData::MacroNs(i.ident.as_interned_str()),
143             ItemKind::Mac(..) => return self.visit_macro_invoc(i.id),
144             ItemKind::GlobalAsm(..) => DefPathData::Misc,
145             ItemKind::Use(..) => {
146                 return visit::walk_item(self, i);
147             }
148         };
149         let def = self.create_def(i.id, def_data, i.span);
150
151         self.with_parent(def, |this| {
152             match i.node {
153                 ItemKind::Struct(ref struct_def, _) | ItemKind::Union(ref struct_def, _) => {
154                     // If this is a unit or tuple-like struct, register the constructor.
155                     if let Some(ctor_hir_id) = struct_def.ctor_id() {
156                         this.create_def(ctor_hir_id, DefPathData::Ctor, i.span);
157                     }
158                 }
159                 _ => {}
160             }
161             visit::walk_item(this, i);
162         });
163     }
164
165     fn visit_use_tree(&mut self, use_tree: &'a UseTree, id: NodeId, _nested: bool) {
166         self.create_def(id, DefPathData::Misc, use_tree.span);
167         visit::walk_use_tree(self, use_tree, id);
168     }
169
170     fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
171         if let ForeignItemKind::Macro(_) = foreign_item.node {
172             return self.visit_macro_invoc(foreign_item.id);
173         }
174
175         let def = self.create_def(foreign_item.id,
176                                   DefPathData::ValueNs(foreign_item.ident.as_interned_str()),
177                                   foreign_item.span);
178
179         self.with_parent(def, |this| {
180             visit::walk_foreign_item(this, foreign_item);
181         });
182     }
183
184     fn visit_variant(&mut self, v: &'a Variant, g: &'a Generics, item_id: NodeId) {
185         let def = self.create_def(v.node.id,
186                                   DefPathData::TypeNs(v.node.ident.as_interned_str()),
187                                   v.span);
188         self.with_parent(def, |this| {
189             if let Some(ctor_hir_id) = v.node.data.ctor_id() {
190                 this.create_def(ctor_hir_id, DefPathData::Ctor, v.span);
191             }
192             visit::walk_variant(this, v, g, item_id)
193         });
194     }
195
196     fn visit_variant_data(&mut self, data: &'a VariantData, _: Ident,
197                           _: &'a Generics, _: NodeId, _: Span) {
198         for (index, field) in data.fields().iter().enumerate() {
199             let name = field.ident.map(|ident| ident.name)
200                 .unwrap_or_else(|| sym::integer(index));
201             let def = self.create_def(field.id,
202                                       DefPathData::ValueNs(name.as_interned_str()),
203                                       field.span);
204             self.with_parent(def, |this| this.visit_struct_field(field));
205         }
206     }
207
208     fn visit_generic_param(&mut self, param: &'a GenericParam) {
209         let name = param.ident.as_interned_str();
210         let def_path_data = match param.kind {
211             GenericParamKind::Lifetime { .. } => DefPathData::LifetimeNs(name),
212             GenericParamKind::Type { .. } => DefPathData::TypeNs(name),
213             GenericParamKind::Const { .. } => DefPathData::ValueNs(name),
214         };
215         self.create_def(param.id, def_path_data, param.ident.span);
216
217         visit::walk_generic_param(self, param);
218     }
219
220     fn visit_trait_item(&mut self, ti: &'a TraitItem) {
221         let def_data = match ti.node {
222             TraitItemKind::Method(..) | TraitItemKind::Const(..) =>
223                 DefPathData::ValueNs(ti.ident.as_interned_str()),
224             TraitItemKind::Type(..) => {
225                 DefPathData::TypeNs(ti.ident.as_interned_str())
226             },
227             TraitItemKind::Macro(..) => return self.visit_macro_invoc(ti.id),
228         };
229
230         let def = self.create_def(ti.id, def_data, ti.span);
231         self.with_parent(def, |this| visit::walk_trait_item(this, ti));
232     }
233
234     fn visit_impl_item(&mut self, ii: &'a ImplItem) {
235         let def_data = match ii.node {
236             ImplItemKind::Method(MethodSig {
237                 ref header,
238                 ref decl,
239             }, ref body) if header.asyncness.node.is_async() => {
240                 return self.visit_async_fn(
241                     ii.id,
242                     ii.ident.name,
243                     ii.span,
244                     header,
245                     &ii.generics,
246                     decl,
247                     body,
248                 )
249             }
250             ImplItemKind::Method(..) | ImplItemKind::Const(..) =>
251                 DefPathData::ValueNs(ii.ident.as_interned_str()),
252             ImplItemKind::Type(..) |
253             ImplItemKind::Existential(..) => {
254                 DefPathData::TypeNs(ii.ident.as_interned_str())
255             },
256             ImplItemKind::Macro(..) => return self.visit_macro_invoc(ii.id),
257         };
258
259         let def = self.create_def(ii.id, def_data, ii.span);
260         self.with_parent(def, |this| visit::walk_impl_item(this, ii));
261     }
262
263     fn visit_pat(&mut self, pat: &'a Pat) {
264         match pat.node {
265             PatKind::Mac(..) => return self.visit_macro_invoc(pat.id),
266             _ => visit::walk_pat(self, pat),
267         }
268     }
269
270     fn visit_anon_const(&mut self, constant: &'a AnonConst) {
271         let def = self.create_def(constant.id,
272                                   DefPathData::AnonConst,
273                                   constant.value.span);
274         self.with_parent(def, |this| visit::walk_anon_const(this, constant));
275     }
276
277     fn visit_expr(&mut self, expr: &'a Expr) {
278         let parent_def = self.parent_def;
279
280         match expr.node {
281             ExprKind::Mac(..) => return self.visit_macro_invoc(expr.id),
282             ExprKind::Closure(_, asyncness, ..) => {
283                 let closure_def = self.create_def(expr.id,
284                                           DefPathData::ClosureExpr,
285                                           expr.span);
286                 self.parent_def = Some(closure_def);
287
288                 // Async closures desugar to closures inside of closures, so
289                 // we must create two defs.
290                 if let IsAsync::Async { closure_id, .. } = asyncness {
291                     let async_def = self.create_def(closure_id,
292                                                     DefPathData::ClosureExpr,
293                                                     expr.span);
294                     self.parent_def = Some(async_def);
295                 }
296             }
297             ExprKind::Async(_, async_id, _) => {
298                 let async_def = self.create_def(async_id,
299                                                 DefPathData::ClosureExpr,
300                                                 expr.span);
301                 self.parent_def = Some(async_def);
302             }
303             _ => {}
304         };
305
306         visit::walk_expr(self, expr);
307         self.parent_def = parent_def;
308     }
309
310     fn visit_ty(&mut self, ty: &'a Ty) {
311         match ty.node {
312             TyKind::Mac(..) => return self.visit_macro_invoc(ty.id),
313             TyKind::ImplTrait(node_id, _) => {
314                 self.create_def(node_id, DefPathData::ImplTrait, ty.span);
315             }
316             _ => {}
317         }
318         visit::walk_ty(self, ty);
319     }
320
321     fn visit_stmt(&mut self, stmt: &'a Stmt) {
322         match stmt.node {
323             StmtKind::Mac(..) => self.visit_macro_invoc(stmt.id),
324             _ => visit::walk_stmt(self, stmt),
325         }
326     }
327
328     fn visit_token(&mut self, t: Token) {
329         if let token::Interpolated(nt) = t {
330             if let token::NtExpr(ref expr) = *nt {
331                 if let ExprKind::Mac(..) = expr.node {
332                     self.visit_macro_invoc(expr.id);
333                 }
334             }
335         }
336     }
337 }