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};
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::indexed_vec::IndexVec;
15 use syntax::ast::{self, Name, NodeId};
16 use syntax::source_map::Spanned;
17 use syntax::ext::base::MacroKind;
18 use syntax_pos::{Span, DUMMY_SP};
21 use crate::hir::DefKind;
22 use crate::hir::itemlikevisit::ItemLikeVisitor;
23 use crate::hir::print::Nested;
24 use crate::util::nodemap::FxHashMap;
25 use crate::util::common::time;
28 use std::result::Result::Err;
29 use crate::ty::TyCtxt;
37 /// Represents an entry and its parent `NodeId`.
38 #[derive(Copy, Clone, Debug)]
39 pub struct Entry<'hir> {
41 dep_node: DepNodeIndex,
45 impl<'hir> Entry<'hir> {
46 fn parent_node(self) -> Option<HirId> {
48 Node::Crate | Node::MacroDef(_) => None,
49 _ => Some(self.parent),
53 fn fn_decl(&self) -> Option<&FnDecl> {
55 Node::Item(ref item) => {
57 ItemKind::Fn(ref fn_decl, _, _, _) => Some(&fn_decl),
62 Node::TraitItem(ref item) => {
64 TraitItemKind::Method(ref method_sig, _) => Some(&method_sig.decl),
69 Node::ImplItem(ref item) => {
71 ImplItemKind::Method(ref method_sig, _) => Some(&method_sig.decl),
76 Node::Expr(ref expr) => {
78 ExprKind::Closure(_, ref fn_decl, ..) => Some(&fn_decl),
87 fn associated_body(self) -> Option<BodyId> {
91 ItemKind::Const(_, body) |
92 ItemKind::Static(.., body) |
93 ItemKind::Fn(_, _, _, body) => Some(body),
98 Node::TraitItem(item) => {
100 TraitItemKind::Const(_, Some(body)) |
101 TraitItemKind::Method(_, TraitMethod::Provided(body)) => Some(body),
106 Node::ImplItem(item) => {
108 ImplItemKind::Const(_, body) |
109 ImplItemKind::Method(_, body) => Some(body),
114 Node::AnonConst(constant) => Some(constant.body),
116 Node::Expr(expr) => {
118 ExprKind::Closure(.., body, _, _) => Some(body),
127 fn is_body_owner(self, hir_id: HirId) -> bool {
128 match self.associated_body() {
129 Some(b) => b.hir_id == hir_id,
135 /// Stores a crate and any number of inlined items from other crates.
138 pub dep_graph: DepGraph,
142 pub fn new(krate: Crate, dep_graph: &DepGraph) -> Forest {
145 dep_graph: dep_graph.clone(),
149 pub fn krate<'hir>(&'hir self) -> &'hir Crate {
150 self.dep_graph.read(DepNode::new_no_params(DepKind::Krate));
154 /// This is used internally in the dependency tracking system.
155 /// Use the `krate` method to ensure your dependency on the
156 /// crate is tracked.
157 pub fn untracked_krate<'hir>(&'hir self) -> &'hir Crate {
162 /// This type is effectively a `HashMap<HirId, Entry<'hir>>`,
163 /// but it is implemented as 2 layers of arrays.
164 /// - first we have `A = Vec<Option<B>>` mapping a `DefIndex`'s index to an inner value
165 /// - which is `B = IndexVec<ItemLocalId, Option<Entry<'hir>>` which gives you the `Entry`.
166 pub(super) type HirEntryMap<'hir> = Vec<Option<IndexVec<ItemLocalId, Option<Entry<'hir>>>>>;
168 /// Represents a mapping from `NodeId`s to AST elements and their parent `NodeId`s.
170 pub struct Map<'hir> {
171 /// The backing storage for all the AST nodes.
172 pub forest: &'hir Forest,
174 /// Same as the dep_graph in forest, just available with one fewer
175 /// deref. This is a gratuitous micro-optimization.
176 pub dep_graph: DepGraph,
178 /// The SVH of the local crate.
181 map: HirEntryMap<'hir>,
183 definitions: &'hir Definitions,
185 /// The reverse mapping of `node_to_hir_id`.
186 hir_to_node_id: FxHashMap<HirId, NodeId>,
189 impl<'hir> Map<'hir> {
191 fn lookup(&self, id: HirId) -> Option<&Entry<'hir>> {
192 let local_map = self.map.get(id.owner.index())?;
193 local_map.as_ref()?.get(id.local_id)?.as_ref()
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, hir_id: HirId) {
204 if let Some(entry) = self.lookup(hir_id) {
205 self.dep_graph.read_index(entry.dep_node);
207 bug!("called `HirMap::read()` with invalid `HirId`: {:?}", hir_id)
212 pub fn definitions(&self) -> &'hir Definitions {
216 pub fn def_key(&self, def_id: DefId) -> DefKey {
217 assert!(def_id.is_local());
218 self.definitions.def_key(def_id.index)
221 pub fn def_path_from_hir_id(&self, id: HirId) -> Option<DefPath> {
222 self.opt_local_def_id_from_hir_id(id).map(|def_id| {
223 self.def_path(def_id)
227 pub fn def_path(&self, def_id: DefId) -> DefPath {
228 assert!(def_id.is_local());
229 self.definitions.def_path(def_id.index)
233 pub fn local_def_id(&self, node: NodeId) -> DefId {
234 self.opt_local_def_id(node).unwrap_or_else(|| {
235 let hir_id = self.node_to_hir_id(node);
236 bug!("local_def_id: no entry for `{}`, which has a map of `{:?}`",
237 node, self.find_entry(hir_id))
241 // FIXME(@ljedrz): replace the NodeId variant
243 pub fn local_def_id_from_hir_id(&self, hir_id: HirId) -> DefId {
244 self.opt_local_def_id_from_hir_id(hir_id).unwrap_or_else(|| {
245 bug!("local_def_id_from_hir_id: no entry for `{:?}`, which has a map of `{:?}`",
246 hir_id, self.find_entry(hir_id))
250 // FIXME(@ljedrz): replace the NodeId variant
252 pub fn opt_local_def_id_from_hir_id(&self, hir_id: HirId) -> Option<DefId> {
253 let node_id = self.hir_to_node_id(hir_id);
254 self.definitions.opt_local_def_id(node_id)
258 pub fn opt_local_def_id(&self, node: NodeId) -> Option<DefId> {
259 self.definitions.opt_local_def_id(node)
263 pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
264 self.definitions.as_local_node_id(def_id)
267 // FIXME(@ljedrz): replace the NodeId variant
269 pub fn as_local_hir_id(&self, def_id: DefId) -> Option<HirId> {
270 self.definitions.as_local_hir_id(def_id)
274 pub fn hir_to_node_id(&self, hir_id: HirId) -> NodeId {
275 self.hir_to_node_id[&hir_id]
279 pub fn node_to_hir_id(&self, node_id: NodeId) -> HirId {
280 self.definitions.node_to_hir_id(node_id)
284 pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> HirId {
285 self.definitions.def_index_to_hir_id(def_index)
289 pub fn def_index_to_node_id(&self, def_index: DefIndex) -> NodeId {
290 self.definitions.as_local_node_id(DefId::local(def_index)).unwrap()
294 pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
295 self.definitions.def_index_to_hir_id(def_id.to_def_id().index)
299 pub fn local_def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
300 self.definitions.as_local_node_id(def_id.to_def_id()).unwrap()
303 fn def_kind(&self, node_id: NodeId) -> Option<DefKind> {
304 let node = if let Some(node) = self.find(node_id) {
311 Node::Item(item) => {
313 ItemKind::Static(..) => DefKind::Static,
314 ItemKind::Const(..) => DefKind::Const,
315 ItemKind::Fn(..) => DefKind::Fn,
316 ItemKind::Mod(..) => DefKind::Mod,
317 ItemKind::Existential(..) => DefKind::Existential,
318 ItemKind::Ty(..) => DefKind::TyAlias,
319 ItemKind::Enum(..) => DefKind::Enum,
320 ItemKind::Struct(..) => DefKind::Struct,
321 ItemKind::Union(..) => DefKind::Union,
322 ItemKind::Trait(..) => DefKind::Trait,
323 ItemKind::TraitAlias(..) => DefKind::TraitAlias,
324 ItemKind::ExternCrate(_) |
326 ItemKind::ForeignMod(..) |
327 ItemKind::GlobalAsm(..) |
328 ItemKind::Impl(..) => return None,
331 Node::ForeignItem(item) => {
333 ForeignItemKind::Fn(..) => DefKind::Fn,
334 ForeignItemKind::Static(..) => DefKind::Static,
335 ForeignItemKind::Type => DefKind::ForeignTy,
338 Node::TraitItem(item) => {
340 TraitItemKind::Const(..) => DefKind::AssociatedConst,
341 TraitItemKind::Method(..) => DefKind::Method,
342 TraitItemKind::Type(..) => DefKind::AssociatedTy,
345 Node::ImplItem(item) => {
347 ImplItemKind::Const(..) => DefKind::AssociatedConst,
348 ImplItemKind::Method(..) => DefKind::Method,
349 ImplItemKind::Type(..) => DefKind::AssociatedTy,
350 ImplItemKind::Existential(..) => DefKind::AssociatedExistential,
353 Node::Variant(_) => DefKind::Variant,
354 Node::Ctor(variant_data) => {
355 // FIXME(eddyb) is this even possible, if we have a `Node::Ctor`?
356 if variant_data.ctor_hir_id().is_none() {
359 let ctor_of = match self.find(self.get_parent_node(node_id)) {
360 Some(Node::Item(..)) => def::CtorOf::Struct,
361 Some(Node::Variant(..)) => def::CtorOf::Variant,
364 DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data))
370 Node::PathSegment(_) |
377 Node::Visibility(_) |
379 Node::Crate => return None,
380 Node::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
381 Node::GenericParam(param) => {
383 GenericParamKind::Lifetime { .. } => return None,
384 GenericParamKind::Type { .. } => DefKind::TyParam,
385 GenericParamKind::Const { .. } => DefKind::ConstParam,
391 fn find_entry(&self, id: HirId) -> Option<Entry<'hir>> {
392 self.lookup(id).cloned()
395 pub fn krate(&self) -> &'hir Crate {
399 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem {
400 self.read(id.hir_id);
402 // N.B., intentionally bypass `self.forest.krate()` so that we
403 // do not trigger a read of the whole krate here
404 self.forest.krate.trait_item(id)
407 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem {
408 self.read(id.hir_id);
410 // N.B., intentionally bypass `self.forest.krate()` so that we
411 // do not trigger a read of the whole krate here
412 self.forest.krate.impl_item(id)
415 pub fn body(&self, id: BodyId) -> &'hir Body {
416 self.read(id.hir_id);
418 // N.B., intentionally bypass `self.forest.krate()` so that we
419 // do not trigger a read of the whole krate here
420 self.forest.krate.body(id)
423 pub fn fn_decl(&self, node_id: ast::NodeId) -> Option<FnDecl> {
424 let hir_id = self.node_to_hir_id(node_id);
425 self.fn_decl_by_hir_id(hir_id)
428 // FIXME(@ljedrz): replace the NodeId variant
429 pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<FnDecl> {
430 if let Some(entry) = self.find_entry(hir_id) {
431 entry.fn_decl().cloned()
433 bug!("no entry for hir_id `{}`", hir_id)
437 /// Returns the `NodeId` that corresponds to the definition of
438 /// which this is the body of, i.e., a `fn`, `const` or `static`
439 /// item (possibly associated), a closure, or a `hir::AnonConst`.
440 pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> NodeId {
441 let parent = self.get_parent_node_by_hir_id(hir_id);
442 assert!(self.lookup(parent).map_or(false, |e| e.is_body_owner(hir_id)));
443 self.hir_to_node_id(parent)
446 pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
447 self.local_def_id(self.body_owner(id))
450 /// Given a `NodeId`, returns the `BodyId` associated with it,
451 /// if the node is a body owner, otherwise returns `None`.
452 pub fn maybe_body_owned_by(&self, id: NodeId) -> Option<BodyId> {
453 let hir_id = self.node_to_hir_id(id);
454 self.maybe_body_owned_by_by_hir_id(hir_id)
457 // FIXME(@ljedrz): replace the NodeId variant
458 pub fn maybe_body_owned_by_by_hir_id(&self, hir_id: HirId) -> Option<BodyId> {
459 if let Some(entry) = self.find_entry(hir_id) {
460 if self.dep_graph.is_fully_enabled() {
461 let hir_id_owner = hir_id.owner;
462 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
463 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
466 entry.associated_body()
468 bug!("no entry for id `{}`", hir_id)
472 /// Given a body owner's id, returns the `BodyId` associated with it.
473 pub fn body_owned_by(&self, id: HirId) -> BodyId {
474 self.maybe_body_owned_by_by_hir_id(id).unwrap_or_else(|| {
475 span_bug!(self.span_by_hir_id(id), "body_owned_by: {} has no associated body",
476 self.hir_to_string(id));
480 pub fn body_owner_kind(&self, id: NodeId) -> BodyOwnerKind {
481 let hir_id = self.node_to_hir_id(id);
482 self.body_owner_kind_by_hir_id(hir_id)
485 // FIXME(@ljedrz): replace the NodeId variant
486 pub fn body_owner_kind_by_hir_id(&self, id: HirId) -> BodyOwnerKind {
487 match self.get_by_hir_id(id) {
488 Node::Item(&Item { node: ItemKind::Const(..), .. }) |
489 Node::TraitItem(&TraitItem { node: TraitItemKind::Const(..), .. }) |
490 Node::ImplItem(&ImplItem { node: ImplItemKind::Const(..), .. }) |
491 Node::AnonConst(_) => {
495 Node::Item(&Item { node: ItemKind::Fn(..), .. }) |
496 Node::TraitItem(&TraitItem { node: TraitItemKind::Method(..), .. }) |
497 Node::ImplItem(&ImplItem { node: ImplItemKind::Method(..), .. }) => {
500 Node::Item(&Item { node: ItemKind::Static(_, m, _), .. }) => {
501 BodyOwnerKind::Static(m)
503 Node::Expr(&Expr { node: ExprKind::Closure(..), .. }) => {
504 BodyOwnerKind::Closure
506 node => bug!("{:#?} is not a body node", node),
510 pub fn ty_param_owner(&self, id: HirId) -> HirId {
511 match self.get_by_hir_id(id) {
512 Node::Item(&Item { node: ItemKind::Trait(..), .. }) |
513 Node::Item(&Item { node: ItemKind::TraitAlias(..), .. }) => id,
514 Node::GenericParam(_) => self.get_parent_node_by_hir_id(id),
515 _ => bug!("ty_param_owner: {} not a type parameter", self.hir_to_string(id))
519 pub fn ty_param_name(&self, id: HirId) -> Name {
520 match self.get_by_hir_id(id) {
521 Node::Item(&Item { node: ItemKind::Trait(..), .. }) |
522 Node::Item(&Item { node: ItemKind::TraitAlias(..), .. }) => keywords::SelfUpper.name(),
523 Node::GenericParam(param) => param.name.ident().name,
524 _ => bug!("ty_param_name: {} not a type parameter", self.hir_to_string(id)),
528 pub fn trait_impls(&self, trait_did: DefId) -> &'hir [HirId] {
529 self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
531 // N.B., intentionally bypass `self.forest.krate()` so that we
532 // do not trigger a read of the whole krate here
533 self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
536 /// Gets the attributes on the crate. This is preferable to
537 /// invoking `krate.attrs` because it registers a tighter
538 /// dep-graph access.
539 pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
540 let def_path_hash = self.definitions.def_path_hash(CRATE_DEF_INDEX);
542 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::Hir));
543 &self.forest.krate.attrs
546 pub fn get_module(&self, module: DefId) -> (&'hir Mod, Span, HirId)
548 let hir_id = self.as_local_hir_id(module).unwrap();
550 match self.find_entry(hir_id).unwrap().node {
553 node: ItemKind::Mod(ref m),
555 }) => (m, span, hir_id),
556 Node::Crate => (&self.forest.krate.module, self.forest.krate.span, hir_id),
557 _ => panic!("not a module")
561 pub fn visit_item_likes_in_module<V>(&self, module: DefId, visitor: &mut V)
562 where V: ItemLikeVisitor<'hir>
564 let hir_id = self.as_local_hir_id(module).unwrap();
566 // Read the module so we'll be re-executed if new items
567 // appear immediately under in the module. If some new item appears
568 // in some nested item in the module, we'll be re-executed due to reads
569 // in the expect_* calls the loops below
572 let node_id = self.hir_to_node_id[&hir_id];
574 let module = &self.forest.krate.modules[&node_id];
576 for id in &module.items {
577 visitor.visit_item(self.expect_item_by_hir_id(*id));
580 for id in &module.trait_items {
581 visitor.visit_trait_item(self.expect_trait_item(id.hir_id));
584 for id in &module.impl_items {
585 visitor.visit_impl_item(self.expect_impl_item(id.hir_id));
589 /// Retrieve the Node corresponding to `id`, panicking if it cannot
591 pub fn get(&self, id: NodeId) -> Node<'hir> {
592 let hir_id = self.node_to_hir_id(id);
593 self.get_by_hir_id(hir_id)
596 // FIXME(@ljedrz): replace the NodeId variant
597 pub fn get_by_hir_id(&self, id: HirId) -> Node<'hir> {
598 // read recorded by `find`
599 self.find_by_hir_id(id).unwrap_or_else(||
600 bug!("couldn't find hir id {} in the HIR map", id))
603 pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
604 self.as_local_node_id(id).map(|id| self.get(id)) // read recorded by `get`
607 pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics> {
608 self.get_if_local(id).and_then(|node| {
610 Node::ImplItem(ref impl_item) => Some(&impl_item.generics),
611 Node::TraitItem(ref trait_item) => Some(&trait_item.generics),
612 Node::Item(ref item) => {
614 ItemKind::Fn(_, _, ref generics, _) |
615 ItemKind::Ty(_, ref generics) |
616 ItemKind::Enum(_, ref generics) |
617 ItemKind::Struct(_, ref generics) |
618 ItemKind::Union(_, ref generics) |
619 ItemKind::Trait(_, _, ref generics, ..) |
620 ItemKind::TraitAlias(ref generics, _) |
621 ItemKind::Impl(_, _, _, ref generics, ..) => Some(generics),
630 pub fn get_generics_span(&self, id: DefId) -> Option<Span> {
631 self.get_generics(id).map(|generics| generics.span).filter(|sp| *sp != DUMMY_SP)
634 /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
635 pub fn find(&self, id: NodeId) -> Option<Node<'hir>> {
636 let hir_id = self.node_to_hir_id(id);
637 self.find_by_hir_id(hir_id)
640 // FIXME(@ljedrz): replace the NodeId variant
641 pub fn find_by_hir_id(&self, hir_id: HirId) -> Option<Node<'hir>> {
642 let result = self.find_entry(hir_id).and_then(|entry| {
643 if let Node::Crate = entry.node {
649 if result.is_some() {
655 /// Similar to `get_parent`; returns the parent node-id, or own `id` if there is
656 /// no parent. Note that the parent may be `CRATE_NODE_ID`, which is not itself
657 /// present in the map -- so passing the return value of get_parent_node to
658 /// get may actually panic.
659 /// This function returns the immediate parent in the AST, whereas get_parent
660 /// returns the enclosing item. Note that this might not be the actual parent
661 /// node in the AST - some kinds of nodes are not in the map and these will
662 /// never appear as the parent_node. So you can always walk the `parent_nodes`
663 /// from a node to the root of the ast (unless you get the same ID back here
664 /// that can happen if the ID is not in the map itself or is just weird).
665 pub fn get_parent_node(&self, id: NodeId) -> NodeId {
666 let hir_id = self.node_to_hir_id(id);
667 let parent_hir_id = self.get_parent_node_by_hir_id(hir_id);
668 self.hir_to_node_id(parent_hir_id)
671 // FIXME(@ljedrz): replace the NodeId variant
672 pub fn get_parent_node_by_hir_id(&self, hir_id: HirId) -> HirId {
673 if self.dep_graph.is_fully_enabled() {
674 let hir_id_owner = hir_id.owner;
675 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
676 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
679 self.find_entry(hir_id)
680 .and_then(|x| x.parent_node())
684 /// Check if the node is an argument. An argument is a local variable whose
685 /// immediate parent is an item or a closure.
686 pub fn is_argument(&self, id: NodeId) -> bool {
687 match self.find(id) {
688 Some(Node::Binding(_)) => (),
691 match self.find(self.get_parent_node(id)) {
692 Some(Node::Item(_)) |
693 Some(Node::TraitItem(_)) |
694 Some(Node::ImplItem(_)) => true,
695 Some(Node::Expr(e)) => {
697 ExprKind::Closure(..) => true,
705 pub fn is_const_scope(&self, hir_id: HirId) -> bool {
706 self.walk_parent_nodes(hir_id, |node| match *node {
707 Node::Item(Item { node: ItemKind::Const(_, _), .. }) => true,
708 Node::Item(Item { node: ItemKind::Fn(_, header, _, _), .. }) => header.is_const(),
710 }, |_| false).map(|id| id != CRATE_HIR_ID).unwrap_or(false)
713 /// If there is some error when walking the parents (e.g., a node does not
714 /// have a parent in the map or a node can't be found), then we return the
715 /// last good `NodeId` we found. Note that reaching the crate root (`id == 0`),
716 /// is not an error, since items in the crate module have the crate root as
718 fn walk_parent_nodes<F, F2>(&self,
722 -> Result<HirId, HirId>
723 where F: Fn(&Node<'hir>) -> bool, F2: Fn(&Node<'hir>) -> bool
725 let mut id = start_id;
727 let parent_node = self.get_parent_node_by_hir_id(id);
728 if parent_node == CRATE_HIR_ID {
729 return Ok(CRATE_HIR_ID);
731 if parent_node == id {
735 if let Some(entry) = self.find_entry(parent_node) {
736 if let Node::Crate = entry.node {
739 if found(&entry.node) {
740 return Ok(parent_node);
741 } else if bail_early(&entry.node) {
742 return Err(parent_node);
751 /// Retrieves the `NodeId` for `id`'s enclosing method, unless there's a
752 /// `while` or `loop` before reaching it, as block tail returns are not
753 /// available in them.
756 /// fn foo(x: usize) -> bool {
758 /// true // `get_return_block` gets passed the `id` corresponding
759 /// } else { // to this, it will return `foo`'s `NodeId`.
766 /// fn foo(x: usize) -> bool {
768 /// true // `get_return_block` gets passed the `id` corresponding
769 /// } // to this, it will return `None`.
773 pub fn get_return_block(&self, id: HirId) -> Option<HirId> {
774 let match_fn = |node: &Node<'_>| {
777 Node::ForeignItem(_) |
779 Node::Expr(Expr { node: ExprKind::Closure(..), ..}) |
780 Node::ImplItem(_) => true,
784 let match_non_returning_block = |node: &Node<'_>| {
786 Node::Expr(ref expr) => {
788 ExprKind::While(..) | ExprKind::Loop(..) | ExprKind::Ret(..) => true,
796 self.walk_parent_nodes(id, match_fn, match_non_returning_block).ok()
799 /// Retrieves the `NodeId` for `id`'s parent item, or `id` itself if no
800 /// parent item is in this map. The "parent item" is the closest parent node
801 /// in the HIR which is recorded by the map and is an item, either an item
802 /// in a module, trait, or impl.
803 pub fn get_parent(&self, id: NodeId) -> NodeId {
804 let hir_id = self.node_to_hir_id(id);
805 let parent_hir_id = self.get_parent_item(hir_id);
806 self.hir_to_node_id(parent_hir_id)
809 // FIXME(@ljedrz): replace the NodeId variant
810 pub fn get_parent_item(&self, hir_id: HirId) -> HirId {
811 match self.walk_parent_nodes(hir_id, |node| match *node {
813 Node::ForeignItem(_) |
815 Node::ImplItem(_) => true,
823 /// Returns the `DefId` of `id`'s nearest module parent, or `id` itself if no
824 /// module parent is in this map.
825 pub fn get_module_parent(&self, id: NodeId) -> DefId {
826 let hir_id = self.node_to_hir_id(id);
827 self.get_module_parent_by_hir_id(hir_id)
830 // FIXME(@ljedrz): replace the NodeId variant
831 pub fn get_module_parent_by_hir_id(&self, id: HirId) -> DefId {
832 self.local_def_id_from_hir_id(self.get_module_parent_node(id))
835 /// Returns the `HirId` of `id`'s nearest module parent, or `id` itself if no
836 /// module parent is in this map.
837 pub fn get_module_parent_node(&self, hir_id: HirId) -> HirId {
838 match self.walk_parent_nodes(hir_id, |node| match *node {
839 Node::Item(&Item { node: ItemKind::Mod(_), .. }) => true,
847 /// Returns the nearest enclosing scope. A scope is an item or block.
848 /// FIXME: it is not clear to me that all items qualify as scopes -- statics
849 /// and associated types probably shouldn't, for example. Behavior in this
850 /// regard should be expected to be highly unstable.
851 pub fn get_enclosing_scope(&self, hir_id: HirId) -> Option<HirId> {
852 self.walk_parent_nodes(hir_id, |node| match *node {
854 Node::ForeignItem(_) |
857 Node::Block(_) => true,
862 pub fn get_parent_did(&self, id: NodeId) -> DefId {
863 let hir_id = self.node_to_hir_id(id);
864 self.get_parent_did_by_hir_id(hir_id)
867 // FIXME(@ljedrz): replace the NodeId variant
868 pub fn get_parent_did_by_hir_id(&self, id: HirId) -> DefId {
869 self.local_def_id_from_hir_id(self.get_parent_item(id))
872 pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
873 let hir_id = self.node_to_hir_id(id);
874 self.get_foreign_abi_by_hir_id(hir_id)
877 // FIXME(@ljedrz): replace the NodeId variant
878 pub fn get_foreign_abi_by_hir_id(&self, hir_id: HirId) -> Abi {
879 let parent = self.get_parent_item(hir_id);
880 if let Some(entry) = self.find_entry(parent) {
882 node: Node::Item(Item { node: ItemKind::ForeignMod(ref nm), .. }), .. } = entry
884 self.read(hir_id); // reveals some of the content of a node
888 bug!("expected foreign mod or inlined parent, found {}", self.hir_to_string(parent))
891 pub fn expect_item(&self, id: NodeId) -> &'hir Item {
892 let hir_id = self.node_to_hir_id(id);
893 self.expect_item_by_hir_id(hir_id)
896 // FIXME(@ljedrz): replace the NodeId variant
897 pub fn expect_item_by_hir_id(&self, id: HirId) -> &'hir Item {
898 match self.find_by_hir_id(id) { // read recorded by `find`
899 Some(Node::Item(item)) => item,
900 _ => bug!("expected item, found {}", self.hir_to_string(id))
904 pub fn expect_impl_item(&self, id: HirId) -> &'hir ImplItem {
905 match self.find_by_hir_id(id) {
906 Some(Node::ImplItem(item)) => item,
907 _ => bug!("expected impl item, found {}", self.hir_to_string(id))
911 pub fn expect_trait_item(&self, id: HirId) -> &'hir TraitItem {
912 match self.find_by_hir_id(id) {
913 Some(Node::TraitItem(item)) => item,
914 _ => bug!("expected trait item, found {}", self.hir_to_string(id))
918 pub fn expect_variant_data(&self, id: HirId) -> &'hir VariantData {
919 match self.find_by_hir_id(id) {
920 Some(Node::Item(i)) => {
922 ItemKind::Struct(ref struct_def, _) |
923 ItemKind::Union(ref struct_def, _) => struct_def,
924 _ => bug!("struct ID bound to non-struct {}", self.hir_to_string(id))
927 Some(Node::Variant(variant)) => &variant.node.data,
928 Some(Node::Ctor(data)) => data,
929 _ => bug!("expected struct or variant, found {}", self.hir_to_string(id))
933 pub fn expect_variant(&self, id: HirId) -> &'hir Variant {
934 match self.find_by_hir_id(id) {
935 Some(Node::Variant(variant)) => variant,
936 _ => bug!("expected variant, found {}", self.hir_to_string(id)),
940 pub fn expect_foreign_item(&self, id: HirId) -> &'hir ForeignItem {
941 match self.find_by_hir_id(id) {
942 Some(Node::ForeignItem(item)) => item,
943 _ => bug!("expected foreign item, found {}", self.hir_to_string(id))
947 pub fn expect_expr(&self, id: NodeId) -> &'hir Expr {
948 let hir_id = self.node_to_hir_id(id);
949 self.expect_expr_by_hir_id(hir_id)
952 // FIXME(@ljedrz): replace the NodeId variant
953 pub fn expect_expr_by_hir_id(&self, id: HirId) -> &'hir Expr {
954 match self.find_by_hir_id(id) { // read recorded by find
955 Some(Node::Expr(expr)) => expr,
956 _ => bug!("expected expr, found {}", self.hir_to_string(id))
960 /// Returns the name associated with the given `NodeId`'s AST.
961 pub fn name(&self, id: NodeId) -> Name {
962 let hir_id = self.node_to_hir_id(id);
963 self.name_by_hir_id(hir_id)
966 // FIXME(@ljedrz): replace the NodeId variant
967 pub fn name_by_hir_id(&self, id: HirId) -> Name {
968 match self.get_by_hir_id(id) {
969 Node::Item(i) => i.ident.name,
970 Node::ForeignItem(fi) => fi.ident.name,
971 Node::ImplItem(ii) => ii.ident.name,
972 Node::TraitItem(ti) => ti.ident.name,
973 Node::Variant(v) => v.node.ident.name,
974 Node::Field(f) => f.ident.name,
975 Node::Lifetime(lt) => lt.name.ident().name,
976 Node::GenericParam(param) => param.name.ident().name,
977 Node::Binding(&Pat { node: PatKind::Binding(_, _, l, _), .. }) => l.name,
978 Node::Ctor(..) => self.name_by_hir_id(self.get_parent_item(id)),
979 _ => bug!("no name for {}", self.hir_to_string(id))
983 /// Given a node ID, get a list of attributes associated with the AST
984 /// corresponding to the Node ID
985 pub fn attrs(&self, id: NodeId) -> &'hir [ast::Attribute] {
986 let hir_id = self.node_to_hir_id(id);
987 self.attrs_by_hir_id(hir_id)
990 // FIXME(@ljedrz): replace the NodeId variant
991 pub fn attrs_by_hir_id(&self, id: HirId) -> &'hir [ast::Attribute] {
992 self.read(id); // reveals attributes on the node
993 let attrs = match self.find_entry(id).map(|entry| entry.node) {
994 Some(Node::Local(l)) => Some(&l.attrs[..]),
995 Some(Node::Item(i)) => Some(&i.attrs[..]),
996 Some(Node::ForeignItem(fi)) => Some(&fi.attrs[..]),
997 Some(Node::TraitItem(ref ti)) => Some(&ti.attrs[..]),
998 Some(Node::ImplItem(ref ii)) => Some(&ii.attrs[..]),
999 Some(Node::Variant(ref v)) => Some(&v.node.attrs[..]),
1000 Some(Node::Field(ref f)) => Some(&f.attrs[..]),
1001 Some(Node::Expr(ref e)) => Some(&*e.attrs),
1002 Some(Node::Stmt(ref s)) => Some(s.node.attrs()),
1003 Some(Node::GenericParam(param)) => Some(¶m.attrs[..]),
1004 // Unit/tuple structs/variants take the attributes straight from
1005 // the struct/variant definition.
1006 Some(Node::Ctor(..)) => return self.attrs_by_hir_id(self.get_parent_item(id)),
1007 Some(Node::Crate) => Some(&self.forest.krate.attrs[..]),
1010 attrs.unwrap_or(&[])
1013 /// Returns an iterator that yields all the hir ids in the map.
1014 fn all_ids<'a>(&'a self) -> impl Iterator<Item = HirId> + 'a {
1015 // This code is a bit awkward because the map is implemented as 2 levels of arrays,
1016 // see the comment on `HirEntryMap`.
1017 // Iterate over all the indices and return a reference to
1018 // local maps and their index given that they exist.
1019 self.map.iter().enumerate().filter_map(|(i, local_map)| {
1020 local_map.as_ref().map(|m| (i, m))
1021 }).flat_map(move |(array_index, local_map)| {
1022 // Iterate over each valid entry in the local map
1023 local_map.iter_enumerated().filter_map(move |(i, entry)| entry.map(move |_| {
1024 // Reconstruct the HirId based on the 3 indices we used to find it
1026 owner: DefIndex::from(array_index),
1033 /// Returns an iterator that yields the node id's with paths that
1034 /// match `parts`. (Requires `parts` is non-empty.)
1036 /// For example, if given `parts` equal to `["bar", "quux"]`, then
1037 /// the iterator will produce node id's for items with paths
1038 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
1039 /// any other such items it can find in the map.
1040 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
1041 -> impl Iterator<Item = NodeId> + 'a {
1042 let nodes = NodesMatchingSuffix {
1044 item_name: parts.last().unwrap(),
1045 in_which: &parts[..parts.len() - 1],
1048 self.all_ids().filter(move |hir| nodes.matches_suffix(*hir)).map(move |hir| {
1049 self.hir_to_node_id(hir)
1053 pub fn span(&self, id: NodeId) -> Span {
1054 let hir_id = self.node_to_hir_id(id);
1055 self.span_by_hir_id(hir_id)
1058 // FIXME(@ljedrz): replace the NodeId variant
1059 pub fn span_by_hir_id(&self, hir_id: HirId) -> Span {
1060 self.read(hir_id); // reveals span from node
1061 match self.find_entry(hir_id).map(|entry| entry.node) {
1062 Some(Node::Item(item)) => item.span,
1063 Some(Node::ForeignItem(foreign_item)) => foreign_item.span,
1064 Some(Node::TraitItem(trait_method)) => trait_method.span,
1065 Some(Node::ImplItem(impl_item)) => impl_item.span,
1066 Some(Node::Variant(variant)) => variant.span,
1067 Some(Node::Field(field)) => field.span,
1068 Some(Node::AnonConst(constant)) => self.body(constant.body).value.span,
1069 Some(Node::Expr(expr)) => expr.span,
1070 Some(Node::Stmt(stmt)) => stmt.span,
1071 Some(Node::PathSegment(seg)) => seg.ident.span,
1072 Some(Node::Ty(ty)) => ty.span,
1073 Some(Node::TraitRef(tr)) => tr.path.span,
1074 Some(Node::Binding(pat)) => pat.span,
1075 Some(Node::Pat(pat)) => pat.span,
1076 Some(Node::Block(block)) => block.span,
1077 Some(Node::Ctor(..)) => match self.find_by_hir_id(
1078 self.get_parent_node_by_hir_id(hir_id))
1080 Some(Node::Item(item)) => item.span,
1081 Some(Node::Variant(variant)) => variant.span,
1082 _ => unreachable!(),
1084 Some(Node::Lifetime(lifetime)) => lifetime.span,
1085 Some(Node::GenericParam(param)) => param.span,
1086 Some(Node::Visibility(&Spanned {
1087 node: VisibilityKind::Restricted { ref path, .. }, ..
1089 Some(Node::Visibility(v)) => bug!("unexpected Visibility {:?}", v),
1090 Some(Node::Local(local)) => local.span,
1091 Some(Node::MacroDef(macro_def)) => macro_def.span,
1092 Some(Node::Crate) => self.forest.krate.span,
1093 None => bug!("hir::map::Map::span: id not in map: {:?}", hir_id),
1097 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
1098 self.as_local_node_id(id).map(|id| self.span(id))
1101 pub fn node_to_string(&self, id: NodeId) -> String {
1102 hir_id_to_string(self, self.node_to_hir_id(id), true)
1105 // FIXME(@ljedrz): replace the NodeId variant
1106 pub fn hir_to_string(&self, id: HirId) -> String {
1107 hir_id_to_string(self, id, true)
1110 pub fn node_to_user_string(&self, id: NodeId) -> String {
1111 hir_id_to_string(self, self.node_to_hir_id(id), false)
1114 // FIXME(@ljedrz): replace the NodeId variant
1115 pub fn hir_to_user_string(&self, id: HirId) -> String {
1116 hir_id_to_string(self, id, false)
1119 pub fn node_to_pretty_string(&self, id: NodeId) -> String {
1120 print::to_string(self, |s| s.print_node(self.get(id)))
1123 // FIXME(@ljedrz): replace the NodeId variant
1124 pub fn hir_to_pretty_string(&self, id: HirId) -> String {
1125 print::to_string(self, |s| s.print_node(self.get_by_hir_id(id)))
1129 pub struct NodesMatchingSuffix<'a> {
1131 item_name: &'a String,
1132 in_which: &'a [String],
1135 impl<'a> NodesMatchingSuffix<'a> {
1136 /// Returns `true` only if some suffix of the module path for parent
1137 /// matches `self.in_which`.
1139 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
1140 /// returns true if parent's path ends with the suffix
1141 /// `x_0::x_1::...::x_k`.
1142 fn suffix_matches(&self, parent: HirId) -> bool {
1143 let mut cursor = parent;
1144 for part in self.in_which.iter().rev() {
1145 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
1146 None => return false,
1147 Some((node_id, name)) => (node_id, name),
1149 if mod_name.as_str() != *part {
1152 cursor = self.map.get_parent_item(mod_id);
1156 // Finds the first mod in parent chain for `id`, along with
1159 // If `id` itself is a mod named `m` with parent `p`, then
1160 // returns `Some(id, m, p)`. If `id` has no mod in its parent
1161 // chain, then returns `None`.
1162 fn find_first_mod_parent<'a>(map: &'a Map<'_>, mut id: HirId) -> Option<(HirId, Name)> {
1164 if let Node::Item(item) = map.find_by_hir_id(id)? {
1165 if item_is_mod(&item) {
1166 return Some((id, item.ident.name))
1169 let parent = map.get_parent_item(id);
1170 if parent == id { return None }
1174 fn item_is_mod(item: &Item) -> bool {
1176 ItemKind::Mod(_) => true,
1183 // We are looking at some node `n` with a given name and parent
1184 // id; do their names match what I am seeking?
1185 fn matches_names(&self, parent_of_n: HirId, name: Name) -> bool {
1186 name.as_str() == *self.item_name && self.suffix_matches(parent_of_n)
1189 fn matches_suffix(&self, hir: HirId) -> bool {
1190 let name = match self.map.find_entry(hir).map(|entry| entry.node) {
1191 Some(Node::Item(n)) => n.name(),
1192 Some(Node::ForeignItem(n)) => n.name(),
1193 Some(Node::TraitItem(n)) => n.name(),
1194 Some(Node::ImplItem(n)) => n.name(),
1195 Some(Node::Variant(n)) => n.name(),
1196 Some(Node::Field(n)) => n.name(),
1199 self.matches_names(self.map.get_parent_item(hir), name)
1204 fn name(&self) -> Name;
1207 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
1209 impl Named for Item { fn name(&self) -> Name { self.ident.name } }
1210 impl Named for ForeignItem { fn name(&self) -> Name { self.ident.name } }
1211 impl Named for VariantKind { fn name(&self) -> Name { self.ident.name } }
1212 impl Named for StructField { fn name(&self) -> Name { self.ident.name } }
1213 impl Named for TraitItem { fn name(&self) -> Name { self.ident.name } }
1214 impl Named for ImplItem { fn name(&self) -> Name { self.ident.name } }
1216 pub fn map_crate<'hir>(sess: &crate::session::Session,
1217 cstore: &CrateStoreDyn,
1218 forest: &'hir Forest,
1219 definitions: &'hir Definitions)
1221 // Build the reverse mapping of `node_to_hir_id`.
1222 let hir_to_node_id = definitions.node_to_hir_id.iter_enumerated()
1223 .map(|(node_id, &hir_id)| (hir_id, node_id)).collect();
1225 let (map, crate_hash) = {
1226 let hcx = crate::ich::StableHashingContext::new(sess, &forest.krate, definitions, cstore);
1228 let mut collector = NodeCollector::root(sess,
1234 intravisit::walk_crate(&mut collector, &forest.krate);
1236 let crate_disambiguator = sess.local_crate_disambiguator();
1237 let cmdline_args = sess.opts.dep_tracking_hash();
1238 collector.finalize_and_compute_crate_hash(
1239 crate_disambiguator,
1247 dep_graph: forest.dep_graph.clone(),
1254 time(sess, "validate hir map", || {
1255 hir_id_validator::check_crate(&map);
1261 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1262 /// except it avoids creating a dependency on the whole crate.
1263 impl<'hir> print::PpAnn for Map<'hir> {
1264 fn nested(&self, state: &mut print::State<'_>, nested: print::Nested) -> io::Result<()> {
1266 Nested::Item(id) => state.print_item(self.expect_item_by_hir_id(id.id)),
1267 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1268 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1269 Nested::Body(id) => state.print_expr(&self.body(id).value),
1270 Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
1275 impl<'a> print::State<'a> {
1276 pub fn print_node(&mut self, node: Node<'_>) -> io::Result<()> {
1278 Node::Item(a) => self.print_item(&a),
1279 Node::ForeignItem(a) => self.print_foreign_item(&a),
1280 Node::TraitItem(a) => self.print_trait_item(a),
1281 Node::ImplItem(a) => self.print_impl_item(a),
1282 Node::Variant(a) => self.print_variant(&a),
1283 Node::AnonConst(a) => self.print_anon_const(&a),
1284 Node::Expr(a) => self.print_expr(&a),
1285 Node::Stmt(a) => self.print_stmt(&a),
1286 Node::PathSegment(a) => self.print_path_segment(&a),
1287 Node::Ty(a) => self.print_type(&a),
1288 Node::TraitRef(a) => self.print_trait_ref(&a),
1290 Node::Pat(a) => self.print_pat(&a),
1292 use syntax::print::pprust::PrintState;
1294 // containing cbox, will be closed by print-block at }
1295 self.cbox(print::indent_unit)?;
1296 // head-ibox, will be closed by print-block after {
1298 self.print_block(&a)
1300 Node::Lifetime(a) => self.print_lifetime(&a),
1301 Node::Visibility(a) => self.print_visibility(&a),
1302 Node::GenericParam(_) => bug!("cannot print Node::GenericParam"),
1303 Node::Field(_) => bug!("cannot print StructField"),
1304 // these cases do not carry enough information in the
1305 // hir_map to reconstruct their full structure for pretty
1307 Node::Ctor(..) => bug!("cannot print isolated Ctor"),
1308 Node::Local(a) => self.print_local_decl(&a),
1309 Node::MacroDef(_) => bug!("cannot print MacroDef"),
1310 Node::Crate => bug!("cannot print Crate"),
1315 fn hir_id_to_string(map: &Map<'_>, id: HirId, include_id: bool) -> String {
1316 let id_str = format!(" (hir_id={})", id);
1317 let id_str = if include_id { &id_str[..] } else { "" };
1320 // This functionality is used for debugging, try to use TyCtxt to get
1321 // the user-friendly path, otherwise fall back to stringifying DefPath.
1322 crate::ty::tls::with_opt(|tcx| {
1323 if let Some(tcx) = tcx {
1324 let def_id = map.local_def_id_from_hir_id(id);
1325 tcx.def_path_str(def_id)
1326 } else if let Some(path) = map.def_path_from_hir_id(id) {
1327 path.data.into_iter().map(|elem| {
1328 elem.data.to_string()
1329 }).collect::<Vec<_>>().join("::")
1331 String::from("<missing path>")
1336 match map.find_by_hir_id(id) {
1337 Some(Node::Item(item)) => {
1338 let item_str = match item.node {
1339 ItemKind::ExternCrate(..) => "extern crate",
1340 ItemKind::Use(..) => "use",
1341 ItemKind::Static(..) => "static",
1342 ItemKind::Const(..) => "const",
1343 ItemKind::Fn(..) => "fn",
1344 ItemKind::Mod(..) => "mod",
1345 ItemKind::ForeignMod(..) => "foreign mod",
1346 ItemKind::GlobalAsm(..) => "global asm",
1347 ItemKind::Ty(..) => "ty",
1348 ItemKind::Existential(..) => "existential type",
1349 ItemKind::Enum(..) => "enum",
1350 ItemKind::Struct(..) => "struct",
1351 ItemKind::Union(..) => "union",
1352 ItemKind::Trait(..) => "trait",
1353 ItemKind::TraitAlias(..) => "trait alias",
1354 ItemKind::Impl(..) => "impl",
1356 format!("{} {}{}", item_str, path_str(), id_str)
1358 Some(Node::ForeignItem(_)) => {
1359 format!("foreign item {}{}", path_str(), id_str)
1361 Some(Node::ImplItem(ii)) => {
1363 ImplItemKind::Const(..) => {
1364 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1366 ImplItemKind::Method(..) => {
1367 format!("method {} in {}{}", ii.ident, path_str(), id_str)
1369 ImplItemKind::Type(_) => {
1370 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1372 ImplItemKind::Existential(_) => {
1373 format!("assoc existential type {} in {}{}", ii.ident, path_str(), id_str)
1377 Some(Node::TraitItem(ti)) => {
1378 let kind = match ti.node {
1379 TraitItemKind::Const(..) => "assoc constant",
1380 TraitItemKind::Method(..) => "trait method",
1381 TraitItemKind::Type(..) => "assoc type",
1384 format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1386 Some(Node::Variant(ref variant)) => {
1387 format!("variant {} in {}{}",
1391 Some(Node::Field(ref field)) => {
1392 format!("field {} in {}{}",
1396 Some(Node::AnonConst(_)) => {
1397 format!("const {}{}", map.hir_to_pretty_string(id), id_str)
1399 Some(Node::Expr(_)) => {
1400 format!("expr {}{}", map.hir_to_pretty_string(id), id_str)
1402 Some(Node::Stmt(_)) => {
1403 format!("stmt {}{}", map.hir_to_pretty_string(id), id_str)
1405 Some(Node::PathSegment(_)) => {
1406 format!("path segment {}{}", map.hir_to_pretty_string(id), id_str)
1408 Some(Node::Ty(_)) => {
1409 format!("type {}{}", map.hir_to_pretty_string(id), id_str)
1411 Some(Node::TraitRef(_)) => {
1412 format!("trait_ref {}{}", map.hir_to_pretty_string(id), id_str)
1414 Some(Node::Binding(_)) => {
1415 format!("local {}{}", map.hir_to_pretty_string(id), id_str)
1417 Some(Node::Pat(_)) => {
1418 format!("pat {}{}", map.hir_to_pretty_string(id), id_str)
1420 Some(Node::Block(_)) => {
1421 format!("block {}{}", map.hir_to_pretty_string(id), id_str)
1423 Some(Node::Local(_)) => {
1424 format!("local {}{}", map.hir_to_pretty_string(id), id_str)
1426 Some(Node::Ctor(..)) => {
1427 format!("ctor {}{}", path_str(), id_str)
1429 Some(Node::Lifetime(_)) => {
1430 format!("lifetime {}{}", map.hir_to_pretty_string(id), id_str)
1432 Some(Node::GenericParam(ref param)) => {
1433 format!("generic_param {:?}{}", param, id_str)
1435 Some(Node::Visibility(ref vis)) => {
1436 format!("visibility {:?}{}", vis, id_str)
1438 Some(Node::MacroDef(_)) => {
1439 format!("macro {}{}", path_str(), id_str)
1441 Some(Node::Crate) => String::from("root_crate"),
1442 None => format!("unknown node{}", id_str),
1446 pub fn def_kind(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> Option<DefKind> {
1447 if let Some(node_id) = tcx.hir().as_local_node_id(def_id) {
1448 tcx.hir().def_kind(node_id)
1450 bug!("Calling local def_kind query provider for upstream DefId: {:?}",