]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/map/def_collector.rs
Switch wasm math symbols to their original names
[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         name: Name,
80         span: Span,
81         header: &FnHeader,
82         generics: &'a Generics,
83         decl: &'a FnDecl,
84         body: &'a Block,
85     ) {
86         let (closure_id, return_impl_trait_id) = match header.asyncness {
87             IsAsync::Async {
88                 closure_id,
89                 return_impl_trait_id,
90             } => (closure_id, return_impl_trait_id),
91             _ => unreachable!(),
92         };
93
94         // For async functions, we need to create their inner defs inside of a
95         // closure to match their desugared representation.
96         let fn_def_data = DefPathData::ValueNs(name.as_interned_str());
97         let fn_def = self.create_def(id, fn_def_data, ITEM_LIKE_SPACE, span);
98         return self.with_parent(fn_def, |this| {
99             this.create_def(return_impl_trait_id, DefPathData::ImplTrait, REGULAR_SPACE, span);
100
101             visit::walk_generics(this, generics);
102             visit::walk_fn_decl(this, decl);
103
104             let closure_def = this.create_def(closure_id,
105                                   DefPathData::ClosureExpr,
106                                   REGULAR_SPACE,
107                                   span);
108             this.with_parent(closure_def, |this| {
109                 visit::walk_block(this, body);
110             })
111         })
112     }
113
114     fn visit_macro_invoc(&mut self, id: NodeId) {
115         if let Some(ref mut visit) = self.visit_macro_invoc {
116             visit(MacroInvocationData {
117                 mark: id.placeholder_to_mark(),
118                 def_index: self.parent_def.unwrap(),
119             })
120         }
121     }
122 }
123
124 impl<'a> visit::Visitor<'a> for DefCollector<'a> {
125     fn visit_item(&mut self, i: &'a Item) {
126         debug!("visit_item: {:?}", i);
127
128         // Pick the def data. This need not be unique, but the more
129         // information we encapsulate into, the better
130         let def_data = match i.node {
131             ItemKind::Impl(..) => DefPathData::Impl,
132             ItemKind::Trait(..) => DefPathData::Trait(i.ident.as_interned_str()),
133             ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) |
134             ItemKind::TraitAlias(..) | ItemKind::Existential(..) |
135             ItemKind::ExternCrate(..) | ItemKind::ForeignMod(..) | ItemKind::Ty(..) =>
136                 DefPathData::TypeNs(i.ident.as_interned_str()),
137             ItemKind::Mod(..) if i.ident == keywords::Invalid.ident() => {
138                 return visit::walk_item(self, i);
139             }
140             ItemKind::Fn(
141                 ref decl,
142                 ref header @ FnHeader { asyncness: IsAsync::Async { .. }, .. },
143                 ref generics,
144                 ref body,
145             ) => {
146                 return self.visit_async_fn(
147                     i.id,
148                     i.ident.name,
149                     i.span,
150                     header,
151                     generics,
152                     decl,
153                     body,
154                 )
155             }
156             ItemKind::Mod(..) => DefPathData::Module(i.ident.as_interned_str()),
157             ItemKind::Static(..) | ItemKind::Const(..) | ItemKind::Fn(..) =>
158                 DefPathData::ValueNs(i.ident.as_interned_str()),
159             ItemKind::MacroDef(..) => DefPathData::MacroDef(i.ident.as_interned_str()),
160             ItemKind::Mac(..) => return self.visit_macro_invoc(i.id),
161             ItemKind::GlobalAsm(..) => DefPathData::Misc,
162             ItemKind::Use(..) => {
163                 return visit::walk_item(self, i);
164             }
165         };
166         let def = self.create_def(i.id, def_data, ITEM_LIKE_SPACE, i.span);
167
168         self.with_parent(def, |this| {
169             match i.node {
170                 ItemKind::Struct(ref struct_def, _) | ItemKind::Union(ref struct_def, _) => {
171                     // If this is a tuple-like struct, register the constructor.
172                     if !struct_def.is_struct() {
173                         this.create_def(struct_def.id(),
174                                         DefPathData::StructCtor,
175                                         REGULAR_SPACE,
176                                         i.span);
177                     }
178                 }
179                 _ => {}
180             }
181             visit::walk_item(this, i);
182         });
183     }
184
185     fn visit_use_tree(&mut self, use_tree: &'a UseTree, id: NodeId, _nested: bool) {
186         self.create_def(id, DefPathData::Misc, ITEM_LIKE_SPACE, use_tree.span);
187         visit::walk_use_tree(self, use_tree, id);
188     }
189
190     fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) {
191         if let ForeignItemKind::Macro(_) = foreign_item.node {
192             return self.visit_macro_invoc(foreign_item.id);
193         }
194
195         let def = self.create_def(foreign_item.id,
196                                   DefPathData::ValueNs(foreign_item.ident.as_interned_str()),
197                                   REGULAR_SPACE,
198                                   foreign_item.span);
199
200         self.with_parent(def, |this| {
201             visit::walk_foreign_item(this, foreign_item);
202         });
203     }
204
205     fn visit_variant(&mut self, v: &'a Variant, g: &'a Generics, item_id: NodeId) {
206         let def = self.create_def(v.node.data.id(),
207                                   DefPathData::EnumVariant(v.node.ident.as_interned_str()),
208                                   REGULAR_SPACE,
209                                   v.span);
210         self.with_parent(def, |this| visit::walk_variant(this, v, g, item_id));
211     }
212
213     fn visit_variant_data(&mut self, data: &'a VariantData, _: Ident,
214                           _: &'a Generics, _: NodeId, _: Span) {
215         for (index, field) in data.fields().iter().enumerate() {
216             let name = field.ident.map(|ident| ident.name)
217                 .unwrap_or_else(|| Symbol::intern(&index.to_string()));
218             let def = self.create_def(field.id,
219                                       DefPathData::Field(name.as_interned_str()),
220                                       REGULAR_SPACE,
221                                       field.span);
222             self.with_parent(def, |this| this.visit_struct_field(field));
223         }
224     }
225
226     fn visit_generic_param(&mut self, param: &'a GenericParam) {
227         let name = param.ident.as_interned_str();
228         let def_path_data = match param.kind {
229             GenericParamKind::Lifetime { .. } => DefPathData::LifetimeParam(name),
230             GenericParamKind::Type { .. } => DefPathData::TypeParam(name),
231         };
232         self.create_def(param.id, def_path_data, REGULAR_SPACE, param.ident.span);
233
234         visit::walk_generic_param(self, param);
235     }
236
237     fn visit_trait_item(&mut self, ti: &'a TraitItem) {
238         let def_data = match ti.node {
239             TraitItemKind::Method(..) | TraitItemKind::Const(..) =>
240                 DefPathData::ValueNs(ti.ident.as_interned_str()),
241             TraitItemKind::Type(..) => {
242                 DefPathData::AssocTypeInTrait(ti.ident.as_interned_str())
243             },
244             TraitItemKind::Macro(..) => return self.visit_macro_invoc(ti.id),
245         };
246
247         let def = self.create_def(ti.id, def_data, ITEM_LIKE_SPACE, ti.span);
248         self.with_parent(def, |this| visit::walk_trait_item(this, ti));
249     }
250
251     fn visit_impl_item(&mut self, ii: &'a ImplItem) {
252         let def_data = match ii.node {
253             ImplItemKind::Method(MethodSig {
254                 header: ref header @ FnHeader { asyncness: IsAsync::Async { .. }, .. },
255                 ref decl,
256             }, ref body) => {
257                 return self.visit_async_fn(
258                     ii.id,
259                     ii.ident.name,
260                     ii.span,
261                     header,
262                     &ii.generics,
263                     decl,
264                     body,
265                 )
266             }
267             ImplItemKind::Method(..) | ImplItemKind::Const(..) =>
268                 DefPathData::ValueNs(ii.ident.as_interned_str()),
269             ImplItemKind::Type(..) => DefPathData::AssocTypeInImpl(ii.ident.as_interned_str()),
270             ImplItemKind::Existential(..) => {
271                 DefPathData::AssocExistentialInImpl(ii.ident.as_interned_str())
272             },
273             ImplItemKind::Macro(..) => return self.visit_macro_invoc(ii.id),
274         };
275
276         let def = self.create_def(ii.id, def_data, ITEM_LIKE_SPACE, ii.span);
277         self.with_parent(def, |this| visit::walk_impl_item(this, ii));
278     }
279
280     fn visit_pat(&mut self, pat: &'a Pat) {
281         match pat.node {
282             PatKind::Mac(..) => return self.visit_macro_invoc(pat.id),
283             _ => visit::walk_pat(self, pat),
284         }
285     }
286
287     fn visit_anon_const(&mut self, constant: &'a AnonConst) {
288         let def = self.create_def(constant.id,
289                                   DefPathData::AnonConst,
290                                   REGULAR_SPACE,
291                                   constant.value.span);
292         self.with_parent(def, |this| visit::walk_anon_const(this, constant));
293     }
294
295     fn visit_expr(&mut self, expr: &'a Expr) {
296         let parent_def = self.parent_def;
297
298         match expr.node {
299             ExprKind::Mac(..) => return self.visit_macro_invoc(expr.id),
300             ExprKind::Closure(_, asyncness, ..) => {
301                 let closure_def = self.create_def(expr.id,
302                                           DefPathData::ClosureExpr,
303                                           REGULAR_SPACE,
304                                           expr.span);
305                 self.parent_def = Some(closure_def);
306
307                 // Async closures desugar to closures inside of closures, so
308                 // we must create two defs.
309                 if let IsAsync::Async { closure_id, .. } = asyncness {
310                     let async_def = self.create_def(closure_id,
311                                                     DefPathData::ClosureExpr,
312                                                     REGULAR_SPACE,
313                                                     expr.span);
314                     self.parent_def = Some(async_def);
315                 }
316             }
317             ExprKind::Async(_, async_id, _) => {
318                 let async_def = self.create_def(async_id,
319                                                 DefPathData::ClosureExpr,
320                                                 REGULAR_SPACE,
321                                                 expr.span);
322                 self.parent_def = Some(async_def);
323             }
324             _ => {}
325         };
326
327         visit::walk_expr(self, expr);
328         self.parent_def = parent_def;
329     }
330
331     fn visit_ty(&mut self, ty: &'a Ty) {
332         match ty.node {
333             TyKind::Mac(..) => return self.visit_macro_invoc(ty.id),
334             TyKind::ImplTrait(node_id, _) => {
335                 self.create_def(node_id, DefPathData::ImplTrait, REGULAR_SPACE, ty.span);
336             }
337             _ => {}
338         }
339         visit::walk_ty(self, ty);
340     }
341
342     fn visit_stmt(&mut self, stmt: &'a Stmt) {
343         match stmt.node {
344             StmtKind::Mac(..) => self.visit_macro_invoc(stmt.id),
345             _ => visit::walk_stmt(self, stmt),
346         }
347     }
348
349     fn visit_token(&mut self, t: Token) {
350         if let Token::Interpolated(nt) = t {
351             match nt.0 {
352                 token::NtExpr(ref expr) => {
353                     if let ExprKind::Mac(..) = expr.node {
354                         self.visit_macro_invoc(expr.id);
355                     }
356                 }
357                 _ => {}
358             }
359         }
360     }
361 }