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 syntax::ast::{self, Name, NodeId, CRATE_NODE_ID};
15 use syntax::source_map::Spanned;
16 use syntax::ext::base::MacroKind;
17 use syntax_pos::{Span, DUMMY_SP};
20 use crate::hir::itemlikevisit::ItemLikeVisitor;
21 use crate::hir::print::Nested;
22 use crate::util::nodemap::FxHashMap;
23 use crate::util::common::time;
26 use std::result::Result::Err;
27 use crate::ty::TyCtxt;
35 pub const ITEM_LIKE_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::Low;
36 pub const REGULAR_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::High;
38 /// Represents an entry and its parent `NodeId`.
39 #[derive(Copy, Clone, Debug)]
40 pub struct Entry<'hir> {
43 dep_node: DepNodeIndex,
47 impl<'hir> Entry<'hir> {
48 fn parent_node(self) -> Option<NodeId> {
50 Node::Crate | Node::MacroDef(_) => None,
51 _ => Some(self.parent),
55 fn fn_decl(&self) -> Option<&FnDecl> {
57 Node::Item(ref item) => {
59 ItemKind::Fn(ref fn_decl, _, _, _) => Some(&fn_decl),
64 Node::TraitItem(ref item) => {
66 TraitItemKind::Method(ref method_sig, _) => Some(&method_sig.decl),
71 Node::ImplItem(ref item) => {
73 ImplItemKind::Method(ref method_sig, _) => Some(&method_sig.decl),
78 Node::Expr(ref expr) => {
80 ExprKind::Closure(_, ref fn_decl, ..) => Some(&fn_decl),
89 fn associated_body(self) -> Option<BodyId> {
93 ItemKind::Const(_, body) |
94 ItemKind::Static(.., body) |
95 ItemKind::Fn(_, _, _, body) => Some(body),
100 Node::TraitItem(item) => {
102 TraitItemKind::Const(_, Some(body)) |
103 TraitItemKind::Method(_, TraitMethod::Provided(body)) => Some(body),
108 Node::ImplItem(item) => {
110 ImplItemKind::Const(_, body) |
111 ImplItemKind::Method(_, body) => Some(body),
116 Node::AnonConst(constant) => Some(constant.body),
118 Node::Expr(expr) => {
120 ExprKind::Closure(.., body, _, _) => Some(body),
129 fn is_body_owner(self, hir_id: HirId) -> bool {
130 match self.associated_body() {
131 Some(b) => b.hir_id == hir_id,
137 /// Stores a crate and any number of inlined items from other crates.
140 pub dep_graph: DepGraph,
144 pub fn new(krate: Crate, dep_graph: &DepGraph) -> Forest {
147 dep_graph: dep_graph.clone(),
151 pub fn krate<'hir>(&'hir self) -> &'hir Crate {
152 self.dep_graph.read(DepNode::new_no_params(DepKind::Krate));
156 /// This is internally in the depedency tracking system.
157 /// Use the `krate` method to ensure your dependency on the
158 /// crate is tracked.
159 pub fn untracked_krate<'hir>(&'hir self) -> &'hir Crate {
164 /// Represents a mapping from `NodeId`s to AST elements and their parent `NodeId`s.
166 pub struct Map<'hir> {
167 /// The backing storage for all the AST nodes.
168 pub forest: &'hir Forest,
170 /// Same as the dep_graph in forest, just available with one fewer
171 /// deref. This is a gratuitous micro-optimization.
172 pub dep_graph: DepGraph,
174 /// The SVH of the local crate.
177 /// `NodeId`s are sequential integers from 0, so we can be
178 /// super-compact by storing them in a vector. Not everything with
179 /// a `NodeId` is in the map, but empirically the occupancy is about
180 /// 75-80%, so there's not too much overhead (certainly less than
181 /// a hashmap, since they (at the time of writing) have a maximum
182 /// of 75% occupancy).
184 /// Also, indexing is pretty quick when you've got a vector and
185 /// plain old integers.
186 map: Vec<Option<Entry<'hir>>>,
188 definitions: &'hir Definitions,
190 /// The reverse mapping of `node_to_hir_id`.
191 hir_to_node_id: FxHashMap<HirId, NodeId>,
194 impl<'hir> Map<'hir> {
195 /// Registers a read in the dependency graph of the AST node with
196 /// the given `id`. This needs to be called each time a public
197 /// function returns the HIR for a node -- in other words, when it
198 /// "reveals" the content of a node to the caller (who might not
199 /// otherwise have had access to those contents, and hence needs a
200 /// read recorded). If the function just returns a DefId or
201 /// NodeId, no actual content was returned, so no read is needed.
202 pub fn read(&self, id: NodeId) {
203 if let Some(entry) = self.map[id.as_usize()] {
204 self.dep_graph.read_index(entry.dep_node);
206 bug!("called `HirMap::read()` with invalid `NodeId`: {:?}", id)
210 // FIXME(@ljedrz): replace the NodeId variant
211 pub fn read_by_hir_id(&self, hir_id: HirId) {
212 let node_id = self.hir_to_node_id(hir_id);
217 pub fn definitions(&self) -> &'hir Definitions {
221 pub fn def_key(&self, def_id: DefId) -> DefKey {
222 assert!(def_id.is_local());
223 self.definitions.def_key(def_id.index)
226 pub fn def_path_from_id(&self, id: NodeId) -> Option<DefPath> {
227 self.opt_local_def_id(id).map(|def_id| {
228 self.def_path(def_id)
232 // FIXME(@ljedrz): replace the NodeId variant
233 pub fn def_path_from_hir_id(&self, id: HirId) -> DefPath {
234 self.def_path(self.local_def_id_from_hir_id(id))
237 pub fn def_path(&self, def_id: DefId) -> DefPath {
238 assert!(def_id.is_local());
239 self.definitions.def_path(def_id.index)
243 pub fn local_def_id(&self, node: NodeId) -> DefId {
244 self.opt_local_def_id(node).unwrap_or_else(|| {
245 bug!("local_def_id: no entry for `{}`, which has a map of `{:?}`",
246 node, self.find_entry(node))
250 // FIXME(@ljedrz): replace the NodeId variant
252 pub fn local_def_id_from_hir_id(&self, hir_id: HirId) -> DefId {
253 let node_id = self.hir_to_node_id(hir_id);
254 self.opt_local_def_id(node_id).unwrap_or_else(|| {
255 bug!("local_def_id_from_hir_id: no entry for `{:?}`, which has a map of `{:?}`",
256 hir_id, self.find_entry(node_id))
260 // FIXME(@ljedrz): replace the NodeId variant
262 pub fn opt_local_def_id_from_hir_id(&self, hir_id: HirId) -> Option<DefId> {
263 let node_id = self.hir_to_node_id(hir_id);
264 self.definitions.opt_local_def_id(node_id)
268 pub fn opt_local_def_id(&self, node: NodeId) -> Option<DefId> {
269 self.definitions.opt_local_def_id(node)
273 pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
274 self.definitions.as_local_node_id(def_id)
277 // FIXME(@ljedrz): replace the NodeId variant
279 pub fn as_local_hir_id(&self, def_id: DefId) -> Option<HirId> {
280 self.definitions.as_local_hir_id(def_id)
284 pub fn hir_to_node_id(&self, hir_id: HirId) -> NodeId {
285 self.hir_to_node_id[&hir_id]
289 pub fn node_to_hir_id(&self, node_id: NodeId) -> HirId {
290 self.definitions.node_to_hir_id(node_id)
294 pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> HirId {
295 self.definitions.def_index_to_hir_id(def_index)
299 pub fn def_index_to_node_id(&self, def_index: DefIndex) -> NodeId {
300 self.definitions.as_local_node_id(DefId::local(def_index)).unwrap()
304 pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
305 self.definitions.def_index_to_hir_id(def_id.to_def_id().index)
309 pub fn local_def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
310 self.definitions.as_local_node_id(def_id.to_def_id()).unwrap()
313 pub fn describe_def(&self, node_id: NodeId) -> Option<Def> {
314 let node = if let Some(node) = self.find(node_id) {
321 Node::Item(item) => {
322 let def_id = || self.local_def_id_from_hir_id(item.hir_id);
325 ItemKind::Static(_, m, _) => Some(Def::Static(def_id(), m == MutMutable)),
326 ItemKind::Const(..) => Some(Def::Const(def_id())),
327 ItemKind::Fn(..) => Some(Def::Fn(def_id())),
328 ItemKind::Mod(..) => Some(Def::Mod(def_id())),
329 ItemKind::Existential(..) => Some(Def::Existential(def_id())),
330 ItemKind::Ty(..) => Some(Def::TyAlias(def_id())),
331 ItemKind::Enum(..) => Some(Def::Enum(def_id())),
332 ItemKind::Struct(..) => Some(Def::Struct(def_id())),
333 ItemKind::Union(..) => Some(Def::Union(def_id())),
334 ItemKind::Trait(..) => Some(Def::Trait(def_id())),
335 ItemKind::TraitAlias(..) => Some(Def::TraitAlias(def_id())),
336 ItemKind::ExternCrate(_) |
338 ItemKind::ForeignMod(..) |
339 ItemKind::GlobalAsm(..) |
340 ItemKind::Impl(..) => None,
343 Node::ForeignItem(item) => {
344 let def_id = self.local_def_id_from_hir_id(item.hir_id);
346 ForeignItemKind::Fn(..) => Some(Def::Fn(def_id)),
347 ForeignItemKind::Static(_, m) => Some(Def::Static(def_id, m)),
348 ForeignItemKind::Type => Some(Def::ForeignTy(def_id)),
351 Node::TraitItem(item) => {
352 let def_id = self.local_def_id_from_hir_id(item.hir_id);
354 TraitItemKind::Const(..) => Some(Def::AssociatedConst(def_id)),
355 TraitItemKind::Method(..) => Some(Def::Method(def_id)),
356 TraitItemKind::Type(..) => Some(Def::AssociatedTy(def_id)),
359 Node::ImplItem(item) => {
360 let def_id = self.local_def_id_from_hir_id(item.hir_id);
362 ImplItemKind::Const(..) => Some(Def::AssociatedConst(def_id)),
363 ImplItemKind::Method(..) => Some(Def::Method(def_id)),
364 ImplItemKind::Type(..) => Some(Def::AssociatedTy(def_id)),
365 ImplItemKind::Existential(..) => Some(Def::AssociatedExistential(def_id)),
368 Node::Variant(variant) => {
369 let def_id = self.local_def_id_from_hir_id(variant.node.data.hir_id());
370 Some(Def::Variant(def_id))
372 Node::StructCtor(variant) => {
373 let def_id = self.local_def_id_from_hir_id(variant.hir_id());
374 Some(Def::StructCtor(def_id, def::CtorKind::from_hir(variant)))
380 Node::PathSegment(_) |
386 Node::Visibility(_) |
389 Node::Local(local) => {
390 Some(Def::Local(self.hir_to_node_id(local.hir_id)))
392 Node::MacroDef(macro_def) => {
393 Some(Def::Macro(self.local_def_id_from_hir_id(macro_def.hir_id),
396 Node::GenericParam(param) => {
397 Some(match param.kind {
398 GenericParamKind::Lifetime { .. } => {
399 let node_id = self.hir_to_node_id(param.hir_id);
402 GenericParamKind::Type { .. } => Def::TyParam(
403 self.local_def_id_from_hir_id(param.hir_id)),
404 GenericParamKind::Const { .. } => Def::ConstParam(
405 self.local_def_id_from_hir_id(param.hir_id)),
411 // FIXME(@ljedrz): replace the NodeId variant
412 pub fn describe_def_by_hir_id(&self, hir_id: HirId) -> Option<Def> {
413 let node_id = self.hir_to_node_id(hir_id);
414 self.describe_def(node_id)
417 fn entry_count(&self) -> usize {
421 fn find_entry(&self, id: NodeId) -> Option<Entry<'hir>> {
422 self.map.get(id.as_usize()).cloned().unwrap_or(None)
425 pub fn krate(&self) -> &'hir Crate {
429 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem {
430 self.read_by_hir_id(id.hir_id);
432 // N.B., intentionally bypass `self.forest.krate()` so that we
433 // do not trigger a read of the whole krate here
434 self.forest.krate.trait_item(id)
437 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem {
438 self.read_by_hir_id(id.hir_id);
440 // N.B., intentionally bypass `self.forest.krate()` so that we
441 // do not trigger a read of the whole krate here
442 self.forest.krate.impl_item(id)
445 pub fn body(&self, id: BodyId) -> &'hir Body {
446 self.read_by_hir_id(id.hir_id);
448 // N.B., intentionally bypass `self.forest.krate()` so that we
449 // do not trigger a read of the whole krate here
450 self.forest.krate.body(id)
453 pub fn fn_decl(&self, node_id: ast::NodeId) -> Option<FnDecl> {
454 if let Some(entry) = self.find_entry(node_id) {
455 entry.fn_decl().cloned()
457 bug!("no entry for node_id `{}`", node_id)
461 // FIXME(@ljedrz): replace the NodeId variant
462 pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<FnDecl> {
463 let node_id = self.hir_to_node_id(hir_id);
464 self.fn_decl(node_id)
467 /// Returns the `NodeId` that corresponds to the definition of
468 /// which this is the body of, i.e., a `fn`, `const` or `static`
469 /// item (possibly associated), a closure, or a `hir::AnonConst`.
470 pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> NodeId {
471 let node_id = self.hir_to_node_id(hir_id);
472 let parent = self.get_parent_node(node_id);
473 assert!(self.map[parent.as_usize()].map_or(false, |e| e.is_body_owner(hir_id)));
477 pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
478 self.local_def_id(self.body_owner(id))
481 /// Given a `NodeId`, returns the `BodyId` associated with it,
482 /// if the node is a body owner, otherwise returns `None`.
483 pub fn maybe_body_owned_by(&self, id: NodeId) -> Option<BodyId> {
484 if let Some(entry) = self.find_entry(id) {
485 if self.dep_graph.is_fully_enabled() {
486 let hir_id_owner = self.node_to_hir_id(id).owner;
487 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
488 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
491 entry.associated_body()
493 bug!("no entry for id `{}`", id)
497 // FIXME(@ljedrz): replace the NodeId variant
498 pub fn maybe_body_owned_by_by_hir_id(&self, id: HirId) -> Option<BodyId> {
499 let node_id = self.hir_to_node_id(id);
500 self.maybe_body_owned_by(node_id)
503 /// Given a body owner's id, returns the `BodyId` associated with it.
504 pub fn body_owned_by(&self, id: HirId) -> BodyId {
505 self.maybe_body_owned_by_by_hir_id(id).unwrap_or_else(|| {
506 span_bug!(self.span_by_hir_id(id), "body_owned_by: {} has no associated body",
507 self.hir_to_string(id));
511 pub fn body_owner_kind(&self, id: NodeId) -> BodyOwnerKind {
513 Node::Item(&Item { node: ItemKind::Const(..), .. }) |
514 Node::TraitItem(&TraitItem { node: TraitItemKind::Const(..), .. }) |
515 Node::ImplItem(&ImplItem { node: ImplItemKind::Const(..), .. }) |
516 Node::AnonConst(_) => {
519 Node::Variant(&Spanned { node: VariantKind { data: VariantData::Tuple(..), .. }, .. }) |
520 Node::StructCtor(..) |
521 Node::Item(&Item { node: ItemKind::Fn(..), .. }) |
522 Node::TraitItem(&TraitItem { node: TraitItemKind::Method(..), .. }) |
523 Node::ImplItem(&ImplItem { node: ImplItemKind::Method(..), .. }) => {
526 Node::Item(&Item { node: ItemKind::Static(_, m, _), .. }) => {
527 BodyOwnerKind::Static(m)
529 Node::Expr(&Expr { node: ExprKind::Closure(..), .. }) => {
530 BodyOwnerKind::Closure
532 node => bug!("{:#?} is not a body node", node),
536 // FIXME(@ljedrz): replace the NodeId variant
537 pub fn body_owner_kind_by_hir_id(&self, id: HirId) -> BodyOwnerKind {
538 let node_id = self.hir_to_node_id(id);
539 self.body_owner_kind(node_id)
542 pub fn ty_param_owner(&self, id: HirId) -> HirId {
543 match self.get_by_hir_id(id) {
544 Node::Item(&Item { node: ItemKind::Trait(..), .. }) |
545 Node::Item(&Item { node: ItemKind::TraitAlias(..), .. }) => id,
546 Node::GenericParam(_) => self.get_parent_node_by_hir_id(id),
547 _ => bug!("ty_param_owner: {} not a type parameter", self.hir_to_string(id))
551 pub fn ty_param_name(&self, id: HirId) -> Name {
552 match self.get_by_hir_id(id) {
553 Node::Item(&Item { node: ItemKind::Trait(..), .. }) |
554 Node::Item(&Item { node: ItemKind::TraitAlias(..), .. }) => keywords::SelfUpper.name(),
555 Node::GenericParam(param) => param.name.ident().name,
556 _ => bug!("ty_param_name: {} not a type parameter", self.hir_to_string(id)),
560 pub fn trait_impls(&self, trait_did: DefId) -> &'hir [HirId] {
561 self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
563 // N.B., intentionally bypass `self.forest.krate()` so that we
564 // do not trigger a read of the whole krate here
565 self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
568 /// Gets the attributes on the crate. This is preferable to
569 /// invoking `krate.attrs` because it registers a tighter
570 /// dep-graph access.
571 pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
572 let def_path_hash = self.definitions.def_path_hash(CRATE_DEF_INDEX);
574 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::Hir));
575 &self.forest.krate.attrs
578 pub fn get_module(&self, module: DefId) -> (&'hir Mod, Span, NodeId)
580 let node_id = self.as_local_node_id(module).unwrap();
582 match self.find_entry(node_id).unwrap().node {
585 node: ItemKind::Mod(ref m),
587 }) => (m, span, node_id),
588 Node::Crate => (&self.forest.krate.module, self.forest.krate.span, node_id),
589 _ => panic!("not a module")
593 pub fn visit_item_likes_in_module<V>(&self, module: DefId, visitor: &mut V)
594 where V: ItemLikeVisitor<'hir>
596 let node_id = self.as_local_node_id(module).unwrap();
598 // Read the module so we'll be re-executed if new items
599 // appear immediately under in the module. If some new item appears
600 // in some nested item in the module, we'll be re-executed due to reads
601 // in the expect_* calls the loops below
604 let module = &self.forest.krate.modules[&node_id];
606 for id in &module.items {
607 visitor.visit_item(self.expect_item(*id));
610 for id in &module.trait_items {
611 visitor.visit_trait_item(self.expect_trait_item(id.hir_id));
614 for id in &module.impl_items {
615 visitor.visit_impl_item(self.expect_impl_item(id.hir_id));
619 /// Retrieve the Node corresponding to `id`, panicking if it cannot
621 pub fn get(&self, id: NodeId) -> Node<'hir> {
622 // read recorded by `find`
623 self.find(id).unwrap_or_else(|| bug!("couldn't find node id {} in the AST map", id))
626 // FIXME(@ljedrz): replace the NodeId variant
627 pub fn get_by_hir_id(&self, id: HirId) -> Node<'hir> {
628 let node_id = self.hir_to_node_id(id);
632 pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
633 self.as_local_node_id(id).map(|id| self.get(id)) // read recorded by `get`
636 pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics> {
637 self.get_if_local(id).and_then(|node| {
639 Node::ImplItem(ref impl_item) => Some(&impl_item.generics),
640 Node::TraitItem(ref trait_item) => Some(&trait_item.generics),
641 Node::Item(ref item) => {
643 ItemKind::Fn(_, _, ref generics, _) |
644 ItemKind::Ty(_, ref generics) |
645 ItemKind::Enum(_, ref generics) |
646 ItemKind::Struct(_, ref generics) |
647 ItemKind::Union(_, ref generics) |
648 ItemKind::Trait(_, _, ref generics, ..) |
649 ItemKind::TraitAlias(ref generics, _) |
650 ItemKind::Impl(_, _, _, ref generics, ..) => Some(generics),
659 pub fn get_generics_span(&self, id: DefId) -> Option<Span> {
660 self.get_generics(id).map(|generics| generics.span).filter(|sp| *sp != DUMMY_SP)
663 /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
664 pub fn find(&self, id: NodeId) -> Option<Node<'hir>> {
665 let result = self.find_entry(id).and_then(|entry| {
666 if let Node::Crate = entry.node {
672 if result.is_some() {
678 // FIXME(@ljedrz): replace the NodeId variant
679 pub fn find_by_hir_id(&self, hir_id: HirId) -> Option<Node<'hir>> {
680 let node_id = self.hir_to_node_id(hir_id);
684 /// Similar to `get_parent`; returns the parent node-id, or own `id` if there is
685 /// no parent. Note that the parent may be `CRATE_NODE_ID`, which is not itself
686 /// present in the map -- so passing the return value of get_parent_node to
687 /// get may actually panic.
688 /// This function returns the immediate parent in the AST, whereas get_parent
689 /// returns the enclosing item. Note that this might not be the actual parent
690 /// node in the AST - some kinds of nodes are not in the map and these will
691 /// never appear as the parent_node. So you can always walk the `parent_nodes`
692 /// from a node to the root of the ast (unless you get the same ID back here
693 /// that can happen if the ID is not in the map itself or is just weird).
694 pub fn get_parent_node(&self, id: NodeId) -> NodeId {
695 if self.dep_graph.is_fully_enabled() {
696 let hir_id_owner = self.node_to_hir_id(id).owner;
697 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
698 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
701 self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
704 // FIXME(@ljedrz): replace the NodeId variant
705 pub fn get_parent_node_by_hir_id(&self, id: HirId) -> HirId {
706 let node_id = self.hir_to_node_id(id);
707 let parent_node_id = self.get_parent_node(node_id);
708 self.node_to_hir_id(parent_node_id)
711 /// Check if the node is an argument. An argument is a local variable whose
712 /// immediate parent is an item or a closure.
713 pub fn is_argument(&self, id: NodeId) -> bool {
714 match self.find(id) {
715 Some(Node::Binding(_)) => (),
718 match self.find(self.get_parent_node(id)) {
719 Some(Node::Item(_)) |
720 Some(Node::TraitItem(_)) |
721 Some(Node::ImplItem(_)) => true,
722 Some(Node::Expr(e)) => {
724 ExprKind::Closure(..) => true,
732 /// If there is some error when walking the parents (e.g., a node does not
733 /// have a parent in the map or a node can't be found), then we return the
734 /// last good `NodeId` we found. Note that reaching the crate root (`id == 0`),
735 /// is not an error, since items in the crate module have the crate root as
737 fn walk_parent_nodes<F, F2>(&self,
741 -> Result<NodeId, NodeId>
742 where F: Fn(&Node<'hir>) -> bool, F2: Fn(&Node<'hir>) -> bool
744 let mut id = start_id;
746 let parent_node = self.get_parent_node(id);
747 if parent_node == CRATE_NODE_ID {
748 return Ok(CRATE_NODE_ID);
750 if parent_node == id {
754 if let Some(entry) = self.find_entry(parent_node) {
755 if let Node::Crate = entry.node {
758 if found(&entry.node) {
759 return Ok(parent_node);
760 } else if bail_early(&entry.node) {
761 return Err(parent_node);
770 /// Retrieves the `NodeId` for `id`'s enclosing method, unless there's a
771 /// `while` or `loop` before reaching it, as block tail returns are not
772 /// available in them.
775 /// fn foo(x: usize) -> bool {
777 /// true // `get_return_block` gets passed the `id` corresponding
778 /// } else { // to this, it will return `foo`'s `NodeId`.
785 /// fn foo(x: usize) -> bool {
787 /// true // `get_return_block` gets passed the `id` corresponding
788 /// } // to this, it will return `None`.
792 pub fn get_return_block(&self, id: HirId) -> Option<HirId> {
793 let match_fn = |node: &Node<'_>| {
796 Node::ForeignItem(_) |
798 Node::Expr(Expr { node: ExprKind::Closure(..), ..}) |
799 Node::ImplItem(_) => true,
803 let match_non_returning_block = |node: &Node<'_>| {
805 Node::Expr(ref expr) => {
807 ExprKind::While(..) | ExprKind::Loop(..) | ExprKind::Ret(..) => true,
815 let node_id = self.hir_to_node_id(id);
816 self.walk_parent_nodes(node_id, match_fn, match_non_returning_block)
818 .map(|return_node_id| self.node_to_hir_id(return_node_id))
821 /// Retrieves the `NodeId` for `id`'s parent item, or `id` itself if no
822 /// parent item is in this map. The "parent item" is the closest parent node
823 /// in the HIR which is recorded by the map and is an item, either an item
824 /// in a module, trait, or impl.
825 pub fn get_parent(&self, id: NodeId) -> NodeId {
826 match self.walk_parent_nodes(id, |node| match *node {
828 Node::ForeignItem(_) |
830 Node::ImplItem(_) => true,
838 // FIXME(@ljedrz): replace the NodeId variant
839 pub fn get_parent_item(&self, id: HirId) -> HirId {
840 let node_id = self.hir_to_node_id(id);
841 let parent_node_id = self.get_parent(node_id);
842 self.node_to_hir_id(parent_node_id)
845 /// Returns the `DefId` of `id`'s nearest module parent, or `id` itself if no
846 /// module parent is in this map.
847 pub fn get_module_parent(&self, id: NodeId) -> DefId {
848 self.local_def_id(self.get_module_parent_node(id))
851 // FIXME(@ljedrz): replace the NodeId variant
852 pub fn get_module_parent_by_hir_id(&self, id: HirId) -> DefId {
853 let node_id = self.hir_to_node_id(id);
854 self.get_module_parent(node_id)
857 /// Returns the `NodeId` of `id`'s nearest module parent, or `id` itself if no
858 /// module parent is in this map.
859 pub fn get_module_parent_node(&self, id: NodeId) -> NodeId {
860 match self.walk_parent_nodes(id, |node| match *node {
861 Node::Item(&Item { node: ItemKind::Mod(_), .. }) => true,
869 /// Returns the nearest enclosing scope. A scope is an item or block.
870 /// FIXME: it is not clear to me that all items qualify as scopes -- statics
871 /// and associated types probably shouldn't, for example. Behavior in this
872 /// regard should be expected to be highly unstable.
873 pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
874 self.walk_parent_nodes(id, |node| match *node {
876 Node::ForeignItem(_) |
879 Node::Block(_) => true,
884 pub fn get_parent_did(&self, id: NodeId) -> DefId {
885 self.local_def_id(self.get_parent(id))
888 // FIXME(@ljedrz): replace the NodeId variant
889 pub fn get_parent_did_by_hir_id(&self, id: HirId) -> DefId {
890 let node_id = self.hir_to_node_id(id);
891 self.get_parent_did(node_id)
894 pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
895 let parent = self.get_parent(id);
896 if let Some(entry) = self.find_entry(parent) {
898 node: Node::Item(Item { node: ItemKind::ForeignMod(ref nm), .. }), .. } = entry
900 self.read(id); // reveals some of the content of a node
904 bug!("expected foreign mod or inlined parent, found {}", self.node_to_string(parent))
907 // FIXME(@ljedrz): replace the NodeId variant
908 pub fn get_foreign_abi_by_hir_id(&self, id: HirId) -> Abi {
909 let node_id = self.hir_to_node_id(id);
910 self.get_foreign_abi(node_id)
913 pub fn expect_item(&self, id: NodeId) -> &'hir Item {
914 match self.find(id) { // read recorded by `find`
915 Some(Node::Item(item)) => item,
916 _ => bug!("expected item, found {}", self.node_to_string(id))
920 // FIXME(@ljedrz): replace the NodeId variant
921 pub fn expect_item_by_hir_id(&self, id: HirId) -> &'hir Item {
922 match self.find_by_hir_id(id) { // read recorded by `find`
923 Some(Node::Item(item)) => item,
924 _ => bug!("expected item, found {}", self.hir_to_string(id))
928 pub fn expect_impl_item(&self, id: HirId) -> &'hir ImplItem {
929 match self.find_by_hir_id(id) {
930 Some(Node::ImplItem(item)) => item,
931 _ => bug!("expected impl item, found {}", self.hir_to_string(id))
935 pub fn expect_trait_item(&self, id: HirId) -> &'hir TraitItem {
936 match self.find_by_hir_id(id) {
937 Some(Node::TraitItem(item)) => item,
938 _ => bug!("expected trait item, found {}", self.hir_to_string(id))
942 pub fn expect_variant_data(&self, id: HirId) -> &'hir VariantData {
943 match self.find_by_hir_id(id) {
944 Some(Node::Item(i)) => {
946 ItemKind::Struct(ref struct_def, _) |
947 ItemKind::Union(ref struct_def, _) => struct_def,
948 _ => bug!("struct ID bound to non-struct {}", self.hir_to_string(id))
951 Some(Node::StructCtor(data)) => data,
952 Some(Node::Variant(variant)) => &variant.node.data,
953 _ => bug!("expected struct or variant, found {}", self.hir_to_string(id))
957 pub fn expect_variant(&self, id: HirId) -> &'hir Variant {
958 match self.find_by_hir_id(id) {
959 Some(Node::Variant(variant)) => variant,
960 _ => bug!("expected variant, found {}", self.hir_to_string(id)),
964 pub fn expect_foreign_item(&self, id: HirId) -> &'hir ForeignItem {
965 match self.find_by_hir_id(id) {
966 Some(Node::ForeignItem(item)) => item,
967 _ => bug!("expected foreign item, found {}", self.hir_to_string(id))
971 pub fn expect_expr(&self, id: NodeId) -> &'hir Expr {
972 match self.find(id) { // read recorded by find
973 Some(Node::Expr(expr)) => expr,
974 _ => bug!("expected expr, found {}", self.node_to_string(id))
978 // FIXME(@ljedrz): replace the NodeId variant
979 pub fn expect_expr_by_hir_id(&self, id: HirId) -> &'hir Expr {
980 let node_id = self.hir_to_node_id(id);
981 self.expect_expr(node_id)
984 /// Returns the name associated with the given NodeId's AST.
985 pub fn name(&self, id: NodeId) -> Name {
987 Node::Item(i) => i.ident.name,
988 Node::ForeignItem(fi) => fi.ident.name,
989 Node::ImplItem(ii) => ii.ident.name,
990 Node::TraitItem(ti) => ti.ident.name,
991 Node::Variant(v) => v.node.ident.name,
992 Node::Field(f) => f.ident.name,
993 Node::Lifetime(lt) => lt.name.ident().name,
994 Node::GenericParam(param) => param.name.ident().name,
995 Node::Binding(&Pat { node: PatKind::Binding(_, _, l, _), .. }) => l.name,
996 Node::StructCtor(_) => self.name(self.get_parent(id)),
997 _ => bug!("no name for {}", self.node_to_string(id))
1001 // FIXME(@ljedrz): replace the NodeId variant
1002 pub fn name_by_hir_id(&self, id: HirId) -> Name {
1003 let node_id = self.hir_to_node_id(id);
1007 /// Given a node ID, get a list of attributes associated with the AST
1008 /// corresponding to the Node ID
1009 pub fn attrs(&self, id: NodeId) -> &'hir [ast::Attribute] {
1010 self.read(id); // reveals attributes on the node
1011 let attrs = match self.find(id) {
1012 Some(Node::Local(l)) => Some(&l.attrs[..]),
1013 Some(Node::Item(i)) => Some(&i.attrs[..]),
1014 Some(Node::ForeignItem(fi)) => Some(&fi.attrs[..]),
1015 Some(Node::TraitItem(ref ti)) => Some(&ti.attrs[..]),
1016 Some(Node::ImplItem(ref ii)) => Some(&ii.attrs[..]),
1017 Some(Node::Variant(ref v)) => Some(&v.node.attrs[..]),
1018 Some(Node::Field(ref f)) => Some(&f.attrs[..]),
1019 Some(Node::Expr(ref e)) => Some(&*e.attrs),
1020 Some(Node::Stmt(ref s)) => Some(s.node.attrs()),
1021 Some(Node::GenericParam(param)) => Some(¶m.attrs[..]),
1022 // unit/tuple structs take the attributes straight from
1023 // the struct definition.
1024 Some(Node::StructCtor(_)) => return self.attrs(self.get_parent(id)),
1027 attrs.unwrap_or(&[])
1030 // FIXME(@ljedrz): replace the NodeId variant
1031 pub fn attrs_by_hir_id(&self, id: HirId) -> &'hir [ast::Attribute] {
1032 let node_id = self.hir_to_node_id(id);
1036 /// Returns an iterator that yields the node id's with paths that
1037 /// match `parts`. (Requires `parts` is non-empty.)
1039 /// For example, if given `parts` equal to `["bar", "quux"]`, then
1040 /// the iterator will produce node id's for items with paths
1041 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
1042 /// any other such items it can find in the map.
1043 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
1044 -> NodesMatchingSuffix<'a, 'hir> {
1045 NodesMatchingSuffix {
1047 item_name: parts.last().unwrap(),
1048 in_which: &parts[..parts.len() - 1],
1053 pub fn span(&self, id: NodeId) -> Span {
1054 self.read(id); // reveals span from node
1055 match self.find_entry(id).map(|entry| entry.node) {
1056 Some(Node::Item(item)) => item.span,
1057 Some(Node::ForeignItem(foreign_item)) => foreign_item.span,
1058 Some(Node::TraitItem(trait_method)) => trait_method.span,
1059 Some(Node::ImplItem(impl_item)) => impl_item.span,
1060 Some(Node::Variant(variant)) => variant.span,
1061 Some(Node::Field(field)) => field.span,
1062 Some(Node::AnonConst(constant)) => self.body(constant.body).value.span,
1063 Some(Node::Expr(expr)) => expr.span,
1064 Some(Node::Stmt(stmt)) => stmt.span,
1065 Some(Node::PathSegment(seg)) => seg.ident.span,
1066 Some(Node::Ty(ty)) => ty.span,
1067 Some(Node::TraitRef(tr)) => tr.path.span,
1068 Some(Node::Binding(pat)) => pat.span,
1069 Some(Node::Pat(pat)) => pat.span,
1070 Some(Node::Block(block)) => block.span,
1071 Some(Node::StructCtor(_)) => self.expect_item(self.get_parent(id)).span,
1072 Some(Node::Lifetime(lifetime)) => lifetime.span,
1073 Some(Node::GenericParam(param)) => param.span,
1074 Some(Node::Visibility(&Spanned {
1075 node: VisibilityKind::Restricted { ref path, .. }, ..
1077 Some(Node::Visibility(v)) => bug!("unexpected Visibility {:?}", v),
1078 Some(Node::Local(local)) => local.span,
1079 Some(Node::MacroDef(macro_def)) => macro_def.span,
1080 Some(Node::Crate) => self.forest.krate.span,
1081 None => bug!("hir::map::Map::span: id not in map: {:?}", id),
1085 // FIXME(@ljedrz): replace the NodeId variant
1086 pub fn span_by_hir_id(&self, id: HirId) -> Span {
1087 let node_id = self.hir_to_node_id(id);
1091 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
1092 self.as_local_node_id(id).map(|id| self.span(id))
1095 pub fn node_to_string(&self, id: NodeId) -> String {
1096 node_id_to_string(self, id, true)
1099 // FIXME(@ljedrz): replace the NodeId variant
1100 pub fn hir_to_string(&self, id: HirId) -> String {
1101 hir_id_to_string(self, id, true)
1104 pub fn node_to_user_string(&self, id: NodeId) -> String {
1105 node_id_to_string(self, id, false)
1108 // FIXME(@ljedrz): replace the NodeId variant
1109 pub fn hir_to_user_string(&self, id: HirId) -> String {
1110 hir_id_to_string(self, id, false)
1113 pub fn node_to_pretty_string(&self, id: NodeId) -> String {
1114 print::to_string(self, |s| s.print_node(self.get(id)))
1117 // FIXME(@ljedrz): replace the NodeId variant
1118 pub fn hir_to_pretty_string(&self, id: HirId) -> String {
1119 print::to_string(self, |s| s.print_node(self.get_by_hir_id(id)))
1123 pub struct NodesMatchingSuffix<'a, 'hir:'a> {
1125 item_name: &'a String,
1126 in_which: &'a [String],
1130 impl<'a, 'hir> NodesMatchingSuffix<'a, 'hir> {
1131 /// Returns `true` only if some suffix of the module path for parent
1132 /// matches `self.in_which`.
1134 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
1135 /// returns true if parent's path ends with the suffix
1136 /// `x_0::x_1::...::x_k`.
1137 fn suffix_matches(&self, parent: NodeId) -> bool {
1138 let mut cursor = parent;
1139 for part in self.in_which.iter().rev() {
1140 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
1141 None => return false,
1142 Some((node_id, name)) => (node_id, name),
1144 if mod_name != &**part {
1147 cursor = self.map.get_parent(mod_id);
1151 // Finds the first mod in parent chain for `id`, along with
1154 // If `id` itself is a mod named `m` with parent `p`, then
1155 // returns `Some(id, m, p)`. If `id` has no mod in its parent
1156 // chain, then returns `None`.
1157 fn find_first_mod_parent<'a>(map: &'a Map<'_>, mut id: NodeId) -> Option<(NodeId, Name)> {
1159 if let Node::Item(item) = map.find(id)? {
1160 if item_is_mod(&item) {
1161 return Some((id, item.ident.name))
1164 let parent = map.get_parent(id);
1165 if parent == id { return None }
1169 fn item_is_mod(item: &Item) -> bool {
1171 ItemKind::Mod(_) => true,
1178 // We are looking at some node `n` with a given name and parent
1179 // id; do their names match what I am seeking?
1180 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
1181 name == &**self.item_name && self.suffix_matches(parent_of_n)
1185 impl<'a, 'hir> Iterator for NodesMatchingSuffix<'a, 'hir> {
1188 fn next(&mut self) -> Option<NodeId> {
1191 if idx.as_usize() >= self.map.entry_count() {
1194 self.idx = NodeId::from_u32(self.idx.as_u32() + 1);
1195 let name = match self.map.find_entry(idx).map(|entry| entry.node) {
1196 Some(Node::Item(n)) => n.name(),
1197 Some(Node::ForeignItem(n)) => n.name(),
1198 Some(Node::TraitItem(n)) => n.name(),
1199 Some(Node::ImplItem(n)) => n.name(),
1200 Some(Node::Variant(n)) => n.name(),
1201 Some(Node::Field(n)) => n.name(),
1204 if self.matches_names(self.map.get_parent(idx), name) {
1212 fn name(&self) -> Name;
1215 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
1217 impl Named for Item { fn name(&self) -> Name { self.ident.name } }
1218 impl Named for ForeignItem { fn name(&self) -> Name { self.ident.name } }
1219 impl Named for VariantKind { fn name(&self) -> Name { self.ident.name } }
1220 impl Named for StructField { fn name(&self) -> Name { self.ident.name } }
1221 impl Named for TraitItem { fn name(&self) -> Name { self.ident.name } }
1222 impl Named for ImplItem { fn name(&self) -> Name { self.ident.name } }
1224 pub fn map_crate<'hir>(sess: &crate::session::Session,
1225 cstore: &CrateStoreDyn,
1226 forest: &'hir Forest,
1227 definitions: &'hir Definitions)
1229 // Build the reverse mapping of `node_to_hir_id`.
1230 let hir_to_node_id = definitions.node_to_hir_id.iter_enumerated()
1231 .map(|(node_id, &hir_id)| (hir_id, node_id)).collect();
1233 let (map, crate_hash) = {
1234 let hcx = crate::ich::StableHashingContext::new(sess, &forest.krate, definitions, cstore);
1236 let mut collector = NodeCollector::root(sess,
1242 intravisit::walk_crate(&mut collector, &forest.krate);
1244 let crate_disambiguator = sess.local_crate_disambiguator();
1245 let cmdline_args = sess.opts.dep_tracking_hash();
1246 collector.finalize_and_compute_crate_hash(
1247 crate_disambiguator,
1253 if log_enabled!(::log::Level::Debug) {
1254 // This only makes sense for ordered stores; note the
1255 // enumerate to count the number of entries.
1256 let (entries_less_1, _) = map.iter().filter_map(|x| *x).enumerate().last()
1257 .expect("AST map was empty after folding?");
1259 let entries = entries_less_1 + 1;
1260 let vector_length = map.len();
1261 debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
1262 entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
1267 dep_graph: forest.dep_graph.clone(),
1274 time(sess, "validate hir map", || {
1275 hir_id_validator::check_crate(&map);
1281 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1282 /// except it avoids creating a dependency on the whole crate.
1283 impl<'hir> print::PpAnn for Map<'hir> {
1284 fn nested(&self, state: &mut print::State<'_>, nested: print::Nested) -> io::Result<()> {
1286 Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1287 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1288 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1289 Nested::Body(id) => state.print_expr(&self.body(id).value),
1290 Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
1295 impl<'a> print::State<'a> {
1296 pub fn print_node(&mut self, node: Node<'_>) -> io::Result<()> {
1298 Node::Item(a) => self.print_item(&a),
1299 Node::ForeignItem(a) => self.print_foreign_item(&a),
1300 Node::TraitItem(a) => self.print_trait_item(a),
1301 Node::ImplItem(a) => self.print_impl_item(a),
1302 Node::Variant(a) => self.print_variant(&a),
1303 Node::AnonConst(a) => self.print_anon_const(&a),
1304 Node::Expr(a) => self.print_expr(&a),
1305 Node::Stmt(a) => self.print_stmt(&a),
1306 Node::PathSegment(a) => self.print_path_segment(&a),
1307 Node::Ty(a) => self.print_type(&a),
1308 Node::TraitRef(a) => self.print_trait_ref(&a),
1310 Node::Pat(a) => self.print_pat(&a),
1312 use syntax::print::pprust::PrintState;
1314 // containing cbox, will be closed by print-block at }
1315 self.cbox(print::indent_unit)?;
1316 // head-ibox, will be closed by print-block after {
1318 self.print_block(&a)
1320 Node::Lifetime(a) => self.print_lifetime(&a),
1321 Node::Visibility(a) => self.print_visibility(&a),
1322 Node::GenericParam(_) => bug!("cannot print Node::GenericParam"),
1323 Node::Field(_) => bug!("cannot print StructField"),
1324 // these cases do not carry enough information in the
1325 // hir_map to reconstruct their full structure for pretty
1327 Node::StructCtor(_) => bug!("cannot print isolated StructCtor"),
1328 Node::Local(a) => self.print_local_decl(&a),
1329 Node::MacroDef(_) => bug!("cannot print MacroDef"),
1330 Node::Crate => bug!("cannot print Crate"),
1335 fn node_id_to_string(map: &Map<'_>, id: NodeId, include_id: bool) -> String {
1336 let id_str = format!(" (id={})", id);
1337 let id_str = if include_id { &id_str[..] } else { "" };
1340 // This functionality is used for debugging, try to use TyCtxt to get
1341 // the user-friendly path, otherwise fall back to stringifying DefPath.
1342 crate::ty::tls::with_opt(|tcx| {
1343 if let Some(tcx) = tcx {
1344 let def_id = map.local_def_id(id);
1345 tcx.def_path_str(def_id)
1346 } else if let Some(path) = map.def_path_from_id(id) {
1347 path.data.into_iter().map(|elem| {
1348 elem.data.to_string()
1349 }).collect::<Vec<_>>().join("::")
1351 String::from("<missing path>")
1356 match map.find(id) {
1357 Some(Node::Item(item)) => {
1358 let item_str = match item.node {
1359 ItemKind::ExternCrate(..) => "extern crate",
1360 ItemKind::Use(..) => "use",
1361 ItemKind::Static(..) => "static",
1362 ItemKind::Const(..) => "const",
1363 ItemKind::Fn(..) => "fn",
1364 ItemKind::Mod(..) => "mod",
1365 ItemKind::ForeignMod(..) => "foreign mod",
1366 ItemKind::GlobalAsm(..) => "global asm",
1367 ItemKind::Ty(..) => "ty",
1368 ItemKind::Existential(..) => "existential type",
1369 ItemKind::Enum(..) => "enum",
1370 ItemKind::Struct(..) => "struct",
1371 ItemKind::Union(..) => "union",
1372 ItemKind::Trait(..) => "trait",
1373 ItemKind::TraitAlias(..) => "trait alias",
1374 ItemKind::Impl(..) => "impl",
1376 format!("{} {}{}", item_str, path_str(), id_str)
1378 Some(Node::ForeignItem(_)) => {
1379 format!("foreign item {}{}", path_str(), id_str)
1381 Some(Node::ImplItem(ii)) => {
1383 ImplItemKind::Const(..) => {
1384 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1386 ImplItemKind::Method(..) => {
1387 format!("method {} in {}{}", ii.ident, path_str(), id_str)
1389 ImplItemKind::Type(_) => {
1390 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1392 ImplItemKind::Existential(_) => {
1393 format!("assoc existential type {} in {}{}", ii.ident, path_str(), id_str)
1397 Some(Node::TraitItem(ti)) => {
1398 let kind = match ti.node {
1399 TraitItemKind::Const(..) => "assoc constant",
1400 TraitItemKind::Method(..) => "trait method",
1401 TraitItemKind::Type(..) => "assoc type",
1404 format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1406 Some(Node::Variant(ref variant)) => {
1407 format!("variant {} in {}{}",
1411 Some(Node::Field(ref field)) => {
1412 format!("field {} in {}{}",
1416 Some(Node::AnonConst(_)) => {
1417 format!("const {}{}", map.node_to_pretty_string(id), id_str)
1419 Some(Node::Expr(_)) => {
1420 format!("expr {}{}", map.node_to_pretty_string(id), id_str)
1422 Some(Node::Stmt(_)) => {
1423 format!("stmt {}{}", map.node_to_pretty_string(id), id_str)
1425 Some(Node::PathSegment(_)) => {
1426 format!("path segment {}{}", map.node_to_pretty_string(id), id_str)
1428 Some(Node::Ty(_)) => {
1429 format!("type {}{}", map.node_to_pretty_string(id), id_str)
1431 Some(Node::TraitRef(_)) => {
1432 format!("trait_ref {}{}", map.node_to_pretty_string(id), id_str)
1434 Some(Node::Binding(_)) => {
1435 format!("local {}{}", map.node_to_pretty_string(id), id_str)
1437 Some(Node::Pat(_)) => {
1438 format!("pat {}{}", map.node_to_pretty_string(id), id_str)
1440 Some(Node::Block(_)) => {
1441 format!("block {}{}", map.node_to_pretty_string(id), id_str)
1443 Some(Node::Local(_)) => {
1444 format!("local {}{}", map.node_to_pretty_string(id), id_str)
1446 Some(Node::StructCtor(_)) => {
1447 format!("struct_ctor {}{}", path_str(), id_str)
1449 Some(Node::Lifetime(_)) => {
1450 format!("lifetime {}{}", map.node_to_pretty_string(id), id_str)
1452 Some(Node::GenericParam(ref param)) => {
1453 format!("generic_param {:?}{}", param, id_str)
1455 Some(Node::Visibility(ref vis)) => {
1456 format!("visibility {:?}{}", vis, id_str)
1458 Some(Node::MacroDef(_)) => {
1459 format!("macro {}{}", path_str(), id_str)
1461 Some(Node::Crate) => String::from("root_crate"),
1462 None => format!("unknown node{}", id_str),
1466 // FIXME(@ljedrz): replace the NodeId variant
1467 fn hir_id_to_string(map: &Map<'_>, id: HirId, include_id: bool) -> String {
1468 let node_id = map.hir_to_node_id(id);
1469 node_id_to_string(map, node_id, include_id)
1472 pub fn describe_def(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> Option<Def> {
1473 if let Some(node_id) = tcx.hir().as_local_node_id(def_id) {
1474 tcx.hir().describe_def(node_id)
1476 bug!("Calling local describe_def query provider for upstream DefId: {:?}",