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