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.
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.
11 use hir::map::definitions::*;
12 use hir::def_id::{CRATE_DEF_INDEX, DefIndex, DefIndexAddressSpace};
13 use session::CrateDisambiguator;
16 use syntax::ext::hygiene::Mark;
18 use syntax::symbol::keywords;
19 use syntax::symbol::Symbol;
20 use syntax::parse::token::{self, Token};
23 use hir::map::{ITEM_LIKE_SPACE, REGULAR_SPACE};
25 /// Creates def ids for nodes in the AST.
26 pub struct DefCollector<'a> {
27 definitions: &'a mut Definitions,
28 parent_def: Option<DefIndex>,
30 pub visit_macro_invoc: Option<&'a mut dyn FnMut(MacroInvocationData)>,
33 pub struct MacroInvocationData {
35 pub def_index: DefIndex,
38 impl<'a> DefCollector<'a> {
39 pub fn new(definitions: &'a mut Definitions, expansion: Mark) -> Self {
44 visit_macro_invoc: None,
48 pub fn collect_root(&mut self,
50 crate_disambiguator: CrateDisambiguator) {
51 let root = self.definitions.create_root_def(crate_name,
53 assert_eq!(root, CRATE_DEF_INDEX);
54 self.parent_def = Some(root);
57 fn create_def(&mut self,
60 address_space: DefIndexAddressSpace,
63 let parent_def = self.parent_def.unwrap();
64 debug!("create_def(node_id={:?}, data={:?}, parent_def={:?})", node_id, data, parent_def);
66 .create_def_with_parent(parent_def, node_id, data, address_space, self.expansion, span)
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);
73 self.parent_def = parent;
82 generics: &'a Generics,
86 let (closure_id, return_impl_trait_id) = match header.asyncness {
90 } => (closure_id, return_impl_trait_id),
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);
101 visit::walk_generics(this, generics);
102 visit::walk_fn_decl(this, decl);
104 let closure_def = this.create_def(closure_id,
105 DefPathData::ClosureExpr,
108 this.with_parent(closure_def, |this| {
109 visit::walk_block(this, body);
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(),
124 impl<'a> visit::Visitor<'a> for DefCollector<'a> {
125 fn visit_item(&mut self, i: &'a Item) {
126 debug!("visit_item: {:?}", i);
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);
142 ref header @ FnHeader { asyncness: IsAsync::Async { .. }, .. },
146 return self.visit_async_fn(
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);
166 let def = self.create_def(i.id, def_data, ITEM_LIKE_SPACE, i.span);
168 self.with_parent(def, |this| {
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,
181 visit::walk_item(this, i);
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);
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);
195 let def = self.create_def(foreign_item.id,
196 DefPathData::ValueNs(foreign_item.ident.as_interned_str()),
200 self.with_parent(def, |this| {
201 visit::walk_foreign_item(this, foreign_item);
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()),
210 self.with_parent(def, |this| visit::walk_variant(this, v, g, item_id));
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()),
222 self.with_parent(def, |this| this.visit_struct_field(field));
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),
232 self.create_def(param.id, def_path_data, REGULAR_SPACE, param.ident.span);
234 visit::walk_generic_param(self, param);
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())
244 TraitItemKind::Macro(..) => return self.visit_macro_invoc(ti.id),
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));
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 { .. }, .. },
257 return self.visit_async_fn(
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())
273 ImplItemKind::Macro(..) => return self.visit_macro_invoc(ii.id),
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));
280 fn visit_pat(&mut self, pat: &'a Pat) {
282 PatKind::Mac(..) => return self.visit_macro_invoc(pat.id),
283 _ => visit::walk_pat(self, pat),
287 fn visit_anon_const(&mut self, constant: &'a AnonConst) {
288 let def = self.create_def(constant.id,
289 DefPathData::AnonConst,
291 constant.value.span);
292 self.with_parent(def, |this| visit::walk_anon_const(this, constant));
295 fn visit_expr(&mut self, expr: &'a Expr) {
296 let parent_def = self.parent_def;
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,
305 self.parent_def = Some(closure_def);
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,
314 self.parent_def = Some(async_def);
317 ExprKind::Async(_, async_id, _) => {
318 let async_def = self.create_def(async_id,
319 DefPathData::ClosureExpr,
322 self.parent_def = Some(async_def);
327 visit::walk_expr(self, expr);
328 self.parent_def = parent_def;
331 fn visit_ty(&mut self, ty: &'a Ty) {
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);
339 visit::walk_ty(self, ty);
342 fn visit_stmt(&mut self, stmt: &'a Stmt) {
344 StmtKind::Mac(..) => self.visit_macro_invoc(stmt.id),
345 _ => visit::walk_stmt(self, stmt),
349 fn visit_token(&mut self, t: Token) {
350 if let Token::Interpolated(nt) = t {
352 token::NtExpr(ref expr) => {
353 if let ExprKind::Mac(..) = expr.node {
354 self.visit_macro_invoc(expr.id);