1 use self::collector::NodeCollector;
2 pub use self::def_collector::{DefCollector, MacroInvocationData};
3 pub use self::definitions::{Definitions, DefKey, DefPath, DefPathData,
4 DisambiguatedDefPathData, DefPathHash};
6 use crate::dep_graph::{DepGraph, DepNode, DepKind, DepNodeIndex};
8 use crate::hir::def_id::{CRATE_DEF_INDEX, DefId, LocalDefId, DefIndexAddressSpace};
10 use crate::middle::cstore::CrateStoreDyn;
12 use rustc_target::spec::abi::Abi;
13 use rustc_data_structures::svh::Svh;
14 use rustc_data_structures::sync::join;
15 use syntax::ast::{self, Name, NodeId, CRATE_NODE_ID};
16 use syntax::source_map::Spanned;
17 use syntax::ext::base::MacroKind;
18 use syntax_pos::{Span, DUMMY_SP};
21 use crate::hir::itemlikevisit::ItemLikeVisitor;
22 use crate::hir::print::Nested;
23 use crate::util::nodemap::FxHashMap;
24 use crate::util::common::time;
27 use std::result::Result::Err;
28 use crate::ty::TyCtxt;
36 pub const ITEM_LIKE_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::Low;
37 pub const REGULAR_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::High;
39 /// Represents an entry and its parent `NodeId`.
40 #[derive(Copy, Clone, Debug)]
41 pub struct Entry<'hir> {
44 dep_node: DepNodeIndex,
48 impl<'hir> Entry<'hir> {
49 fn parent_node(self) -> Option<NodeId> {
51 Node::Crate | Node::MacroDef(_) => None,
52 _ => Some(self.parent),
56 fn fn_decl(&self) -> Option<&FnDecl> {
58 Node::Item(ref item) => {
60 ItemKind::Fn(ref fn_decl, _, _, _) => Some(&fn_decl),
65 Node::TraitItem(ref item) => {
67 TraitItemKind::Method(ref method_sig, _) => Some(&method_sig.decl),
72 Node::ImplItem(ref item) => {
74 ImplItemKind::Method(ref method_sig, _) => Some(&method_sig.decl),
79 Node::Expr(ref expr) => {
81 ExprKind::Closure(_, ref fn_decl, ..) => Some(&fn_decl),
90 fn associated_body(self) -> Option<BodyId> {
94 ItemKind::Const(_, body) |
95 ItemKind::Static(.., body) |
96 ItemKind::Fn(_, _, _, body) => Some(body),
101 Node::TraitItem(item) => {
103 TraitItemKind::Const(_, Some(body)) |
104 TraitItemKind::Method(_, TraitMethod::Provided(body)) => Some(body),
109 Node::ImplItem(item) => {
111 ImplItemKind::Const(_, body) |
112 ImplItemKind::Method(_, body) => Some(body),
117 Node::AnonConst(constant) => Some(constant.body),
119 Node::Expr(expr) => {
121 ExprKind::Closure(.., body, _, _) => Some(body),
130 fn is_body_owner(self, hir_id: HirId) -> bool {
131 match self.associated_body() {
132 Some(b) => b.hir_id == hir_id,
138 /// Stores a crate and any number of inlined items from other crates.
141 pub dep_graph: DepGraph,
145 pub fn new(krate: Crate, dep_graph: &DepGraph) -> Forest {
148 dep_graph: dep_graph.clone(),
152 pub fn krate<'hir>(&'hir self) -> &'hir Crate {
153 self.dep_graph.read(DepNode::new_no_params(DepKind::Krate));
157 /// This is internally in the depedency tracking system.
158 /// Use the `krate` method to ensure your dependency on the
159 /// crate is tracked.
160 pub fn untracked_krate<'hir>(&'hir self) -> &'hir Crate {
165 /// Represents a mapping from `NodeId`s to AST elements and their parent `NodeId`s.
167 pub struct Map<'hir> {
168 /// The backing storage for all the AST nodes.
169 pub forest: &'hir Forest,
171 /// Same as the dep_graph in forest, just available with one fewer
172 /// deref. This is a gratuitous micro-optimization.
173 pub dep_graph: DepGraph,
175 /// The SVH of the local crate.
178 /// `NodeId`s are sequential integers from 0, so we can be
179 /// super-compact by storing them in a vector. Not everything with
180 /// a `NodeId` is in the map, but empirically the occupancy is about
181 /// 75-80%, so there's not too much overhead (certainly less than
182 /// a hashmap, since they (at the time of writing) have a maximum
183 /// of 75% occupancy).
185 /// Also, indexing is pretty quick when you've got a vector and
186 /// plain old integers.
187 map: Vec<Option<Entry<'hir>>>,
189 definitions: &'hir Definitions,
191 /// The reverse mapping of `node_to_hir_id`.
192 hir_to_node_id: FxHashMap<HirId, NodeId>,
195 impl<'hir> Map<'hir> {
196 /// Registers a read in the dependency graph of the AST node with
197 /// the given `id`. This needs to be called each time a public
198 /// function returns the HIR for a node -- in other words, when it
199 /// "reveals" the content of a node to the caller (who might not
200 /// otherwise have had access to those contents, and hence needs a
201 /// read recorded). If the function just returns a DefId or
202 /// NodeId, no actual content was returned, so no read is needed.
203 pub fn read(&self, id: NodeId) {
204 if let Some(entry) = self.map[id.as_usize()] {
205 self.dep_graph.read_index(entry.dep_node);
207 bug!("called `HirMap::read()` with invalid `NodeId`: {:?}", id)
211 // FIXME(@ljedrz): replace the NodeId variant
212 pub fn read_by_hir_id(&self, hir_id: HirId) {
213 let node_id = self.hir_to_node_id(hir_id);
218 pub fn definitions(&self) -> &'hir Definitions {
222 pub fn def_key(&self, def_id: DefId) -> DefKey {
223 assert!(def_id.is_local());
224 self.definitions.def_key(def_id.index)
227 pub fn def_path_from_id(&self, id: NodeId) -> Option<DefPath> {
228 self.opt_local_def_id(id).map(|def_id| {
229 self.def_path(def_id)
233 // FIXME(@ljedrz): replace the NodeId variant
234 pub fn def_path_from_hir_id(&self, id: HirId) -> DefPath {
235 self.def_path(self.local_def_id_from_hir_id(id))
238 pub fn def_path(&self, def_id: DefId) -> DefPath {
239 assert!(def_id.is_local());
240 self.definitions.def_path(def_id.index)
244 pub fn local_def_id(&self, node: NodeId) -> DefId {
245 self.opt_local_def_id(node).unwrap_or_else(|| {
246 bug!("local_def_id: no entry for `{}`, which has a map of `{:?}`",
247 node, self.find_entry(node))
251 // FIXME(@ljedrz): replace the NodeId variant
253 pub fn local_def_id_from_hir_id(&self, hir_id: HirId) -> DefId {
254 let node_id = self.hir_to_node_id(hir_id);
255 self.opt_local_def_id(node_id).unwrap_or_else(|| {
256 bug!("local_def_id_from_hir_id: no entry for `{:?}`, which has a map of `{:?}`",
257 hir_id, self.find_entry(node_id))
261 // FIXME(@ljedrz): replace the NodeId variant
263 pub fn opt_local_def_id_from_hir_id(&self, hir_id: HirId) -> Option<DefId> {
264 let node_id = self.hir_to_node_id(hir_id);
265 self.definitions.opt_local_def_id(node_id)
269 pub fn opt_local_def_id(&self, node: NodeId) -> Option<DefId> {
270 self.definitions.opt_local_def_id(node)
274 pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
275 self.definitions.as_local_node_id(def_id)
278 // FIXME(@ljedrz): replace the NodeId variant
280 pub fn as_local_hir_id(&self, def_id: DefId) -> Option<HirId> {
281 self.definitions.as_local_hir_id(def_id)
285 pub fn hir_to_node_id(&self, hir_id: HirId) -> NodeId {
286 self.hir_to_node_id[&hir_id]
290 pub fn node_to_hir_id(&self, node_id: NodeId) -> HirId {
291 self.definitions.node_to_hir_id(node_id)
295 pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> HirId {
296 self.definitions.def_index_to_hir_id(def_index)
300 pub fn def_index_to_node_id(&self, def_index: DefIndex) -> NodeId {
301 self.definitions.as_local_node_id(DefId::local(def_index)).unwrap()
305 pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
306 self.definitions.def_index_to_hir_id(def_id.to_def_id().index)
310 pub fn local_def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
311 self.definitions.as_local_node_id(def_id.to_def_id()).unwrap()
314 pub fn describe_def(&self, node_id: NodeId) -> Option<Def> {
315 let node = if let Some(node) = self.find(node_id) {
322 Node::Item(item) => {
323 let def_id = || self.local_def_id(item.id);
326 ItemKind::Static(_, m, _) => Some(Def::Static(def_id(), m == MutMutable)),
327 ItemKind::Const(..) => Some(Def::Const(def_id())),
328 ItemKind::Fn(..) => Some(Def::Fn(def_id())),
329 ItemKind::Mod(..) => Some(Def::Mod(def_id())),
330 ItemKind::Existential(..) => Some(Def::Existential(def_id())),
331 ItemKind::Ty(..) => Some(Def::TyAlias(def_id())),
332 ItemKind::Enum(..) => Some(Def::Enum(def_id())),
333 ItemKind::Struct(..) => Some(Def::Struct(def_id())),
334 ItemKind::Union(..) => Some(Def::Union(def_id())),
335 ItemKind::Trait(..) => Some(Def::Trait(def_id())),
336 ItemKind::TraitAlias(..) => Some(Def::TraitAlias(def_id())),
337 ItemKind::ExternCrate(_) |
339 ItemKind::ForeignMod(..) |
340 ItemKind::GlobalAsm(..) |
341 ItemKind::Impl(..) => None,
344 Node::ForeignItem(item) => {
345 let def_id = self.local_def_id(item.id);
347 ForeignItemKind::Fn(..) => Some(Def::Fn(def_id)),
348 ForeignItemKind::Static(_, m) => Some(Def::Static(def_id, m)),
349 ForeignItemKind::Type => Some(Def::ForeignTy(def_id)),
352 Node::TraitItem(item) => {
353 let def_id = self.local_def_id(item.id);
355 TraitItemKind::Const(..) => Some(Def::AssociatedConst(def_id)),
356 TraitItemKind::Method(..) => Some(Def::Method(def_id)),
357 TraitItemKind::Type(..) => Some(Def::AssociatedTy(def_id)),
360 Node::ImplItem(item) => {
361 let def_id = self.local_def_id(item.id);
363 ImplItemKind::Const(..) => Some(Def::AssociatedConst(def_id)),
364 ImplItemKind::Method(..) => Some(Def::Method(def_id)),
365 ImplItemKind::Type(..) => Some(Def::AssociatedTy(def_id)),
366 ImplItemKind::Existential(..) => Some(Def::AssociatedExistential(def_id)),
369 Node::Variant(variant) => {
370 let def_id = self.local_def_id(variant.node.data.id());
371 Some(Def::Variant(def_id))
373 Node::StructCtor(variant) => {
374 let def_id = self.local_def_id(variant.id());
375 Some(Def::StructCtor(def_id, def::CtorKind::from_hir(variant)))
381 Node::PathSegment(_) |
387 Node::Visibility(_) |
390 Node::Local(local) => {
391 Some(Def::Local(local.id))
393 Node::MacroDef(macro_def) => {
394 Some(Def::Macro(self.local_def_id(macro_def.id),
397 Node::GenericParam(param) => {
398 Some(match param.kind {
399 GenericParamKind::Lifetime { .. } => Def::Local(param.id),
400 GenericParamKind::Type { .. } => Def::TyParam(self.local_def_id(param.id)),
406 // FIXME(@ljedrz): replace the NodeId variant
407 pub fn describe_def_by_hir_id(&self, hir_id: HirId) -> Option<Def> {
408 let node_id = self.hir_to_node_id(hir_id);
409 self.describe_def(node_id)
412 fn entry_count(&self) -> usize {
416 fn find_entry(&self, id: NodeId) -> Option<Entry<'hir>> {
417 self.map.get(id.as_usize()).cloned().unwrap_or(None)
420 pub fn krate(&self) -> &'hir Crate {
424 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem {
425 self.read(id.node_id);
427 // N.B., intentionally bypass `self.forest.krate()` so that we
428 // do not trigger a read of the whole krate here
429 self.forest.krate.trait_item(id)
432 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem {
433 self.read(id.node_id);
435 // N.B., intentionally bypass `self.forest.krate()` so that we
436 // do not trigger a read of the whole krate here
437 self.forest.krate.impl_item(id)
440 pub fn body(&self, id: BodyId) -> &'hir Body {
441 self.read_by_hir_id(id.hir_id);
443 // N.B., intentionally bypass `self.forest.krate()` so that we
444 // do not trigger a read of the whole krate here
445 self.forest.krate.body(id)
448 pub fn fn_decl(&self, node_id: ast::NodeId) -> Option<FnDecl> {
449 if let Some(entry) = self.find_entry(node_id) {
450 entry.fn_decl().cloned()
452 bug!("no entry for node_id `{}`", node_id)
456 // FIXME(@ljedrz): replace the NodeId variant
457 pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<FnDecl> {
458 let node_id = self.hir_to_node_id(hir_id);
459 self.fn_decl(node_id)
462 /// Returns the `NodeId` that corresponds to the definition of
463 /// which this is the body of, i.e., a `fn`, `const` or `static`
464 /// item (possibly associated), a closure, or a `hir::AnonConst`.
465 pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> NodeId {
466 let node_id = self.hir_to_node_id(hir_id);
467 let parent = self.get_parent_node(node_id);
468 assert!(self.map[parent.as_usize()].map_or(false, |e| e.is_body_owner(hir_id)));
472 pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
473 self.local_def_id(self.body_owner(id))
476 /// Given a `NodeId`, returns the `BodyId` associated with it,
477 /// if the node is a body owner, otherwise returns `None`.
478 pub fn maybe_body_owned_by(&self, id: NodeId) -> Option<BodyId> {
479 if let Some(entry) = self.find_entry(id) {
480 if self.dep_graph.is_fully_enabled() {
481 let hir_id_owner = self.node_to_hir_id(id).owner;
482 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
483 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
486 entry.associated_body()
488 bug!("no entry for id `{}`", id)
492 // FIXME(@ljedrz): replace the NodeId variant
493 pub fn maybe_body_owned_by_by_hir_id(&self, id: HirId) -> Option<BodyId> {
494 let node_id = self.hir_to_node_id(id);
495 self.maybe_body_owned_by(node_id)
498 /// Given a body owner's id, returns the `BodyId` associated with it.
499 pub fn body_owned_by(&self, id: NodeId) -> BodyId {
500 self.maybe_body_owned_by(id).unwrap_or_else(|| {
501 span_bug!(self.span(id), "body_owned_by: {} has no associated body",
502 self.node_to_string(id));
506 pub fn body_owner_kind(&self, id: NodeId) -> BodyOwnerKind {
508 Node::Item(&Item { node: ItemKind::Const(..), .. }) |
509 Node::TraitItem(&TraitItem { node: TraitItemKind::Const(..), .. }) |
510 Node::ImplItem(&ImplItem { node: ImplItemKind::Const(..), .. }) |
511 Node::AnonConst(_) => {
514 Node::Variant(&Spanned { node: VariantKind { data: VariantData::Tuple(..), .. }, .. }) |
515 Node::StructCtor(..) |
516 Node::Item(&Item { node: ItemKind::Fn(..), .. }) |
517 Node::TraitItem(&TraitItem { node: TraitItemKind::Method(..), .. }) |
518 Node::ImplItem(&ImplItem { node: ImplItemKind::Method(..), .. }) => {
521 Node::Item(&Item { node: ItemKind::Static(_, m, _), .. }) => {
522 BodyOwnerKind::Static(m)
524 Node::Expr(&Expr { node: ExprKind::Closure(..), .. }) => {
525 BodyOwnerKind::Closure
527 node => bug!("{:#?} is not a body node", node),
531 // FIXME(@ljedrz): replace the NodeId variant
532 pub fn body_owner_kind_by_hir_id(&self, id: HirId) -> BodyOwnerKind {
533 let node_id = self.hir_to_node_id(id);
534 self.body_owner_kind(node_id)
537 pub fn ty_param_owner(&self, id: NodeId) -> NodeId {
539 Node::Item(&Item { node: ItemKind::Trait(..), .. }) => id,
540 Node::GenericParam(_) => self.get_parent_node(id),
541 _ => bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id))
545 pub fn ty_param_name(&self, id: NodeId) -> Name {
547 Node::Item(&Item { node: ItemKind::Trait(..), .. }) => keywords::SelfUpper.name(),
548 Node::GenericParam(param) => param.name.ident().name,
549 _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
553 pub fn trait_impls(&self, trait_did: DefId) -> &'hir [NodeId] {
554 self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
556 // N.B., intentionally bypass `self.forest.krate()` so that we
557 // do not trigger a read of the whole krate here
558 self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
561 pub fn trait_auto_impl(&self, trait_did: DefId) -> Option<NodeId> {
562 self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
564 // N.B., intentionally bypass `self.forest.krate()` so that we
565 // do not trigger a read of the whole krate here
566 self.forest.krate.trait_auto_impl.get(&trait_did).cloned()
569 pub fn trait_is_auto(&self, trait_did: DefId) -> bool {
570 self.trait_auto_impl(trait_did).is_some()
573 /// Gets the attributes on the crate. This is preferable to
574 /// invoking `krate.attrs` because it registers a tighter
575 /// dep-graph access.
576 pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
577 let def_path_hash = self.definitions.def_path_hash(CRATE_DEF_INDEX);
579 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::Hir));
580 &self.forest.krate.attrs
583 pub fn get_module(&self, module: DefId) -> (&'hir Mod, Span, NodeId)
585 let node_id = self.as_local_node_id(module).unwrap();
587 match self.find_entry(node_id).unwrap().node {
590 node: ItemKind::Mod(ref m),
592 }) => (m, span, node_id),
593 Node::Crate => (&self.forest.krate.module, self.forest.krate.span, node_id),
594 _ => panic!("not a module")
598 pub fn visit_item_likes_in_module<V>(&self, module: DefId, visitor: &mut V)
599 where V: ItemLikeVisitor<'hir>
601 let node_id = self.as_local_node_id(module).unwrap();
603 // Read the module so we'll be re-executed if new items
604 // appear immediately under in the module. If some new item appears
605 // in some nested item in the module, we'll be re-executed due to reads
606 // in the expect_* calls the loops below
609 let module = &self.forest.krate.modules[&node_id];
611 for id in &module.items {
612 visitor.visit_item(self.expect_item(*id));
615 for id in &module.trait_items {
616 visitor.visit_trait_item(self.expect_trait_item(id.node_id));
619 for id in &module.impl_items {
620 visitor.visit_impl_item(self.expect_impl_item(id.node_id));
624 /// Retrieve the Node corresponding to `id`, panicking if it cannot
626 pub fn get(&self, id: NodeId) -> Node<'hir> {
627 // read recorded by `find`
628 self.find(id).unwrap_or_else(|| bug!("couldn't find node id {} in the AST map", id))
631 // FIXME(@ljedrz): replace the NodeId variant
632 pub fn get_by_hir_id(&self, id: HirId) -> Node<'hir> {
633 let node_id = self.hir_to_node_id(id);
637 pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
638 self.as_local_node_id(id).map(|id| self.get(id)) // read recorded by `get`
641 pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics> {
642 self.get_if_local(id).and_then(|node| {
644 Node::ImplItem(ref impl_item) => Some(&impl_item.generics),
645 Node::TraitItem(ref trait_item) => Some(&trait_item.generics),
646 Node::Item(ref item) => {
648 ItemKind::Fn(_, _, ref generics, _) |
649 ItemKind::Ty(_, ref generics) |
650 ItemKind::Enum(_, ref generics) |
651 ItemKind::Struct(_, ref generics) |
652 ItemKind::Union(_, ref generics) |
653 ItemKind::Trait(_, _, ref generics, ..) |
654 ItemKind::TraitAlias(ref generics, _) |
655 ItemKind::Impl(_, _, _, ref generics, ..) => Some(generics),
664 pub fn get_generics_span(&self, id: DefId) -> Option<Span> {
665 self.get_generics(id).map(|generics| generics.span).filter(|sp| *sp != DUMMY_SP)
668 /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
669 pub fn find(&self, id: NodeId) -> Option<Node<'hir>> {
670 let result = self.find_entry(id).and_then(|entry| {
671 if let Node::Crate = entry.node {
677 if result.is_some() {
683 // FIXME(@ljedrz): replace the NodeId variant
684 pub fn find_by_hir_id(&self, hir_id: HirId) -> Option<Node<'hir>> {
685 let node_id = self.hir_to_node_id(hir_id);
689 /// Similar to `get_parent`; returns the parent node-id, or own `id` if there is
690 /// no parent. Note that the parent may be `CRATE_NODE_ID`, which is not itself
691 /// present in the map -- so passing the return value of get_parent_node to
692 /// get may actually panic.
693 /// This function returns the immediate parent in the AST, whereas get_parent
694 /// returns the enclosing item. Note that this might not be the actual parent
695 /// node in the AST - some kinds of nodes are not in the map and these will
696 /// never appear as the parent_node. So you can always walk the `parent_nodes`
697 /// from a node to the root of the ast (unless you get the same ID back here
698 /// that can happen if the ID is not in the map itself or is just weird).
699 pub fn get_parent_node(&self, id: NodeId) -> NodeId {
700 if self.dep_graph.is_fully_enabled() {
701 let hir_id_owner = self.node_to_hir_id(id).owner;
702 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
703 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
706 self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
709 // FIXME(@ljedrz): replace the NodeId variant
710 pub fn get_parent_node_by_hir_id(&self, id: HirId) -> HirId {
711 let node_id = self.hir_to_node_id(id);
712 let parent_node_id = self.get_parent_node(node_id);
713 self.node_to_hir_id(parent_node_id)
716 /// Check if the node is an argument. An argument is a local variable whose
717 /// immediate parent is an item or a closure.
718 pub fn is_argument(&self, id: NodeId) -> bool {
719 match self.find(id) {
720 Some(Node::Binding(_)) => (),
723 match self.find(self.get_parent_node(id)) {
724 Some(Node::Item(_)) |
725 Some(Node::TraitItem(_)) |
726 Some(Node::ImplItem(_)) => true,
727 Some(Node::Expr(e)) => {
729 ExprKind::Closure(..) => true,
737 /// If there is some error when walking the parents (e.g., a node does not
738 /// have a parent in the map or a node can't be found), then we return the
739 /// last good `NodeId` we found. Note that reaching the crate root (`id == 0`),
740 /// is not an error, since items in the crate module have the crate root as
742 fn walk_parent_nodes<F, F2>(&self,
746 -> Result<NodeId, NodeId>
747 where F: Fn(&Node<'hir>) -> bool, F2: Fn(&Node<'hir>) -> bool
749 let mut id = start_id;
751 let parent_node = self.get_parent_node(id);
752 if parent_node == CRATE_NODE_ID {
753 return Ok(CRATE_NODE_ID);
755 if parent_node == id {
759 if let Some(entry) = self.find_entry(parent_node) {
760 if let Node::Crate = entry.node {
763 if found(&entry.node) {
764 return Ok(parent_node);
765 } else if bail_early(&entry.node) {
766 return Err(parent_node);
775 /// Retrieves the `NodeId` for `id`'s enclosing method, unless there's a
776 /// `while` or `loop` before reaching it, as block tail returns are not
777 /// available in them.
780 /// fn foo(x: usize) -> bool {
782 /// true // `get_return_block` gets passed the `id` corresponding
783 /// } else { // to this, it will return `foo`'s `NodeId`.
790 /// fn foo(x: usize) -> bool {
792 /// true // `get_return_block` gets passed the `id` corresponding
793 /// } // to this, it will return `None`.
797 pub fn get_return_block(&self, id: NodeId) -> Option<NodeId> {
798 let match_fn = |node: &Node<'_>| {
801 Node::ForeignItem(_) |
803 Node::Expr(Expr { node: ExprKind::Closure(..), ..}) |
804 Node::ImplItem(_) => true,
808 let match_non_returning_block = |node: &Node<'_>| {
810 Node::Expr(ref expr) => {
812 ExprKind::While(..) | ExprKind::Loop(..) | ExprKind::Ret(..) => true,
820 self.walk_parent_nodes(id, match_fn, match_non_returning_block).ok()
823 /// Retrieves the `NodeId` for `id`'s parent item, or `id` itself if no
824 /// parent item is in this map. The "parent item" is the closest parent node
825 /// in the HIR which is recorded by the map and is an item, either an item
826 /// in a module, trait, or impl.
827 pub fn get_parent(&self, id: NodeId) -> NodeId {
828 match self.walk_parent_nodes(id, |node| match *node {
830 Node::ForeignItem(_) |
832 Node::ImplItem(_) => true,
840 // FIXME(@ljedrz): replace the NodeId variant
841 pub fn get_parent_item(&self, id: HirId) -> HirId {
842 let node_id = self.hir_to_node_id(id);
843 let parent_node_id = self.get_parent(node_id);
844 self.node_to_hir_id(parent_node_id)
847 /// Returns the `DefId` of `id`'s nearest module parent, or `id` itself if no
848 /// module parent is in this map.
849 pub fn get_module_parent(&self, id: NodeId) -> DefId {
850 self.local_def_id(self.get_module_parent_node(id))
853 // FIXME(@ljedrz): replace the NodeId variant
854 pub fn get_module_parent_by_hir_id(&self, id: HirId) -> DefId {
855 let node_id = self.hir_to_node_id(id);
856 self.get_module_parent(node_id)
859 /// Returns the `NodeId` of `id`'s nearest module parent, or `id` itself if no
860 /// module parent is in this map.
861 pub fn get_module_parent_node(&self, id: NodeId) -> NodeId {
862 match self.walk_parent_nodes(id, |node| match *node {
863 Node::Item(&Item { node: ItemKind::Mod(_), .. }) => true,
871 /// Returns the nearest enclosing scope. A scope is an item or block.
872 /// FIXME: it is not clear to me that all items qualify as scopes -- statics
873 /// and associated types probably shouldn't, for example. Behavior in this
874 /// regard should be expected to be highly unstable.
875 pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
876 self.walk_parent_nodes(id, |node| match *node {
878 Node::ForeignItem(_) |
881 Node::Block(_) => true,
886 pub fn get_parent_did(&self, id: NodeId) -> DefId {
887 self.local_def_id(self.get_parent(id))
890 // FIXME(@ljedrz): replace the NodeId variant
891 pub fn get_parent_did_by_hir_id(&self, id: HirId) -> DefId {
892 let node_id = self.hir_to_node_id(id);
893 self.get_parent_did(node_id)
896 pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
897 let parent = self.get_parent(id);
898 if let Some(entry) = self.find_entry(parent) {
900 node: Node::Item(Item { node: ItemKind::ForeignMod(ref nm), .. }), .. } = entry
902 self.read(id); // reveals some of the content of a node
906 bug!("expected foreign mod or inlined parent, found {}", self.node_to_string(parent))
909 // FIXME(@ljedrz): replace the NodeId variant
910 pub fn get_foreign_abi_by_hir_id(&self, id: HirId) -> Abi {
911 let node_id = self.hir_to_node_id(id);
912 self.get_foreign_abi(node_id)
915 pub fn expect_item(&self, id: NodeId) -> &'hir Item {
916 match self.find(id) { // read recorded by `find`
917 Some(Node::Item(item)) => item,
918 _ => bug!("expected item, found {}", self.node_to_string(id))
922 // FIXME(@ljedrz): replace the NodeId variant
923 pub fn expect_item_by_hir_id(&self, id: HirId) -> &'hir Item {
924 let node_id = self.hir_to_node_id(id);
925 self.expect_item(node_id)
928 pub fn expect_impl_item(&self, id: NodeId) -> &'hir ImplItem {
929 match self.find(id) {
930 Some(Node::ImplItem(item)) => item,
931 _ => bug!("expected impl item, found {}", self.node_to_string(id))
935 // FIXME(@ljedrz): replace the NodeId variant
936 pub fn expect_impl_item_by_hir_id(&self, id: HirId) -> &'hir ImplItem {
937 let node_id = self.hir_to_node_id(id);
938 self.expect_impl_item(node_id)
941 // FIXME(@ljedrz): replace the NodeId variant
942 pub fn expect_trait_item_by_hir_id(&self, id: HirId) -> &'hir TraitItem {
943 let node_id = self.hir_to_node_id(id);
944 self.expect_trait_item(node_id)
947 pub fn expect_trait_item(&self, id: NodeId) -> &'hir TraitItem {
948 match self.find(id) {
949 Some(Node::TraitItem(item)) => item,
950 _ => bug!("expected trait item, found {}", self.node_to_string(id))
954 pub fn expect_variant_data(&self, id: HirId) -> &'hir VariantData {
955 let id = self.hir_to_node_id(id); // FIXME(@ljedrz): remove when possible
957 match self.find(id) {
958 Some(Node::Item(i)) => {
960 ItemKind::Struct(ref struct_def, _) |
961 ItemKind::Union(ref struct_def, _) => struct_def,
962 _ => bug!("struct ID bound to non-struct {}", self.node_to_string(id))
965 Some(Node::StructCtor(data)) => data,
966 Some(Node::Variant(variant)) => &variant.node.data,
967 _ => bug!("expected struct or variant, found {}", self.node_to_string(id))
971 pub fn expect_variant(&self, id: HirId) -> &'hir Variant {
972 let id = self.hir_to_node_id(id); // FIXME(@ljedrz): remove when possible
974 match self.find(id) {
975 Some(Node::Variant(variant)) => variant,
976 _ => bug!("expected variant, found {}", self.node_to_string(id)),
980 pub fn expect_foreign_item(&self, id: NodeId) -> &'hir ForeignItem {
981 match self.find(id) {
982 Some(Node::ForeignItem(item)) => item,
983 _ => bug!("expected foreign item, found {}", self.node_to_string(id))
987 pub fn expect_expr(&self, id: NodeId) -> &'hir Expr {
988 match self.find(id) { // read recorded by find
989 Some(Node::Expr(expr)) => expr,
990 _ => bug!("expected expr, found {}", self.node_to_string(id))
994 // FIXME(@ljedrz): replace the NodeId variant
995 pub fn expect_expr_by_hir_id(&self, id: HirId) -> &'hir Expr {
996 let node_id = self.hir_to_node_id(id);
997 self.expect_expr(node_id)
1000 /// Returns the name associated with the given NodeId's AST.
1001 pub fn name(&self, id: NodeId) -> Name {
1002 match self.get(id) {
1003 Node::Item(i) => i.ident.name,
1004 Node::ForeignItem(fi) => fi.ident.name,
1005 Node::ImplItem(ii) => ii.ident.name,
1006 Node::TraitItem(ti) => ti.ident.name,
1007 Node::Variant(v) => v.node.ident.name,
1008 Node::Field(f) => f.ident.name,
1009 Node::Lifetime(lt) => lt.name.ident().name,
1010 Node::GenericParam(param) => param.name.ident().name,
1011 Node::Binding(&Pat { node: PatKind::Binding(_, _, _, l, _), .. }) => l.name,
1012 Node::StructCtor(_) => self.name(self.get_parent(id)),
1013 _ => bug!("no name for {}", self.node_to_string(id))
1017 // FIXME(@ljedrz): replace the NodeId variant
1018 pub fn name_by_hir_id(&self, id: HirId) -> Name {
1019 let node_id = self.hir_to_node_id(id);
1023 /// Given a node ID, get a list of attributes associated with the AST
1024 /// corresponding to the Node ID
1025 pub fn attrs(&self, id: NodeId) -> &'hir [ast::Attribute] {
1026 self.read(id); // reveals attributes on the node
1027 let attrs = match self.find(id) {
1028 Some(Node::Item(i)) => Some(&i.attrs[..]),
1029 Some(Node::ForeignItem(fi)) => Some(&fi.attrs[..]),
1030 Some(Node::TraitItem(ref ti)) => Some(&ti.attrs[..]),
1031 Some(Node::ImplItem(ref ii)) => Some(&ii.attrs[..]),
1032 Some(Node::Variant(ref v)) => Some(&v.node.attrs[..]),
1033 Some(Node::Field(ref f)) => Some(&f.attrs[..]),
1034 Some(Node::Expr(ref e)) => Some(&*e.attrs),
1035 Some(Node::Stmt(ref s)) => Some(s.node.attrs()),
1036 Some(Node::GenericParam(param)) => Some(¶m.attrs[..]),
1037 // unit/tuple structs take the attributes straight from
1038 // the struct definition.
1039 Some(Node::StructCtor(_)) => return self.attrs(self.get_parent(id)),
1042 attrs.unwrap_or(&[])
1045 // FIXME(@ljedrz): replace the NodeId variant
1046 pub fn attrs_by_hir_id(&self, id: HirId) -> &'hir [ast::Attribute] {
1047 let node_id = self.hir_to_node_id(id);
1051 /// Returns an iterator that yields the node id's with paths that
1052 /// match `parts`. (Requires `parts` is non-empty.)
1054 /// For example, if given `parts` equal to `["bar", "quux"]`, then
1055 /// the iterator will produce node id's for items with paths
1056 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
1057 /// any other such items it can find in the map.
1058 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
1059 -> NodesMatchingSuffix<'a, 'hir> {
1060 NodesMatchingSuffix {
1062 item_name: parts.last().unwrap(),
1063 in_which: &parts[..parts.len() - 1],
1068 pub fn span(&self, id: NodeId) -> Span {
1069 self.read(id); // reveals span from node
1070 match self.find_entry(id).map(|entry| entry.node) {
1071 Some(Node::Item(item)) => item.span,
1072 Some(Node::ForeignItem(foreign_item)) => foreign_item.span,
1073 Some(Node::TraitItem(trait_method)) => trait_method.span,
1074 Some(Node::ImplItem(impl_item)) => impl_item.span,
1075 Some(Node::Variant(variant)) => variant.span,
1076 Some(Node::Field(field)) => field.span,
1077 Some(Node::AnonConst(constant)) => self.body(constant.body).value.span,
1078 Some(Node::Expr(expr)) => expr.span,
1079 Some(Node::Stmt(stmt)) => stmt.span,
1080 Some(Node::PathSegment(seg)) => seg.ident.span,
1081 Some(Node::Ty(ty)) => ty.span,
1082 Some(Node::TraitRef(tr)) => tr.path.span,
1083 Some(Node::Binding(pat)) => pat.span,
1084 Some(Node::Pat(pat)) => pat.span,
1085 Some(Node::Block(block)) => block.span,
1086 Some(Node::StructCtor(_)) => self.expect_item(self.get_parent(id)).span,
1087 Some(Node::Lifetime(lifetime)) => lifetime.span,
1088 Some(Node::GenericParam(param)) => param.span,
1089 Some(Node::Visibility(&Spanned {
1090 node: VisibilityKind::Restricted { ref path, .. }, ..
1092 Some(Node::Visibility(v)) => bug!("unexpected Visibility {:?}", v),
1093 Some(Node::Local(local)) => local.span,
1094 Some(Node::MacroDef(macro_def)) => macro_def.span,
1095 Some(Node::Crate) => self.forest.krate.span,
1096 None => bug!("hir::map::Map::span: id not in map: {:?}", id),
1100 // FIXME(@ljedrz): replace the NodeId variant
1101 pub fn span_by_hir_id(&self, id: HirId) -> Span {
1102 let node_id = self.hir_to_node_id(id);
1106 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
1107 self.as_local_node_id(id).map(|id| self.span(id))
1110 pub fn node_to_string(&self, id: NodeId) -> String {
1111 node_id_to_string(self, id, true)
1114 // FIXME(@ljedrz): replace the NodeId variant
1115 pub fn hir_to_string(&self, id: HirId) -> String {
1116 hir_id_to_string(self, id, true)
1119 pub fn node_to_user_string(&self, id: NodeId) -> String {
1120 node_id_to_string(self, id, false)
1123 // FIXME(@ljedrz): replace the NodeId variant
1124 pub fn hir_to_user_string(&self, id: HirId) -> String {
1125 hir_id_to_string(self, id, false)
1128 pub fn node_to_pretty_string(&self, id: NodeId) -> String {
1129 print::to_string(self, |s| s.print_node(self.get(id)))
1132 // FIXME(@ljedrz): replace the NodeId variant
1133 pub fn hir_to_pretty_string(&self, id: HirId) -> String {
1134 print::to_string(self, |s| s.print_node(self.get_by_hir_id(id)))
1138 pub struct NodesMatchingSuffix<'a, 'hir:'a> {
1140 item_name: &'a String,
1141 in_which: &'a [String],
1145 impl<'a, 'hir> NodesMatchingSuffix<'a, 'hir> {
1146 /// Returns `true` only if some suffix of the module path for parent
1147 /// matches `self.in_which`.
1149 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
1150 /// returns true if parent's path ends with the suffix
1151 /// `x_0::x_1::...::x_k`.
1152 fn suffix_matches(&self, parent: NodeId) -> bool {
1153 let mut cursor = parent;
1154 for part in self.in_which.iter().rev() {
1155 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
1156 None => return false,
1157 Some((node_id, name)) => (node_id, name),
1159 if mod_name != &**part {
1162 cursor = self.map.get_parent(mod_id);
1166 // Finds the first mod in parent chain for `id`, along with
1169 // If `id` itself is a mod named `m` with parent `p`, then
1170 // returns `Some(id, m, p)`. If `id` has no mod in its parent
1171 // chain, then returns `None`.
1172 fn find_first_mod_parent<'a>(map: &'a Map<'_>, mut id: NodeId) -> Option<(NodeId, Name)> {
1174 if let Node::Item(item) = map.find(id)? {
1175 if item_is_mod(&item) {
1176 return Some((id, item.ident.name))
1179 let parent = map.get_parent(id);
1180 if parent == id { return None }
1184 fn item_is_mod(item: &Item) -> bool {
1186 ItemKind::Mod(_) => true,
1193 // We are looking at some node `n` with a given name and parent
1194 // id; do their names match what I am seeking?
1195 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
1196 name == &**self.item_name && self.suffix_matches(parent_of_n)
1200 impl<'a, 'hir> Iterator for NodesMatchingSuffix<'a, 'hir> {
1203 fn next(&mut self) -> Option<NodeId> {
1206 if idx.as_usize() >= self.map.entry_count() {
1209 self.idx = NodeId::from_u32(self.idx.as_u32() + 1);
1210 let name = match self.map.find_entry(idx).map(|entry| entry.node) {
1211 Some(Node::Item(n)) => n.name(),
1212 Some(Node::ForeignItem(n)) => n.name(),
1213 Some(Node::TraitItem(n)) => n.name(),
1214 Some(Node::ImplItem(n)) => n.name(),
1215 Some(Node::Variant(n)) => n.name(),
1216 Some(Node::Field(n)) => n.name(),
1219 if self.matches_names(self.map.get_parent(idx), name) {
1227 fn name(&self) -> Name;
1230 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
1232 impl Named for Item { fn name(&self) -> Name { self.ident.name } }
1233 impl Named for ForeignItem { fn name(&self) -> Name { self.ident.name } }
1234 impl Named for VariantKind { fn name(&self) -> Name { self.ident.name } }
1235 impl Named for StructField { fn name(&self) -> Name { self.ident.name } }
1236 impl Named for TraitItem { fn name(&self) -> Name { self.ident.name } }
1237 impl Named for ImplItem { fn name(&self) -> Name { self.ident.name } }
1239 pub fn map_crate<'hir>(sess: &crate::session::Session,
1240 cstore: &CrateStoreDyn,
1241 forest: &'hir Forest,
1242 definitions: &'hir Definitions)
1244 let ((map, crate_hash), hir_to_node_id) = join(|| {
1245 let hcx = crate::ich::StableHashingContext::new(sess, &forest.krate, definitions, cstore);
1247 let mut collector = NodeCollector::root(sess,
1252 intravisit::walk_crate(&mut collector, &forest.krate);
1254 let crate_disambiguator = sess.local_crate_disambiguator();
1255 let cmdline_args = sess.opts.dep_tracking_hash();
1256 collector.finalize_and_compute_crate_hash(
1257 crate_disambiguator,
1262 // Build the reverse mapping of `node_to_hir_id`.
1263 definitions.node_to_hir_id.iter_enumerated()
1264 .map(|(node_id, &hir_id)| (hir_id, node_id)).collect()
1267 if log_enabled!(::log::Level::Debug) {
1268 // This only makes sense for ordered stores; note the
1269 // enumerate to count the number of entries.
1270 let (entries_less_1, _) = map.iter().filter_map(|x| *x).enumerate().last()
1271 .expect("AST map was empty after folding?");
1273 let entries = entries_less_1 + 1;
1274 let vector_length = map.len();
1275 debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
1276 entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
1281 dep_graph: forest.dep_graph.clone(),
1288 time(sess, "validate hir map", || {
1289 hir_id_validator::check_crate(&map);
1295 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1296 /// except it avoids creating a dependency on the whole crate.
1297 impl<'hir> print::PpAnn for Map<'hir> {
1298 fn nested(&self, state: &mut print::State<'_>, nested: print::Nested) -> io::Result<()> {
1300 Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1301 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1302 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1303 Nested::Body(id) => state.print_expr(&self.body(id).value),
1304 Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
1309 impl<'a> print::State<'a> {
1310 pub fn print_node(&mut self, node: Node<'_>) -> io::Result<()> {
1312 Node::Item(a) => self.print_item(&a),
1313 Node::ForeignItem(a) => self.print_foreign_item(&a),
1314 Node::TraitItem(a) => self.print_trait_item(a),
1315 Node::ImplItem(a) => self.print_impl_item(a),
1316 Node::Variant(a) => self.print_variant(&a),
1317 Node::AnonConst(a) => self.print_anon_const(&a),
1318 Node::Expr(a) => self.print_expr(&a),
1319 Node::Stmt(a) => self.print_stmt(&a),
1320 Node::PathSegment(a) => self.print_path_segment(&a),
1321 Node::Ty(a) => self.print_type(&a),
1322 Node::TraitRef(a) => self.print_trait_ref(&a),
1324 Node::Pat(a) => self.print_pat(&a),
1326 use syntax::print::pprust::PrintState;
1328 // containing cbox, will be closed by print-block at }
1329 self.cbox(print::indent_unit)?;
1330 // head-ibox, will be closed by print-block after {
1332 self.print_block(&a)
1334 Node::Lifetime(a) => self.print_lifetime(&a),
1335 Node::Visibility(a) => self.print_visibility(&a),
1336 Node::GenericParam(_) => bug!("cannot print Node::GenericParam"),
1337 Node::Field(_) => bug!("cannot print StructField"),
1338 // these cases do not carry enough information in the
1339 // hir_map to reconstruct their full structure for pretty
1341 Node::StructCtor(_) => bug!("cannot print isolated StructCtor"),
1342 Node::Local(a) => self.print_local_decl(&a),
1343 Node::MacroDef(_) => bug!("cannot print MacroDef"),
1344 Node::Crate => bug!("cannot print Crate"),
1349 fn node_id_to_string(map: &Map<'_>, id: NodeId, include_id: bool) -> String {
1350 let id_str = format!(" (id={})", id);
1351 let id_str = if include_id { &id_str[..] } else { "" };
1354 // This functionality is used for debugging, try to use TyCtxt to get
1355 // the user-friendly path, otherwise fall back to stringifying DefPath.
1356 crate::ty::tls::with_opt(|tcx| {
1357 if let Some(tcx) = tcx {
1358 tcx.node_path_str(id)
1359 } else if let Some(path) = map.def_path_from_id(id) {
1360 path.data.into_iter().map(|elem| {
1361 elem.data.to_string()
1362 }).collect::<Vec<_>>().join("::")
1364 String::from("<missing path>")
1369 match map.find(id) {
1370 Some(Node::Item(item)) => {
1371 let item_str = match item.node {
1372 ItemKind::ExternCrate(..) => "extern crate",
1373 ItemKind::Use(..) => "use",
1374 ItemKind::Static(..) => "static",
1375 ItemKind::Const(..) => "const",
1376 ItemKind::Fn(..) => "fn",
1377 ItemKind::Mod(..) => "mod",
1378 ItemKind::ForeignMod(..) => "foreign mod",
1379 ItemKind::GlobalAsm(..) => "global asm",
1380 ItemKind::Ty(..) => "ty",
1381 ItemKind::Existential(..) => "existential type",
1382 ItemKind::Enum(..) => "enum",
1383 ItemKind::Struct(..) => "struct",
1384 ItemKind::Union(..) => "union",
1385 ItemKind::Trait(..) => "trait",
1386 ItemKind::TraitAlias(..) => "trait alias",
1387 ItemKind::Impl(..) => "impl",
1389 format!("{} {}{}", item_str, path_str(), id_str)
1391 Some(Node::ForeignItem(_)) => {
1392 format!("foreign item {}{}", path_str(), id_str)
1394 Some(Node::ImplItem(ii)) => {
1396 ImplItemKind::Const(..) => {
1397 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1399 ImplItemKind::Method(..) => {
1400 format!("method {} in {}{}", ii.ident, path_str(), id_str)
1402 ImplItemKind::Type(_) => {
1403 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1405 ImplItemKind::Existential(_) => {
1406 format!("assoc existential type {} in {}{}", ii.ident, path_str(), id_str)
1410 Some(Node::TraitItem(ti)) => {
1411 let kind = match ti.node {
1412 TraitItemKind::Const(..) => "assoc constant",
1413 TraitItemKind::Method(..) => "trait method",
1414 TraitItemKind::Type(..) => "assoc type",
1417 format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1419 Some(Node::Variant(ref variant)) => {
1420 format!("variant {} in {}{}",
1424 Some(Node::Field(ref field)) => {
1425 format!("field {} in {}{}",
1429 Some(Node::AnonConst(_)) => {
1430 format!("const {}{}", map.node_to_pretty_string(id), id_str)
1432 Some(Node::Expr(_)) => {
1433 format!("expr {}{}", map.node_to_pretty_string(id), id_str)
1435 Some(Node::Stmt(_)) => {
1436 format!("stmt {}{}", map.node_to_pretty_string(id), id_str)
1438 Some(Node::PathSegment(_)) => {
1439 format!("path segment {}{}", map.node_to_pretty_string(id), id_str)
1441 Some(Node::Ty(_)) => {
1442 format!("type {}{}", map.node_to_pretty_string(id), id_str)
1444 Some(Node::TraitRef(_)) => {
1445 format!("trait_ref {}{}", map.node_to_pretty_string(id), id_str)
1447 Some(Node::Binding(_)) => {
1448 format!("local {}{}", map.node_to_pretty_string(id), id_str)
1450 Some(Node::Pat(_)) => {
1451 format!("pat {}{}", map.node_to_pretty_string(id), id_str)
1453 Some(Node::Block(_)) => {
1454 format!("block {}{}", map.node_to_pretty_string(id), id_str)
1456 Some(Node::Local(_)) => {
1457 format!("local {}{}", map.node_to_pretty_string(id), id_str)
1459 Some(Node::StructCtor(_)) => {
1460 format!("struct_ctor {}{}", path_str(), id_str)
1462 Some(Node::Lifetime(_)) => {
1463 format!("lifetime {}{}", map.node_to_pretty_string(id), id_str)
1465 Some(Node::GenericParam(ref param)) => {
1466 format!("generic_param {:?}{}", param, id_str)
1468 Some(Node::Visibility(ref vis)) => {
1469 format!("visibility {:?}{}", vis, id_str)
1471 Some(Node::MacroDef(_)) => {
1472 format!("macro {}{}", path_str(), id_str)
1474 Some(Node::Crate) => String::from("root_crate"),
1475 None => format!("unknown node{}", id_str),
1479 // FIXME(@ljedrz): replace the NodeId variant
1480 fn hir_id_to_string(map: &Map<'_>, id: HirId, include_id: bool) -> String {
1481 let node_id = map.hir_to_node_id(id);
1482 node_id_to_string(map, node_id, include_id)
1485 pub fn describe_def(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> Option<Def> {
1486 if let Some(node_id) = tcx.hir().as_local_node_id(def_id) {
1487 tcx.hir().describe_def(node_id)
1489 bug!("Calling local describe_def query provider for upstream DefId: {:?}",