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;
79 async_node_id: NodeId,
82 visit_fn: impl FnOnce(&mut DefCollector<'a>)
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,
93 this.with_parent(closure_def, visit_fn)
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(),
107 impl<'a> visit::Visitor<'a> for DefCollector<'a> {
108 fn visit_item(&mut self, i: &'a Item) {
109 debug!("visit_item: {:?}", i);
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);
123 ItemKind::Fn(_, FnHeader { asyncness: IsAsync::Async(async_node_id), .. }, ..) => {
124 return self.visit_async_fn(
129 |this| visit::walk_item(this, i)
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);
142 let def = self.create_def(i.id, def_data, ITEM_LIKE_SPACE, i.span);
144 self.with_parent(def, |this| {
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,
157 visit::walk_item(this, i);
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);
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);
171 let def = self.create_def(foreign_item.id,
172 DefPathData::ValueNs(foreign_item.ident.name.as_interned_str()),
176 self.with_parent(def, |this| {
177 visit::walk_foreign_item(this, foreign_item);
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()),
187 self.with_parent(def, |this| visit::walk_variant(this, v, g, item_id));
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()),
199 self.with_parent(def, |this| this.visit_struct_field(field));
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),
209 self.create_def(param.id, def_path_data, REGULAR_SPACE, param.ident.span);
211 visit::walk_generic_param(self, param);
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())
221 TraitItemKind::Macro(..) => return self.visit_macro_invoc(ti.id),
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));
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), .. }, ..
233 return self.visit_async_fn(
238 |this| visit::walk_impl_item(this, ii)
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),
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));
251 fn visit_pat(&mut self, pat: &'a Pat) {
253 PatKind::Mac(..) => return self.visit_macro_invoc(pat.id),
254 _ => visit::walk_pat(self, pat),
258 fn visit_anon_const(&mut self, constant: &'a AnonConst) {
259 let def = self.create_def(constant.id,
260 DefPathData::AnonConst,
262 constant.value.span);
263 self.with_parent(def, |this| visit::walk_anon_const(this, constant));
266 fn visit_expr(&mut self, expr: &'a Expr) {
267 let parent_def = self.parent_def;
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,
276 self.parent_def = Some(closure_def);
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,
285 self.parent_def = Some(async_def);
288 ExprKind::Async(_, async_id, _) => {
289 let async_def = self.create_def(async_id,
290 DefPathData::ClosureExpr,
293 self.parent_def = Some(async_def);
298 visit::walk_expr(self, expr);
299 self.parent_def = parent_def;
302 fn visit_ty(&mut self, ty: &'a Ty) {
304 TyKind::Mac(..) => return self.visit_macro_invoc(ty.id),
307 visit::walk_ty(self, ty);
310 fn visit_stmt(&mut self, stmt: &'a Stmt) {
312 StmtKind::Mac(..) => self.visit_macro_invoc(stmt.id),
313 _ => visit::walk_stmt(self, stmt),
317 fn visit_token(&mut self, t: Token) {
318 if let Token::Interpolated(nt) = t {
320 token::NtExpr(ref expr) => {
321 if let ExprKind::Mac(..) = expr.node {
322 self.visit_macro_invoc(expr.id);