1 // Copyright 2012-2015 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 self::collector::NodeCollector;
12 pub use self::def_collector::{DefCollector, MacroInvocationData};
13 pub use self::definitions::{Definitions, DefKey, DefPath, DefPathData,
14 DisambiguatedDefPathData, DefPathHash};
16 use dep_graph::{DepGraph, DepNode, DepKind, DepNodeIndex};
18 use hir::def_id::{CRATE_DEF_INDEX, DefId, LocalDefId, DefIndexAddressSpace};
20 use middle::cstore::CrateStore;
22 use rustc_target::spec::abi::Abi;
23 use rustc_data_structures::svh::Svh;
24 use syntax::ast::{self, Name, NodeId, CRATE_NODE_ID};
25 use syntax::source_map::Spanned;
26 use syntax::ext::base::MacroKind;
27 use syntax_pos::{Span, DUMMY_SP};
30 use hir::print::Nested;
31 use util::nodemap::FxHashMap;
34 use std::result::Result::Err;
44 pub const ITEM_LIKE_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::Low;
45 pub const REGULAR_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::High;
47 #[derive(Copy, Clone, Debug)]
48 pub enum NodeKind<'hir> {
50 ForeignItem(&'hir ForeignItem),
51 TraitItem(&'hir TraitItem),
52 ImplItem(&'hir ImplItem),
53 Variant(&'hir Variant),
54 Field(&'hir StructField),
55 AnonConst(&'hir AnonConst),
59 TraitRef(&'hir TraitRef),
64 MacroDef(&'hir MacroDef),
66 /// StructCtor represents a tuple struct.
67 StructCtor(&'hir VariantData),
69 Lifetime(&'hir Lifetime),
70 GenericParam(&'hir GenericParam),
71 Visibility(&'hir Visibility),
74 /// Represents an entry and its parent NodeID.
75 /// The odd layout is to bring down the total size.
76 #[derive(Copy, Debug)]
77 pub enum EntryKind<'hir> {
78 /// Placeholder for holes in the map.
81 /// All the node types, with a parent ID.
82 Item(NodeId, DepNodeIndex, &'hir Item),
83 ForeignItem(NodeId, DepNodeIndex, &'hir ForeignItem),
84 TraitItem(NodeId, DepNodeIndex, &'hir TraitItem),
85 ImplItem(NodeId, DepNodeIndex, &'hir ImplItem),
86 Variant(NodeId, DepNodeIndex, &'hir Variant),
87 Field(NodeId, DepNodeIndex, &'hir StructField),
88 AnonConst(NodeId, DepNodeIndex, &'hir AnonConst),
89 Expr(NodeId, DepNodeIndex, &'hir Expr),
90 Stmt(NodeId, DepNodeIndex, &'hir Stmt),
91 Ty(NodeId, DepNodeIndex, &'hir Ty),
92 TraitRef(NodeId, DepNodeIndex, &'hir TraitRef),
93 Binding(NodeId, DepNodeIndex, &'hir Pat),
94 Pat(NodeId, DepNodeIndex, &'hir Pat),
95 Block(NodeId, DepNodeIndex, &'hir Block),
96 StructCtor(NodeId, DepNodeIndex, &'hir VariantData),
97 Lifetime(NodeId, DepNodeIndex, &'hir Lifetime),
98 GenericParam(NodeId, DepNodeIndex, &'hir GenericParam),
99 Visibility(NodeId, DepNodeIndex, &'hir Visibility),
100 Local(NodeId, DepNodeIndex, &'hir Local),
101 MacroDef(DepNodeIndex, &'hir MacroDef),
103 /// Roots for node trees. The DepNodeIndex is the dependency node of the
104 /// crate's root module.
105 RootCrate(DepNodeIndex),
108 impl<'hir> Clone for EntryKind<'hir> {
109 fn clone(&self) -> EntryKind<'hir> {
114 impl<'hir> EntryKind<'hir> {
115 fn parent_node(self) -> Option<NodeId> {
117 EntryKind::Item(id, _, _) => id,
118 EntryKind::ForeignItem(id, _, _) => id,
119 EntryKind::TraitItem(id, _, _) => id,
120 EntryKind::ImplItem(id, _, _) => id,
121 EntryKind::Variant(id, _, _) => id,
122 EntryKind::Field(id, _, _) => id,
123 EntryKind::AnonConst(id, _, _) => id,
124 EntryKind::Expr(id, _, _) => id,
125 EntryKind::Stmt(id, _, _) => id,
126 EntryKind::Ty(id, _, _) => id,
127 EntryKind::TraitRef(id, _, _) => id,
128 EntryKind::Binding(id, _, _) => id,
129 EntryKind::Pat(id, _, _) => id,
130 EntryKind::Block(id, _, _) => id,
131 EntryKind::StructCtor(id, _, _) => id,
132 EntryKind::Lifetime(id, _, _) => id,
133 EntryKind::GenericParam(id, _, _) => id,
134 EntryKind::Visibility(id, _, _) => id,
135 EntryKind::Local(id, _, _) => id,
137 EntryKind::NotPresent |
138 EntryKind::MacroDef(..) |
139 EntryKind::RootCrate(_) => return None,
143 fn to_node(self) -> Option<NodeKind<'hir>> {
145 EntryKind::Item(_, _, n) => NodeKind::Item(n),
146 EntryKind::ForeignItem(_, _, n) => NodeKind::ForeignItem(n),
147 EntryKind::TraitItem(_, _, n) => NodeKind::TraitItem(n),
148 EntryKind::ImplItem(_, _, n) => NodeKind::ImplItem(n),
149 EntryKind::Variant(_, _, n) => NodeKind::Variant(n),
150 EntryKind::Field(_, _, n) => NodeKind::Field(n),
151 EntryKind::AnonConst(_, _, n) => NodeKind::AnonConst(n),
152 EntryKind::Expr(_, _, n) => NodeKind::Expr(n),
153 EntryKind::Stmt(_, _, n) => NodeKind::Stmt(n),
154 EntryKind::Ty(_, _, n) => NodeKind::Ty(n),
155 EntryKind::TraitRef(_, _, n) => NodeKind::TraitRef(n),
156 EntryKind::Binding(_, _, n) => NodeKind::Binding(n),
157 EntryKind::Pat(_, _, n) => NodeKind::Pat(n),
158 EntryKind::Block(_, _, n) => NodeKind::Block(n),
159 EntryKind::StructCtor(_, _, n) => NodeKind::StructCtor(n),
160 EntryKind::Lifetime(_, _, n) => NodeKind::Lifetime(n),
161 EntryKind::GenericParam(_, _, n) => NodeKind::GenericParam(n),
162 EntryKind::Visibility(_, _, n) => NodeKind::Visibility(n),
163 EntryKind::Local(_, _, n) => NodeKind::Local(n),
164 EntryKind::MacroDef(_, n) => NodeKind::MacroDef(n),
166 EntryKind::NotPresent |
167 EntryKind::RootCrate(_) => return None
171 fn fn_decl(&self) -> Option<&FnDecl> {
173 EntryKind::Item(_, _, ref item) => {
175 ItemKind::Fn(ref fn_decl, _, _, _) => Some(&fn_decl),
180 EntryKind::TraitItem(_, _, ref item) => {
182 TraitItemKind::Method(ref method_sig, _) => Some(&method_sig.decl),
187 EntryKind::ImplItem(_, _, ref item) => {
189 ImplItemKind::Method(ref method_sig, _) => Some(&method_sig.decl),
194 EntryKind::Expr(_, _, ref expr) => {
196 ExprKind::Closure(_, ref fn_decl, ..) => Some(&fn_decl),
205 fn associated_body(self) -> Option<BodyId> {
207 EntryKind::Item(_, _, item) => {
209 ItemKind::Const(_, body) |
210 ItemKind::Static(.., body) |
211 ItemKind::Fn(_, _, _, body) => Some(body),
216 EntryKind::TraitItem(_, _, item) => {
218 TraitItemKind::Const(_, Some(body)) |
219 TraitItemKind::Method(_, TraitMethod::Provided(body)) => Some(body),
224 EntryKind::ImplItem(_, _, item) => {
226 ImplItemKind::Const(_, body) |
227 ImplItemKind::Method(_, body) => Some(body),
232 EntryKind::AnonConst(_, _, constant) => Some(constant.body),
234 EntryKind::Expr(_, _, expr) => {
236 ExprKind::Closure(.., body, _, _) => Some(body),
245 fn is_body_owner(self, node_id: NodeId) -> bool {
246 match self.associated_body() {
247 Some(b) => b.node_id == node_id,
253 /// Stores a crate and any number of inlined items from other crates.
256 pub dep_graph: DepGraph,
260 pub fn new(krate: Crate, dep_graph: &DepGraph) -> Forest {
263 dep_graph: dep_graph.clone(),
267 pub fn krate<'hir>(&'hir self) -> &'hir Crate {
268 self.dep_graph.read(DepNode::new_no_params(DepKind::Krate));
273 /// Represents a mapping from NodeKind IDs to AST elements and their parent
276 pub struct Map<'hir> {
277 /// The backing storage for all the AST nodes.
278 pub forest: &'hir Forest,
280 /// Same as the dep_graph in forest, just available with one fewer
281 /// deref. This is a gratuitous micro-optimization.
282 pub dep_graph: DepGraph,
284 /// The SVH of the local crate.
287 /// NodeIds are sequential integers from 0, so we can be
288 /// super-compact by storing them in a vector. Not everything with
289 /// a NodeId is in the map, but empirically the occupancy is about
290 /// 75-80%, so there's not too much overhead (certainly less than
291 /// a hashmap, since they (at the time of writing) have a maximum
292 /// of 75% occupancy).
294 /// Also, indexing is pretty quick when you've got a vector and
295 /// plain old integers.
296 map: Vec<EntryKind<'hir>>,
298 definitions: &'hir Definitions,
300 /// The reverse mapping of `node_to_hir_id`.
301 hir_to_node_id: FxHashMap<HirId, NodeId>,
304 impl<'hir> Map<'hir> {
305 /// Registers a read in the dependency graph of the AST node with
306 /// the given `id`. This needs to be called each time a public
307 /// function returns the HIR for a node -- in other words, when it
308 /// "reveals" the content of a node to the caller (who might not
309 /// otherwise have had access to those contents, and hence needs a
310 /// read recorded). If the function just returns a DefId or
311 /// NodeId, no actual content was returned, so no read is needed.
312 pub fn read(&self, id: NodeId) {
313 let entry = self.map[id.as_usize()];
315 EntryKind::Item(_, dep_node_index, _) |
316 EntryKind::TraitItem(_, dep_node_index, _) |
317 EntryKind::ImplItem(_, dep_node_index, _) |
318 EntryKind::Variant(_, dep_node_index, _) |
319 EntryKind::ForeignItem(_, dep_node_index, _) |
320 EntryKind::Field(_, dep_node_index, _) |
321 EntryKind::Stmt(_, dep_node_index, _) |
322 EntryKind::Ty(_, dep_node_index, _) |
323 EntryKind::TraitRef(_, dep_node_index, _) |
324 EntryKind::Binding(_, dep_node_index, _) |
325 EntryKind::Pat(_, dep_node_index, _) |
326 EntryKind::Block(_, dep_node_index, _) |
327 EntryKind::StructCtor(_, dep_node_index, _) |
328 EntryKind::Lifetime(_, dep_node_index, _) |
329 EntryKind::GenericParam(_, dep_node_index, _) |
330 EntryKind::Visibility(_, dep_node_index, _) |
331 EntryKind::AnonConst(_, dep_node_index, _) |
332 EntryKind::Expr(_, dep_node_index, _) |
333 EntryKind::Local(_, dep_node_index, _) |
334 EntryKind::MacroDef(dep_node_index, _) |
335 EntryKind::RootCrate(dep_node_index) => {
336 self.dep_graph.read_index(dep_node_index);
338 EntryKind::NotPresent => {
339 bug!("called HirMap::read() with invalid NodeId")
345 pub fn definitions(&self) -> &'hir Definitions {
349 pub fn def_key(&self, def_id: DefId) -> DefKey {
350 assert!(def_id.is_local());
351 self.definitions.def_key(def_id.index)
354 pub fn def_path_from_id(&self, id: NodeId) -> Option<DefPath> {
355 self.opt_local_def_id(id).map(|def_id| {
356 self.def_path(def_id)
360 pub fn def_path(&self, def_id: DefId) -> DefPath {
361 assert!(def_id.is_local());
362 self.definitions.def_path(def_id.index)
366 pub fn local_def_id(&self, node: NodeId) -> DefId {
367 self.opt_local_def_id(node).unwrap_or_else(|| {
368 bug!("local_def_id: no entry for `{}`, which has a map of `{:?}`",
369 node, self.find_entry(node))
374 pub fn opt_local_def_id(&self, node: NodeId) -> Option<DefId> {
375 self.definitions.opt_local_def_id(node)
379 pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
380 self.definitions.as_local_node_id(def_id)
384 pub fn hir_to_node_id(&self, hir_id: HirId) -> NodeId {
385 self.hir_to_node_id[&hir_id]
389 pub fn node_to_hir_id(&self, node_id: NodeId) -> HirId {
390 self.definitions.node_to_hir_id(node_id)
394 pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> HirId {
395 self.definitions.def_index_to_hir_id(def_index)
399 pub fn def_index_to_node_id(&self, def_index: DefIndex) -> NodeId {
400 self.definitions.as_local_node_id(DefId::local(def_index)).unwrap()
404 pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
405 self.definitions.def_index_to_hir_id(def_id.to_def_id().index)
409 pub fn local_def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
410 self.definitions.as_local_node_id(def_id.to_def_id()).unwrap()
413 pub fn describe_def(&self, node_id: NodeId) -> Option<Def> {
414 let node = if let Some(node) = self.find(node_id) {
421 NodeKind::Item(item) => {
423 self.local_def_id(item.id)
427 ItemKind::Static(_, m, _) => Some(Def::Static(def_id(),
429 ItemKind::Const(..) => Some(Def::Const(def_id())),
430 ItemKind::Fn(..) => Some(Def::Fn(def_id())),
431 ItemKind::Mod(..) => Some(Def::Mod(def_id())),
432 ItemKind::Existential(..) => Some(Def::Existential(def_id())),
433 ItemKind::Ty(..) => Some(Def::TyAlias(def_id())),
434 ItemKind::Enum(..) => Some(Def::Enum(def_id())),
435 ItemKind::Struct(..) => Some(Def::Struct(def_id())),
436 ItemKind::Union(..) => Some(Def::Union(def_id())),
437 ItemKind::Trait(..) => Some(Def::Trait(def_id())),
438 ItemKind::TraitAlias(..) => {
439 bug!("trait aliases are not yet implemented (see issue #41517)")
441 ItemKind::ExternCrate(_) |
443 ItemKind::ForeignMod(..) |
444 ItemKind::GlobalAsm(..) |
445 ItemKind::Impl(..) => None,
448 NodeKind::ForeignItem(item) => {
449 let def_id = self.local_def_id(item.id);
451 ForeignItemKind::Fn(..) => Some(Def::Fn(def_id)),
452 ForeignItemKind::Static(_, m) => Some(Def::Static(def_id, m)),
453 ForeignItemKind::Type => Some(Def::ForeignTy(def_id)),
456 NodeKind::TraitItem(item) => {
457 let def_id = self.local_def_id(item.id);
459 TraitItemKind::Const(..) => Some(Def::AssociatedConst(def_id)),
460 TraitItemKind::Method(..) => Some(Def::Method(def_id)),
461 TraitItemKind::Type(..) => Some(Def::AssociatedTy(def_id)),
464 NodeKind::ImplItem(item) => {
465 let def_id = self.local_def_id(item.id);
467 ImplItemKind::Const(..) => Some(Def::AssociatedConst(def_id)),
468 ImplItemKind::Method(..) => Some(Def::Method(def_id)),
469 ImplItemKind::Type(..) => Some(Def::AssociatedTy(def_id)),
470 ImplItemKind::Existential(..) => Some(Def::AssociatedExistential(def_id)),
473 NodeKind::Variant(variant) => {
474 let def_id = self.local_def_id(variant.node.data.id());
475 Some(Def::Variant(def_id))
478 NodeKind::AnonConst(_) |
482 NodeKind::TraitRef(_) |
484 NodeKind::Binding(_) |
485 NodeKind::StructCtor(_) |
486 NodeKind::Lifetime(_) |
487 NodeKind::Visibility(_) |
488 NodeKind::Block(_) => None,
489 NodeKind::Local(local) => {
490 Some(Def::Local(local.id))
492 NodeKind::MacroDef(macro_def) => {
493 Some(Def::Macro(self.local_def_id(macro_def.id),
496 NodeKind::GenericParam(param) => {
497 Some(match param.kind {
498 GenericParamKind::Lifetime { .. } => Def::Local(param.id),
499 GenericParamKind::Type { .. } => Def::TyParam(self.local_def_id(param.id)),
505 fn entry_count(&self) -> usize {
509 fn find_entry(&self, id: NodeId) -> Option<EntryKind<'hir>> {
510 self.map.get(id.as_usize()).cloned()
513 pub fn krate(&self) -> &'hir Crate {
517 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem {
518 self.read(id.node_id);
520 // NB: intentionally bypass `self.forest.krate()` so that we
521 // do not trigger a read of the whole krate here
522 self.forest.krate.trait_item(id)
525 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem {
526 self.read(id.node_id);
528 // NB: intentionally bypass `self.forest.krate()` so that we
529 // do not trigger a read of the whole krate here
530 self.forest.krate.impl_item(id)
533 pub fn body(&self, id: BodyId) -> &'hir Body {
534 self.read(id.node_id);
536 // NB: intentionally bypass `self.forest.krate()` so that we
537 // do not trigger a read of the whole krate here
538 self.forest.krate.body(id)
541 pub fn fn_decl(&self, node_id: ast::NodeId) -> Option<FnDecl> {
542 if let Some(entry) = self.find_entry(node_id) {
543 entry.fn_decl().map(|fd| fd.clone())
545 bug!("no entry for node_id `{}`", node_id)
549 /// Returns the `NodeId` that corresponds to the definition of
550 /// which this is the body of, i.e. a `fn`, `const` or `static`
551 /// item (possibly associated), a closure, or a `hir::AnonConst`.
552 pub fn body_owner(&self, BodyId { node_id }: BodyId) -> NodeId {
553 let parent = self.get_parent_node(node_id);
554 assert!(self.map[parent.as_usize()].is_body_owner(node_id));
558 pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
559 self.local_def_id(self.body_owner(id))
562 /// Given a node id, returns the `BodyId` associated with it,
563 /// if the node is a body owner, otherwise returns `None`.
564 pub fn maybe_body_owned_by(&self, id: NodeId) -> Option<BodyId> {
565 if let Some(entry) = self.find_entry(id) {
566 if self.dep_graph.is_fully_enabled() {
567 let hir_id_owner = self.node_to_hir_id(id).owner;
568 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
569 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
572 entry.associated_body()
574 bug!("no entry for id `{}`", id)
578 /// Given a body owner's id, returns the `BodyId` associated with it.
579 pub fn body_owned_by(&self, id: NodeId) -> BodyId {
580 self.maybe_body_owned_by(id).unwrap_or_else(|| {
581 span_bug!(self.span(id), "body_owned_by: {} has no associated body",
582 self.node_to_string(id));
586 pub fn body_owner_kind(&self, id: NodeId) -> BodyOwnerKind {
588 NodeKind::Item(&Item { node: ItemKind::Const(..), .. }) |
589 NodeKind::TraitItem(&TraitItem { node: TraitItemKind::Const(..), .. }) |
590 NodeKind::ImplItem(&ImplItem { node: ImplItemKind::Const(..), .. }) |
591 NodeKind::AnonConst(_) => {
594 NodeKind::Item(&Item { node: ItemKind::Static(_, m, _), .. }) => {
595 BodyOwnerKind::Static(m)
597 // Default to function if it's not a constant or static.
598 _ => BodyOwnerKind::Fn
602 pub fn ty_param_owner(&self, id: NodeId) -> NodeId {
604 NodeKind::Item(&Item { node: ItemKind::Trait(..), .. }) => id,
605 NodeKind::GenericParam(_) => self.get_parent_node(id),
607 bug!("ty_param_owner: {} not a type parameter",
608 self.node_to_string(id))
613 pub fn ty_param_name(&self, id: NodeId) -> Name {
615 NodeKind::Item(&Item { node: ItemKind::Trait(..), .. }) => {
616 keywords::SelfType.name()
618 NodeKind::GenericParam(param) => param.name.ident().name,
619 _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
623 pub fn trait_impls(&self, trait_did: DefId) -> &'hir [NodeId] {
624 self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
626 // NB: intentionally bypass `self.forest.krate()` so that we
627 // do not trigger a read of the whole krate here
628 self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
631 pub fn trait_auto_impl(&self, trait_did: DefId) -> Option<NodeId> {
632 self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
634 // NB: intentionally bypass `self.forest.krate()` so that we
635 // do not trigger a read of the whole krate here
636 self.forest.krate.trait_auto_impl.get(&trait_did).cloned()
639 pub fn trait_is_auto(&self, trait_did: DefId) -> bool {
640 self.trait_auto_impl(trait_did).is_some()
643 /// Get the attributes on the krate. This is preferable to
644 /// invoking `krate.attrs` because it registers a tighter
645 /// dep-graph access.
646 pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
647 let def_path_hash = self.definitions.def_path_hash(CRATE_DEF_INDEX);
649 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::Hir));
650 &self.forest.krate.attrs
653 /// Retrieve the NodeKind corresponding to `id`, panicking if it cannot
655 pub fn get(&self, id: NodeId) -> NodeKind<'hir> {
656 match self.find(id) {
657 Some(node) => node, // read recorded by `find`
658 None => bug!("couldn't find node id {} in the AST map", id)
662 pub fn get_if_local(&self, id: DefId) -> Option<NodeKind<'hir>> {
663 self.as_local_node_id(id).map(|id| self.get(id)) // read recorded by `get`
666 pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics> {
667 self.get_if_local(id).and_then(|node| {
669 NodeKind::ImplItem(ref impl_item) => Some(&impl_item.generics),
670 NodeKind::TraitItem(ref trait_item) => Some(&trait_item.generics),
671 NodeKind::Item(ref item) => {
673 ItemKind::Fn(_, _, ref generics, _) |
674 ItemKind::Ty(_, ref generics) |
675 ItemKind::Enum(_, ref generics) |
676 ItemKind::Struct(_, ref generics) |
677 ItemKind::Union(_, ref generics) |
678 ItemKind::Trait(_, _, ref generics, ..) |
679 ItemKind::TraitAlias(ref generics, _) |
680 ItemKind::Impl(_, _, _, ref generics, ..) => Some(generics),
689 pub fn get_generics_span(&self, id: DefId) -> Option<Span> {
690 self.get_generics(id).map(|generics| generics.span).filter(|sp| *sp != DUMMY_SP)
693 /// Retrieve the NodeKind corresponding to `id`, returning None if
695 pub fn find(&self, id: NodeId) -> Option<NodeKind<'hir>> {
696 let result = self.find_entry(id).and_then(|x| x.to_node());
697 if result.is_some() {
703 /// Similar to get_parent, returns the parent node id or id if there is no
704 /// parent. Note that the parent may be CRATE_NODE_ID, which is not itself
705 /// present in the map -- so passing the return value of get_parent_node to
706 /// get may actually panic.
707 /// This function returns the immediate parent in the AST, whereas get_parent
708 /// returns the enclosing item. Note that this might not be the actual parent
709 /// node in the AST - some kinds of nodes are not in the map and these will
710 /// never appear as the parent_node. So you can always walk the parent_nodes
711 /// from a node to the root of the ast (unless you get the same id back here
712 /// that can happen if the id is not in the map itself or is just weird).
713 pub fn get_parent_node(&self, id: NodeId) -> NodeId {
714 if self.dep_graph.is_fully_enabled() {
715 let hir_id_owner = self.node_to_hir_id(id).owner;
716 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
717 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
720 self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
723 /// Check if the node is an argument. An argument is a local variable whose
724 /// immediate parent is an item or a closure.
725 pub fn is_argument(&self, id: NodeId) -> bool {
726 match self.find(id) {
727 Some(NodeKind::Binding(_)) => (),
730 match self.find(self.get_parent_node(id)) {
731 Some(NodeKind::Item(_)) |
732 Some(NodeKind::TraitItem(_)) |
733 Some(NodeKind::ImplItem(_)) => true,
734 Some(NodeKind::Expr(e)) => {
736 ExprKind::Closure(..) => true,
744 /// If there is some error when walking the parents (e.g., a node does not
745 /// have a parent in the map or a node can't be found), then we return the
746 /// last good node id we found. Note that reaching the crate root (id == 0),
747 /// is not an error, since items in the crate module have the crate root as
749 fn walk_parent_nodes<F, F2>(&self,
753 -> Result<NodeId, NodeId>
754 where F: Fn(&NodeKind<'hir>) -> bool, F2: Fn(&NodeKind<'hir>) -> bool
756 let mut id = start_id;
758 let parent_node = self.get_parent_node(id);
759 if parent_node == CRATE_NODE_ID {
760 return Ok(CRATE_NODE_ID);
762 if parent_node == id {
766 let node = self.find_entry(parent_node);
770 let node = node.unwrap().to_node();
774 return Ok(parent_node);
775 } else if bail_early(node) {
776 return Err(parent_node);
780 return Err(parent_node);
787 /// Retrieve the NodeId for `id`'s enclosing method, unless there's a
788 /// `while` or `loop` before reaching it, as block tail returns are not
789 /// available in them.
792 /// fn foo(x: usize) -> bool {
794 /// true // `get_return_block` gets passed the `id` corresponding
795 /// } else { // to this, it will return `foo`'s `NodeId`.
802 /// fn foo(x: usize) -> bool {
804 /// true // `get_return_block` gets passed the `id` corresponding
805 /// } // to this, it will return `None`.
809 pub fn get_return_block(&self, id: NodeId) -> Option<NodeId> {
810 let match_fn = |node: &NodeKind| {
813 NodeKind::ForeignItem(_) |
814 NodeKind::TraitItem(_) |
815 NodeKind::ImplItem(_) => true,
819 let match_non_returning_block = |node: &NodeKind| {
821 NodeKind::Expr(ref expr) => {
823 ExprKind::While(..) | ExprKind::Loop(..) => true,
831 match self.walk_parent_nodes(id, match_fn, match_non_returning_block) {
837 /// Retrieve the NodeId for `id`'s parent item, or `id` itself if no
838 /// parent item is in this map. The "parent item" is the closest parent node
839 /// in the HIR which is recorded by the map and is an item, either an item
840 /// in a module, trait, or impl.
841 pub fn get_parent(&self, id: NodeId) -> NodeId {
842 match self.walk_parent_nodes(id, |node| match *node {
844 NodeKind::ForeignItem(_) |
845 NodeKind::TraitItem(_) |
846 NodeKind::ImplItem(_) => true,
854 /// Returns the NodeId of `id`'s nearest module parent, or `id` itself if no
855 /// module parent is in this map.
856 pub fn get_module_parent(&self, id: NodeId) -> DefId {
857 let id = match self.walk_parent_nodes(id, |node| match *node {
858 NodeKind::Item(&Item { node: ItemKind::Mod(_), .. }) => true,
864 self.local_def_id(id)
867 /// Returns the nearest enclosing scope. A scope is an item or block.
868 /// FIXME it is not clear to me that all items qualify as scopes - statics
869 /// and associated types probably shouldn't, for example. Behavior in this
870 /// regard should be expected to be highly unstable.
871 pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
872 match self.walk_parent_nodes(id, |node| match *node {
874 NodeKind::ForeignItem(_) |
875 NodeKind::TraitItem(_) |
876 NodeKind::ImplItem(_) |
877 NodeKind::Block(_) => true,
885 pub fn get_parent_did(&self, id: NodeId) -> DefId {
886 self.local_def_id(self.get_parent(id))
889 pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
890 let parent = self.get_parent(id);
891 let abi = match self.find_entry(parent) {
892 Some(EntryKind::Item(_, _, i)) => {
894 ItemKind::ForeignMod(ref nm) => Some(nm.abi),
902 self.read(id); // reveals some of the content of a node
905 None => bug!("expected foreign mod or inlined parent, found {}",
906 self.node_to_string(parent))
910 pub fn expect_item(&self, id: NodeId) -> &'hir Item {
911 match self.find(id) { // read recorded by `find`
912 Some(NodeKind::Item(item)) => item,
913 _ => bug!("expected item, found {}", self.node_to_string(id))
917 pub fn expect_impl_item(&self, id: NodeId) -> &'hir ImplItem {
918 match self.find(id) {
919 Some(NodeKind::ImplItem(item)) => item,
920 _ => bug!("expected impl item, found {}", self.node_to_string(id))
924 pub fn expect_trait_item(&self, id: NodeId) -> &'hir TraitItem {
925 match self.find(id) {
926 Some(NodeKind::TraitItem(item)) => item,
927 _ => bug!("expected trait item, found {}", self.node_to_string(id))
931 pub fn expect_variant_data(&self, id: NodeId) -> &'hir VariantData {
932 match self.find(id) {
933 Some(NodeKind::Item(i)) => {
935 ItemKind::Struct(ref struct_def, _) |
936 ItemKind::Union(ref struct_def, _) => struct_def,
938 bug!("struct ID bound to non-struct {}",
939 self.node_to_string(id));
943 Some(NodeKind::StructCtor(data)) => data,
944 Some(NodeKind::Variant(variant)) => &variant.node.data,
946 bug!("expected struct or variant, found {}",
947 self.node_to_string(id));
952 pub fn expect_variant(&self, id: NodeId) -> &'hir Variant {
953 match self.find(id) {
954 Some(NodeKind::Variant(variant)) => variant,
955 _ => bug!("expected variant, found {}", self.node_to_string(id)),
959 pub fn expect_foreign_item(&self, id: NodeId) -> &'hir ForeignItem {
960 match self.find(id) {
961 Some(NodeKind::ForeignItem(item)) => item,
962 _ => bug!("expected foreign item, found {}", self.node_to_string(id))
966 pub fn expect_expr(&self, id: NodeId) -> &'hir Expr {
967 match self.find(id) { // read recorded by find
968 Some(NodeKind::Expr(expr)) => expr,
969 _ => bug!("expected expr, found {}", self.node_to_string(id))
973 /// Returns the name associated with the given NodeId's AST.
974 pub fn name(&self, id: NodeId) -> Name {
976 NodeKind::Item(i) => i.name,
977 NodeKind::ForeignItem(i) => i.name,
978 NodeKind::ImplItem(ii) => ii.ident.name,
979 NodeKind::TraitItem(ti) => ti.ident.name,
980 NodeKind::Variant(v) => v.node.name,
981 NodeKind::Field(f) => f.ident.name,
982 NodeKind::Lifetime(lt) => lt.name.ident().name,
983 NodeKind::GenericParam(param) => param.name.ident().name,
984 NodeKind::Binding(&Pat { node: PatKind::Binding(_,_,l,_), .. }) => l.name,
985 NodeKind::StructCtor(_) => self.name(self.get_parent(id)),
986 _ => bug!("no name for {}", self.node_to_string(id))
990 /// Given a node ID, get a list of attributes associated with the AST
991 /// corresponding to the NodeKind ID
992 pub fn attrs(&self, id: NodeId) -> &'hir [ast::Attribute] {
993 self.read(id); // reveals attributes on the node
994 let attrs = match self.find(id) {
995 Some(NodeKind::Item(i)) => Some(&i.attrs[..]),
996 Some(NodeKind::ForeignItem(fi)) => Some(&fi.attrs[..]),
997 Some(NodeKind::TraitItem(ref ti)) => Some(&ti.attrs[..]),
998 Some(NodeKind::ImplItem(ref ii)) => Some(&ii.attrs[..]),
999 Some(NodeKind::Variant(ref v)) => Some(&v.node.attrs[..]),
1000 Some(NodeKind::Field(ref f)) => Some(&f.attrs[..]),
1001 Some(NodeKind::Expr(ref e)) => Some(&*e.attrs),
1002 Some(NodeKind::Stmt(ref s)) => Some(s.node.attrs()),
1003 Some(NodeKind::GenericParam(param)) => Some(¶m.attrs[..]),
1004 // unit/tuple structs take the attributes straight from
1005 // the struct definition.
1006 Some(NodeKind::StructCtor(_)) => {
1007 return self.attrs(self.get_parent(id));
1011 attrs.unwrap_or(&[])
1014 /// Returns an iterator that yields the node id's with paths that
1015 /// match `parts`. (Requires `parts` is non-empty.)
1017 /// For example, if given `parts` equal to `["bar", "quux"]`, then
1018 /// the iterator will produce node id's for items with paths
1019 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
1020 /// any other such items it can find in the map.
1021 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
1022 -> NodesMatchingSuffix<'a, 'hir> {
1023 NodesMatchingSuffix {
1025 item_name: parts.last().unwrap(),
1026 in_which: &parts[..parts.len() - 1],
1031 pub fn span(&self, id: NodeId) -> Span {
1032 self.read(id); // reveals span from node
1033 match self.find_entry(id) {
1034 Some(EntryKind::Item(_, _, item)) => item.span,
1035 Some(EntryKind::ForeignItem(_, _, foreign_item)) => foreign_item.span,
1036 Some(EntryKind::TraitItem(_, _, trait_method)) => trait_method.span,
1037 Some(EntryKind::ImplItem(_, _, impl_item)) => impl_item.span,
1038 Some(EntryKind::Variant(_, _, variant)) => variant.span,
1039 Some(EntryKind::Field(_, _, field)) => field.span,
1040 Some(EntryKind::AnonConst(_, _, constant)) => self.body(constant.body).value.span,
1041 Some(EntryKind::Expr(_, _, expr)) => expr.span,
1042 Some(EntryKind::Stmt(_, _, stmt)) => stmt.span,
1043 Some(EntryKind::Ty(_, _, ty)) => ty.span,
1044 Some(EntryKind::TraitRef(_, _, tr)) => tr.path.span,
1045 Some(EntryKind::Binding(_, _, pat)) => pat.span,
1046 Some(EntryKind::Pat(_, _, pat)) => pat.span,
1047 Some(EntryKind::Block(_, _, block)) => block.span,
1048 Some(EntryKind::StructCtor(_, _, _)) => self.expect_item(self.get_parent(id)).span,
1049 Some(EntryKind::Lifetime(_, _, lifetime)) => lifetime.span,
1050 Some(EntryKind::GenericParam(_, _, param)) => param.span,
1051 Some(EntryKind::Visibility(_, _, &Spanned {
1052 node: VisibilityKind::Restricted { ref path, .. }, ..
1054 Some(EntryKind::Visibility(_, _, v)) => bug!("unexpected Visibility {:?}", v),
1055 Some(EntryKind::Local(_, _, local)) => local.span,
1056 Some(EntryKind::MacroDef(_, macro_def)) => macro_def.span,
1058 Some(EntryKind::RootCrate(_)) => self.forest.krate.span,
1059 Some(EntryKind::NotPresent) | None => {
1060 bug!("hir::map::Map::span: id not in map: {:?}", id)
1065 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
1066 self.as_local_node_id(id).map(|id| self.span(id))
1069 pub fn node_to_string(&self, id: NodeId) -> String {
1070 node_id_to_string(self, id, true)
1073 pub fn node_to_user_string(&self, id: NodeId) -> String {
1074 node_id_to_string(self, id, false)
1077 pub fn node_to_pretty_string(&self, id: NodeId) -> String {
1078 print::to_string(self, |s| s.print_node(self.get(id)))
1082 pub struct NodesMatchingSuffix<'a, 'hir:'a> {
1084 item_name: &'a String,
1085 in_which: &'a [String],
1089 impl<'a, 'hir> NodesMatchingSuffix<'a, 'hir> {
1090 /// Returns true only if some suffix of the module path for parent
1091 /// matches `self.in_which`.
1093 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
1094 /// returns true if parent's path ends with the suffix
1095 /// `x_0::x_1::...::x_k`.
1096 fn suffix_matches(&self, parent: NodeId) -> bool {
1097 let mut cursor = parent;
1098 for part in self.in_which.iter().rev() {
1099 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
1100 None => return false,
1101 Some((node_id, name)) => (node_id, name),
1103 if mod_name != &**part {
1106 cursor = self.map.get_parent(mod_id);
1110 // Finds the first mod in parent chain for `id`, along with
1113 // If `id` itself is a mod named `m` with parent `p`, then
1114 // returns `Some(id, m, p)`. If `id` has no mod in its parent
1115 // chain, then returns `None`.
1116 fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
1118 match map.find(id)? {
1119 NodeKind::Item(item) if item_is_mod(&item) =>
1120 return Some((id, item.name)),
1123 let parent = map.get_parent(id);
1124 if parent == id { return None }
1128 fn item_is_mod(item: &Item) -> bool {
1130 ItemKind::Mod(_) => true,
1137 // We are looking at some node `n` with a given name and parent
1138 // id; do their names match what I am seeking?
1139 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
1140 name == &**self.item_name && self.suffix_matches(parent_of_n)
1144 impl<'a, 'hir> Iterator for NodesMatchingSuffix<'a, 'hir> {
1147 fn next(&mut self) -> Option<NodeId> {
1150 if idx.as_usize() >= self.map.entry_count() {
1153 self.idx = NodeId::from_u32(self.idx.as_u32() + 1);
1154 let name = match self.map.find_entry(idx) {
1155 Some(EntryKind::Item(_, _, n)) => n.name(),
1156 Some(EntryKind::ForeignItem(_, _, n))=> n.name(),
1157 Some(EntryKind::TraitItem(_, _, n)) => n.name(),
1158 Some(EntryKind::ImplItem(_, _, n)) => n.name(),
1159 Some(EntryKind::Variant(_, _, n)) => n.name(),
1160 Some(EntryKind::Field(_, _, n)) => n.name(),
1163 if self.matches_names(self.map.get_parent(idx), name) {
1171 fn name(&self) -> Name;
1174 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
1176 impl Named for Item { fn name(&self) -> Name { self.name } }
1177 impl Named for ForeignItem { fn name(&self) -> Name { self.name } }
1178 impl Named for VariantKind { fn name(&self) -> Name { self.name } }
1179 impl Named for StructField { fn name(&self) -> Name { self.ident.name } }
1180 impl Named for TraitItem { fn name(&self) -> Name { self.ident.name } }
1181 impl Named for ImplItem { fn name(&self) -> Name { self.ident.name } }
1184 pub fn map_crate<'hir>(sess: &::session::Session,
1185 cstore: &dyn CrateStore,
1186 forest: &'hir mut Forest,
1187 definitions: &'hir Definitions)
1189 let (map, crate_hash) = {
1190 let hcx = ::ich::StableHashingContext::new(sess, &forest.krate, definitions, cstore);
1192 let mut collector = NodeCollector::root(&forest.krate,
1196 intravisit::walk_crate(&mut collector, &forest.krate);
1198 let crate_disambiguator = sess.local_crate_disambiguator();
1199 let cmdline_args = sess.opts.dep_tracking_hash();
1200 collector.finalize_and_compute_crate_hash(crate_disambiguator,
1206 if log_enabled!(::log::Level::Debug) {
1207 // This only makes sense for ordered stores; note the
1208 // enumerate to count the number of entries.
1209 let (entries_less_1, _) = map.iter().filter(|&x| {
1211 EntryKind::NotPresent => false,
1214 }).enumerate().last().expect("AST map was empty after folding?");
1216 let entries = entries_less_1 + 1;
1217 let vector_length = map.len();
1218 debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
1219 entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
1222 // Build the reverse mapping of `node_to_hir_id`.
1223 let hir_to_node_id = definitions.node_to_hir_id.iter_enumerated()
1224 .map(|(node_id, &hir_id)| (hir_id, node_id)).collect();
1228 dep_graph: forest.dep_graph.clone(),
1235 hir_id_validator::check_crate(&map);
1240 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1241 /// except it avoids creating a dependency on the whole crate.
1242 impl<'hir> print::PpAnn for Map<'hir> {
1243 fn nested(&self, state: &mut print::State, nested: print::Nested) -> io::Result<()> {
1245 Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1246 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1247 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1248 Nested::Body(id) => state.print_expr(&self.body(id).value),
1249 Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
1254 impl<'a> print::State<'a> {
1255 pub fn print_node(&mut self, node: NodeKind) -> io::Result<()> {
1257 NodeKind::Item(a) => self.print_item(&a),
1258 NodeKind::ForeignItem(a) => self.print_foreign_item(&a),
1259 NodeKind::TraitItem(a) => self.print_trait_item(a),
1260 NodeKind::ImplItem(a) => self.print_impl_item(a),
1261 NodeKind::Variant(a) => self.print_variant(&a),
1262 NodeKind::AnonConst(a) => self.print_anon_const(&a),
1263 NodeKind::Expr(a) => self.print_expr(&a),
1264 NodeKind::Stmt(a) => self.print_stmt(&a),
1265 NodeKind::Ty(a) => self.print_type(&a),
1266 NodeKind::TraitRef(a) => self.print_trait_ref(&a),
1267 NodeKind::Binding(a) |
1268 NodeKind::Pat(a) => self.print_pat(&a),
1269 NodeKind::Block(a) => {
1270 use syntax::print::pprust::PrintState;
1272 // containing cbox, will be closed by print-block at }
1273 self.cbox(print::indent_unit)?;
1274 // head-ibox, will be closed by print-block after {
1276 self.print_block(&a)
1278 NodeKind::Lifetime(a) => self.print_lifetime(&a),
1279 NodeKind::Visibility(a) => self.print_visibility(&a),
1280 NodeKind::GenericParam(_) => bug!("cannot print NodeKind::GenericParam"),
1281 NodeKind::Field(_) => bug!("cannot print StructField"),
1282 // these cases do not carry enough information in the
1283 // hir_map to reconstruct their full structure for pretty
1285 NodeKind::StructCtor(_) => bug!("cannot print isolated StructCtor"),
1286 NodeKind::Local(a) => self.print_local_decl(&a),
1287 NodeKind::MacroDef(_) => bug!("cannot print MacroDef"),
1292 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
1293 let id_str = format!(" (id={})", id);
1294 let id_str = if include_id { &id_str[..] } else { "" };
1297 // This functionality is used for debugging, try to use TyCtxt to get
1298 // the user-friendly path, otherwise fall back to stringifying DefPath.
1299 ::ty::tls::with_opt(|tcx| {
1300 if let Some(tcx) = tcx {
1301 tcx.node_path_str(id)
1302 } else if let Some(path) = map.def_path_from_id(id) {
1303 path.data.into_iter().map(|elem| {
1304 elem.data.to_string()
1305 }).collect::<Vec<_>>().join("::")
1307 String::from("<missing path>")
1312 match map.find(id) {
1313 Some(NodeKind::Item(item)) => {
1314 let item_str = match item.node {
1315 ItemKind::ExternCrate(..) => "extern crate",
1316 ItemKind::Use(..) => "use",
1317 ItemKind::Static(..) => "static",
1318 ItemKind::Const(..) => "const",
1319 ItemKind::Fn(..) => "fn",
1320 ItemKind::Mod(..) => "mod",
1321 ItemKind::ForeignMod(..) => "foreign mod",
1322 ItemKind::GlobalAsm(..) => "global asm",
1323 ItemKind::Ty(..) => "ty",
1324 ItemKind::Existential(..) => "existential type",
1325 ItemKind::Enum(..) => "enum",
1326 ItemKind::Struct(..) => "struct",
1327 ItemKind::Union(..) => "union",
1328 ItemKind::Trait(..) => "trait",
1329 ItemKind::TraitAlias(..) => "trait alias",
1330 ItemKind::Impl(..) => "impl",
1332 format!("{} {}{}", item_str, path_str(), id_str)
1334 Some(NodeKind::ForeignItem(_)) => {
1335 format!("foreign item {}{}", path_str(), id_str)
1337 Some(NodeKind::ImplItem(ii)) => {
1339 ImplItemKind::Const(..) => {
1340 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1342 ImplItemKind::Method(..) => {
1343 format!("method {} in {}{}", ii.ident, path_str(), id_str)
1345 ImplItemKind::Type(_) => {
1346 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1348 ImplItemKind::Existential(_) => {
1349 format!("assoc existential type {} in {}{}", ii.ident, path_str(), id_str)
1353 Some(NodeKind::TraitItem(ti)) => {
1354 let kind = match ti.node {
1355 TraitItemKind::Const(..) => "assoc constant",
1356 TraitItemKind::Method(..) => "trait method",
1357 TraitItemKind::Type(..) => "assoc type",
1360 format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1362 Some(NodeKind::Variant(ref variant)) => {
1363 format!("variant {} in {}{}",
1367 Some(NodeKind::Field(ref field)) => {
1368 format!("field {} in {}{}",
1372 Some(NodeKind::AnonConst(_)) => {
1373 format!("const {}{}", map.node_to_pretty_string(id), id_str)
1375 Some(NodeKind::Expr(_)) => {
1376 format!("expr {}{}", map.node_to_pretty_string(id), id_str)
1378 Some(NodeKind::Stmt(_)) => {
1379 format!("stmt {}{}", map.node_to_pretty_string(id), id_str)
1381 Some(NodeKind::Ty(_)) => {
1382 format!("type {}{}", map.node_to_pretty_string(id), id_str)
1384 Some(NodeKind::TraitRef(_)) => {
1385 format!("trait_ref {}{}", map.node_to_pretty_string(id), id_str)
1387 Some(NodeKind::Binding(_)) => {
1388 format!("local {}{}", map.node_to_pretty_string(id), id_str)
1390 Some(NodeKind::Pat(_)) => {
1391 format!("pat {}{}", map.node_to_pretty_string(id), id_str)
1393 Some(NodeKind::Block(_)) => {
1394 format!("block {}{}", map.node_to_pretty_string(id), id_str)
1396 Some(NodeKind::Local(_)) => {
1397 format!("local {}{}", map.node_to_pretty_string(id), id_str)
1399 Some(NodeKind::StructCtor(_)) => {
1400 format!("struct_ctor {}{}", path_str(), id_str)
1402 Some(NodeKind::Lifetime(_)) => {
1403 format!("lifetime {}{}", map.node_to_pretty_string(id), id_str)
1405 Some(NodeKind::GenericParam(ref param)) => {
1406 format!("generic_param {:?}{}", param, id_str)
1408 Some(NodeKind::Visibility(ref vis)) => {
1409 format!("visibility {:?}{}", vis, id_str)
1411 Some(NodeKind::MacroDef(_)) => {
1412 format!("macro {}{}", path_str(), id_str)
1415 format!("unknown node{}", id_str)
1420 pub fn describe_def(tcx: TyCtxt, def_id: DefId) -> Option<Def> {
1421 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1422 tcx.hir.describe_def(node_id)
1424 bug!("Calling local describe_def query provider for upstream DefId: {:?}",