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};
15 use syntax::source_map::Spanned;
16 use syntax::ext::base::MacroKind;
17 use syntax_pos::{Span, DUMMY_SP};
20 use crate::hir::DefKind;
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> {
43 dep_node: DepNodeIndex,
47 impl<'hir> Entry<'hir> {
48 fn parent_node(self) -> Option<HirId> {
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 used internally in the dependency 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: FxHashMap<HirId, 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 let hir_id = self.node_to_hir_id(id);
204 self.read_by_hir_id(hir_id);
207 // FIXME(@ljedrz): replace the NodeId variant
208 pub fn read_by_hir_id(&self, hir_id: HirId) {
209 if let Some(entry) = self.map.get(&hir_id) {
210 self.dep_graph.read_index(entry.dep_node);
212 bug!("called `HirMap::read()` with invalid `HirId`: {:?}", 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 let hir_id = self.node_to_hir_id(node);
246 bug!("local_def_id: no entry for `{}`, which has a map of `{:?}`",
247 node, self.find_entry(hir_id))
251 // FIXME(@ljedrz): replace the NodeId variant
253 pub fn local_def_id_from_hir_id(&self, hir_id: HirId) -> DefId {
254 self.opt_local_def_id_from_hir_id(hir_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(hir_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 fn def_kind(&self, node_id: NodeId) -> Option<DefKind> {
314 let node = if let Some(node) = self.find(node_id) {
321 Node::Item(item) => {
323 ItemKind::Static(..) => DefKind::Static,
324 ItemKind::Const(..) => DefKind::Const,
325 ItemKind::Fn(..) => DefKind::Fn,
326 ItemKind::Mod(..) => DefKind::Mod,
327 ItemKind::Existential(..) => DefKind::Existential,
328 ItemKind::Ty(..) => DefKind::TyAlias,
329 ItemKind::Enum(..) => DefKind::Enum,
330 ItemKind::Struct(..) => DefKind::Struct,
331 ItemKind::Union(..) => DefKind::Union,
332 ItemKind::Trait(..) => DefKind::Trait,
333 ItemKind::TraitAlias(..) => DefKind::TraitAlias,
334 ItemKind::ExternCrate(_) |
336 ItemKind::ForeignMod(..) |
337 ItemKind::GlobalAsm(..) |
338 ItemKind::Impl(..) => return None,
341 Node::ForeignItem(item) => {
343 ForeignItemKind::Fn(..) => DefKind::Fn,
344 ForeignItemKind::Static(..) => DefKind::Static,
345 ForeignItemKind::Type => DefKind::ForeignTy,
348 Node::TraitItem(item) => {
350 TraitItemKind::Const(..) => DefKind::AssociatedConst,
351 TraitItemKind::Method(..) => DefKind::Method,
352 TraitItemKind::Type(..) => DefKind::AssociatedTy,
355 Node::ImplItem(item) => {
357 ImplItemKind::Const(..) => DefKind::AssociatedConst,
358 ImplItemKind::Method(..) => DefKind::Method,
359 ImplItemKind::Type(..) => DefKind::AssociatedTy,
360 ImplItemKind::Existential(..) => DefKind::AssociatedExistential,
363 Node::Variant(_) => DefKind::Variant,
364 Node::Ctor(variant_data) => {
365 // FIXME(eddyb) is this even possible, if we have a `Node::Ctor`?
366 if variant_data.ctor_hir_id().is_none() {
369 let ctor_of = match self.find(self.get_parent_node(node_id)) {
370 Some(Node::Item(..)) => def::CtorOf::Struct,
371 Some(Node::Variant(..)) => def::CtorOf::Variant,
374 DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data))
380 Node::PathSegment(_) |
387 Node::Visibility(_) |
389 Node::Crate => return None,
390 Node::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
391 Node::GenericParam(param) => {
393 GenericParamKind::Lifetime { .. } => return None,
394 GenericParamKind::Type { .. } => DefKind::TyParam,
395 GenericParamKind::Const { .. } => DefKind::ConstParam,
401 fn entry_count(&self) -> usize {
405 fn find_entry(&self, id: HirId) -> Option<Entry<'hir>> {
406 self.map.get(&id).cloned()
409 pub fn krate(&self) -> &'hir Crate {
413 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem {
414 self.read_by_hir_id(id.hir_id);
416 // N.B., intentionally bypass `self.forest.krate()` so that we
417 // do not trigger a read of the whole krate here
418 self.forest.krate.trait_item(id)
421 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem {
422 self.read_by_hir_id(id.hir_id);
424 // N.B., intentionally bypass `self.forest.krate()` so that we
425 // do not trigger a read of the whole krate here
426 self.forest.krate.impl_item(id)
429 pub fn body(&self, id: BodyId) -> &'hir Body {
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.body(id)
437 pub fn fn_decl(&self, node_id: ast::NodeId) -> Option<FnDecl> {
438 let hir_id = self.node_to_hir_id(node_id);
439 self.fn_decl_by_hir_id(hir_id)
442 // FIXME(@ljedrz): replace the NodeId variant
443 pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<FnDecl> {
444 if let Some(entry) = self.find_entry(hir_id) {
445 entry.fn_decl().cloned()
447 bug!("no entry for hir_id `{}`", hir_id)
451 /// Returns the `NodeId` that corresponds to the definition of
452 /// which this is the body of, i.e., a `fn`, `const` or `static`
453 /// item (possibly associated), a closure, or a `hir::AnonConst`.
454 pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> NodeId {
455 let parent = self.get_parent_node_by_hir_id(hir_id);
456 assert!(self.map.get(&parent).map_or(false, |e| e.is_body_owner(hir_id)));
457 self.hir_to_node_id(parent)
460 pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
461 self.local_def_id(self.body_owner(id))
464 /// Given a `NodeId`, returns the `BodyId` associated with it,
465 /// if the node is a body owner, otherwise returns `None`.
466 pub fn maybe_body_owned_by(&self, id: NodeId) -> Option<BodyId> {
467 let hir_id = self.node_to_hir_id(id);
468 self.maybe_body_owned_by_by_hir_id(hir_id)
471 // FIXME(@ljedrz): replace the NodeId variant
472 pub fn maybe_body_owned_by_by_hir_id(&self, hir_id: HirId) -> Option<BodyId> {
473 if let Some(entry) = self.find_entry(hir_id) {
474 if self.dep_graph.is_fully_enabled() {
475 let hir_id_owner = hir_id.owner;
476 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
477 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
480 entry.associated_body()
482 bug!("no entry for id `{}`", hir_id)
486 /// Given a body owner's id, returns the `BodyId` associated with it.
487 pub fn body_owned_by(&self, id: HirId) -> BodyId {
488 self.maybe_body_owned_by_by_hir_id(id).unwrap_or_else(|| {
489 span_bug!(self.span_by_hir_id(id), "body_owned_by: {} has no associated body",
490 self.hir_to_string(id));
494 pub fn body_owner_kind(&self, id: NodeId) -> BodyOwnerKind {
495 let hir_id = self.node_to_hir_id(id);
496 self.body_owner_kind_by_hir_id(hir_id)
499 // FIXME(@ljedrz): replace the NodeId variant
500 pub fn body_owner_kind_by_hir_id(&self, id: HirId) -> BodyOwnerKind {
501 match self.get_by_hir_id(id) {
502 Node::Item(&Item { node: ItemKind::Const(..), .. }) |
503 Node::TraitItem(&TraitItem { node: TraitItemKind::Const(..), .. }) |
504 Node::ImplItem(&ImplItem { node: ImplItemKind::Const(..), .. }) |
505 Node::AnonConst(_) => {
509 Node::Item(&Item { node: ItemKind::Fn(..), .. }) |
510 Node::TraitItem(&TraitItem { node: TraitItemKind::Method(..), .. }) |
511 Node::ImplItem(&ImplItem { node: ImplItemKind::Method(..), .. }) => {
514 Node::Item(&Item { node: ItemKind::Static(_, m, _), .. }) => {
515 BodyOwnerKind::Static(m)
517 Node::Expr(&Expr { node: ExprKind::Closure(..), .. }) => {
518 BodyOwnerKind::Closure
520 node => bug!("{:#?} is not a body node", node),
524 pub fn ty_param_owner(&self, id: HirId) -> HirId {
525 match self.get_by_hir_id(id) {
526 Node::Item(&Item { node: ItemKind::Trait(..), .. }) |
527 Node::Item(&Item { node: ItemKind::TraitAlias(..), .. }) => id,
528 Node::GenericParam(_) => self.get_parent_node_by_hir_id(id),
529 _ => bug!("ty_param_owner: {} not a type parameter", self.hir_to_string(id))
533 pub fn ty_param_name(&self, id: HirId) -> Name {
534 match self.get_by_hir_id(id) {
535 Node::Item(&Item { node: ItemKind::Trait(..), .. }) |
536 Node::Item(&Item { node: ItemKind::TraitAlias(..), .. }) => keywords::SelfUpper.name(),
537 Node::GenericParam(param) => param.name.ident().name,
538 _ => bug!("ty_param_name: {} not a type parameter", self.hir_to_string(id)),
542 pub fn trait_impls(&self, trait_did: DefId) -> &'hir [HirId] {
543 self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
545 // N.B., intentionally bypass `self.forest.krate()` so that we
546 // do not trigger a read of the whole krate here
547 self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
550 /// Gets the attributes on the crate. This is preferable to
551 /// invoking `krate.attrs` because it registers a tighter
552 /// dep-graph access.
553 pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
554 let def_path_hash = self.definitions.def_path_hash(CRATE_DEF_INDEX);
556 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::Hir));
557 &self.forest.krate.attrs
560 pub fn get_module(&self, module: DefId) -> (&'hir Mod, Span, HirId)
562 let hir_id = self.as_local_hir_id(module).unwrap();
563 self.read_by_hir_id(hir_id);
564 match self.find_entry(hir_id).unwrap().node {
567 node: ItemKind::Mod(ref m),
569 }) => (m, span, hir_id),
570 Node::Crate => (&self.forest.krate.module, self.forest.krate.span, hir_id),
571 _ => panic!("not a module")
575 pub fn visit_item_likes_in_module<V>(&self, module: DefId, visitor: &mut V)
576 where V: ItemLikeVisitor<'hir>
578 let node_id = self.as_local_node_id(module).unwrap();
580 // Read the module so we'll be re-executed if new items
581 // appear immediately under in the module. If some new item appears
582 // in some nested item in the module, we'll be re-executed due to reads
583 // in the expect_* calls the loops below
586 let module = &self.forest.krate.modules[&node_id];
588 for id in &module.items {
589 visitor.visit_item(self.expect_item_by_hir_id(*id));
592 for id in &module.trait_items {
593 visitor.visit_trait_item(self.expect_trait_item(id.hir_id));
596 for id in &module.impl_items {
597 visitor.visit_impl_item(self.expect_impl_item(id.hir_id));
601 /// Retrieve the Node corresponding to `id`, panicking if it cannot
603 pub fn get(&self, id: NodeId) -> Node<'hir> {
604 let hir_id = self.node_to_hir_id(id);
605 self.get_by_hir_id(hir_id)
608 // FIXME(@ljedrz): replace the NodeId variant
609 pub fn get_by_hir_id(&self, id: HirId) -> Node<'hir> {
610 // read recorded by `find`
611 self.find_by_hir_id(id).unwrap_or_else(||
612 bug!("couldn't find hir id {} in the HIR map", id))
615 pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
616 self.as_local_node_id(id).map(|id| self.get(id)) // read recorded by `get`
619 pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics> {
620 self.get_if_local(id).and_then(|node| {
622 Node::ImplItem(ref impl_item) => Some(&impl_item.generics),
623 Node::TraitItem(ref trait_item) => Some(&trait_item.generics),
624 Node::Item(ref item) => {
626 ItemKind::Fn(_, _, ref generics, _) |
627 ItemKind::Ty(_, ref generics) |
628 ItemKind::Enum(_, ref generics) |
629 ItemKind::Struct(_, ref generics) |
630 ItemKind::Union(_, ref generics) |
631 ItemKind::Trait(_, _, ref generics, ..) |
632 ItemKind::TraitAlias(ref generics, _) |
633 ItemKind::Impl(_, _, _, ref generics, ..) => Some(generics),
642 pub fn get_generics_span(&self, id: DefId) -> Option<Span> {
643 self.get_generics(id).map(|generics| generics.span).filter(|sp| *sp != DUMMY_SP)
646 /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
647 pub fn find(&self, id: NodeId) -> Option<Node<'hir>> {
648 let hir_id = self.node_to_hir_id(id);
649 self.find_by_hir_id(hir_id)
652 // FIXME(@ljedrz): replace the NodeId variant
653 pub fn find_by_hir_id(&self, hir_id: HirId) -> Option<Node<'hir>> {
654 let result = self.find_entry(hir_id).and_then(|entry| {
655 if let Node::Crate = entry.node {
661 if result.is_some() {
662 self.read_by_hir_id(hir_id);
667 /// Similar to `get_parent`; returns the parent node-id, or own `id` if there is
668 /// no parent. Note that the parent may be `CRATE_NODE_ID`, which is not itself
669 /// present in the map -- so passing the return value of get_parent_node to
670 /// get may actually panic.
671 /// This function returns the immediate parent in the AST, whereas get_parent
672 /// returns the enclosing item. Note that this might not be the actual parent
673 /// node in the AST - some kinds of nodes are not in the map and these will
674 /// never appear as the parent_node. So you can always walk the `parent_nodes`
675 /// from a node to the root of the ast (unless you get the same ID back here
676 /// that can happen if the ID is not in the map itself or is just weird).
677 pub fn get_parent_node(&self, id: NodeId) -> NodeId {
678 let hir_id = self.node_to_hir_id(id);
679 let parent_hir_id = self.get_parent_node_by_hir_id(hir_id);
680 self.hir_to_node_id(parent_hir_id)
683 // FIXME(@ljedrz): replace the NodeId variant
684 pub fn get_parent_node_by_hir_id(&self, hir_id: HirId) -> HirId {
685 if self.dep_graph.is_fully_enabled() {
686 let hir_id_owner = hir_id.owner;
687 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
688 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
691 self.find_entry(hir_id)
692 .and_then(|x| x.parent_node())
696 /// Check if the node is an argument. An argument is a local variable whose
697 /// immediate parent is an item or a closure.
698 pub fn is_argument(&self, id: NodeId) -> bool {
699 match self.find(id) {
700 Some(Node::Binding(_)) => (),
703 match self.find(self.get_parent_node(id)) {
704 Some(Node::Item(_)) |
705 Some(Node::TraitItem(_)) |
706 Some(Node::ImplItem(_)) => true,
707 Some(Node::Expr(e)) => {
709 ExprKind::Closure(..) => true,
717 pub fn is_const_scope(&self, hir_id: HirId) -> bool {
718 self.walk_parent_nodes(hir_id, |node| match *node {
719 Node::Item(Item { node: ItemKind::Const(_, _), .. }) => true,
720 Node::Item(Item { node: ItemKind::Fn(_, header, _, _), .. }) => header.is_const(),
722 }, |_| false).map(|id| id != CRATE_HIR_ID).unwrap_or(false)
725 /// If there is some error when walking the parents (e.g., a node does not
726 /// have a parent in the map or a node can't be found), then we return the
727 /// last good `NodeId` we found. Note that reaching the crate root (`id == 0`),
728 /// is not an error, since items in the crate module have the crate root as
730 fn walk_parent_nodes<F, F2>(&self,
734 -> Result<HirId, HirId>
735 where F: Fn(&Node<'hir>) -> bool, F2: Fn(&Node<'hir>) -> bool
737 let mut id = start_id;
739 let parent_node = self.get_parent_node_by_hir_id(id);
740 if parent_node == CRATE_HIR_ID {
741 return Ok(CRATE_HIR_ID);
743 if parent_node == id {
747 if let Some(entry) = self.find_entry(parent_node) {
748 if let Node::Crate = entry.node {
751 if found(&entry.node) {
752 return Ok(parent_node);
753 } else if bail_early(&entry.node) {
754 return Err(parent_node);
763 /// Retrieves the `NodeId` for `id`'s enclosing method, unless there's a
764 /// `while` or `loop` before reaching it, as block tail returns are not
765 /// available in them.
768 /// fn foo(x: usize) -> bool {
770 /// true // `get_return_block` gets passed the `id` corresponding
771 /// } else { // to this, it will return `foo`'s `NodeId`.
778 /// fn foo(x: usize) -> bool {
780 /// true // `get_return_block` gets passed the `id` corresponding
781 /// } // to this, it will return `None`.
785 pub fn get_return_block(&self, id: HirId) -> Option<HirId> {
786 let match_fn = |node: &Node<'_>| {
789 Node::ForeignItem(_) |
791 Node::Expr(Expr { node: ExprKind::Closure(..), ..}) |
792 Node::ImplItem(_) => true,
796 let match_non_returning_block = |node: &Node<'_>| {
798 Node::Expr(ref expr) => {
800 ExprKind::While(..) | ExprKind::Loop(..) | ExprKind::Ret(..) => true,
808 self.walk_parent_nodes(id, match_fn, match_non_returning_block).ok()
811 /// Retrieves the `NodeId` for `id`'s parent item, or `id` itself if no
812 /// parent item is in this map. The "parent item" is the closest parent node
813 /// in the HIR which is recorded by the map and is an item, either an item
814 /// in a module, trait, or impl.
815 pub fn get_parent(&self, id: NodeId) -> NodeId {
816 let hir_id = self.node_to_hir_id(id);
817 let parent_hir_id = self.get_parent_item(hir_id);
818 self.hir_to_node_id(parent_hir_id)
821 // FIXME(@ljedrz): replace the NodeId variant
822 pub fn get_parent_item(&self, hir_id: HirId) -> HirId {
823 match self.walk_parent_nodes(hir_id, |node| match *node {
825 Node::ForeignItem(_) |
827 Node::ImplItem(_) => true,
835 /// Returns the `DefId` of `id`'s nearest module parent, or `id` itself if no
836 /// module parent is in this map.
837 pub fn get_module_parent(&self, id: NodeId) -> DefId {
838 let hir_id = self.node_to_hir_id(id);
839 self.get_module_parent_by_hir_id(hir_id)
842 // FIXME(@ljedrz): replace the NodeId variant
843 pub fn get_module_parent_by_hir_id(&self, id: HirId) -> DefId {
844 self.local_def_id_from_hir_id(self.get_module_parent_node(id))
847 /// Returns the `HirId` of `id`'s nearest module parent, or `id` itself if no
848 /// module parent is in this map.
849 pub fn get_module_parent_node(&self, hir_id: HirId) -> HirId {
850 match self.walk_parent_nodes(hir_id, |node| match *node {
851 Node::Item(&Item { node: ItemKind::Mod(_), .. }) => true,
859 /// Returns the nearest enclosing scope. A scope is an item or block.
860 /// FIXME: it is not clear to me that all items qualify as scopes -- statics
861 /// and associated types probably shouldn't, for example. Behavior in this
862 /// regard should be expected to be highly unstable.
863 pub fn get_enclosing_scope(&self, hir_id: HirId) -> Option<HirId> {
864 self.walk_parent_nodes(hir_id, |node| match *node {
866 Node::ForeignItem(_) |
869 Node::Block(_) => true,
874 pub fn get_parent_did(&self, id: NodeId) -> DefId {
875 let hir_id = self.node_to_hir_id(id);
876 self.get_parent_did_by_hir_id(hir_id)
879 // FIXME(@ljedrz): replace the NodeId variant
880 pub fn get_parent_did_by_hir_id(&self, id: HirId) -> DefId {
881 self.local_def_id_from_hir_id(self.get_parent_item(id))
884 pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
885 let hir_id = self.node_to_hir_id(id);
886 self.get_foreign_abi_by_hir_id(hir_id)
889 // FIXME(@ljedrz): replace the NodeId variant
890 pub fn get_foreign_abi_by_hir_id(&self, hir_id: HirId) -> Abi {
891 let parent = self.get_parent_item(hir_id);
892 if let Some(entry) = self.find_entry(parent) {
894 node: Node::Item(Item { node: ItemKind::ForeignMod(ref nm), .. }), .. } = entry
896 self.read_by_hir_id(hir_id); // reveals some of the content of a node
900 bug!("expected foreign mod or inlined parent, found {}", self.hir_to_string(parent))
903 pub fn expect_item(&self, id: NodeId) -> &'hir Item {
904 let hir_id = self.node_to_hir_id(id);
905 self.expect_item_by_hir_id(hir_id)
908 // FIXME(@ljedrz): replace the NodeId variant
909 pub fn expect_item_by_hir_id(&self, id: HirId) -> &'hir Item {
910 match self.find_by_hir_id(id) { // read recorded by `find`
911 Some(Node::Item(item)) => item,
912 _ => bug!("expected item, found {}", self.hir_to_string(id))
916 pub fn expect_impl_item(&self, id: HirId) -> &'hir ImplItem {
917 match self.find_by_hir_id(id) {
918 Some(Node::ImplItem(item)) => item,
919 _ => bug!("expected impl item, found {}", self.hir_to_string(id))
923 pub fn expect_trait_item(&self, id: HirId) -> &'hir TraitItem {
924 match self.find_by_hir_id(id) {
925 Some(Node::TraitItem(item)) => item,
926 _ => bug!("expected trait item, found {}", self.hir_to_string(id))
930 pub fn expect_variant_data(&self, id: HirId) -> &'hir VariantData {
931 match self.find_by_hir_id(id) {
932 Some(Node::Item(i)) => {
934 ItemKind::Struct(ref struct_def, _) |
935 ItemKind::Union(ref struct_def, _) => struct_def,
936 _ => bug!("struct ID bound to non-struct {}", self.hir_to_string(id))
939 Some(Node::Variant(variant)) => &variant.node.data,
940 Some(Node::Ctor(data)) => data,
941 _ => bug!("expected struct or variant, found {}", self.hir_to_string(id))
945 pub fn expect_variant(&self, id: HirId) -> &'hir Variant {
946 match self.find_by_hir_id(id) {
947 Some(Node::Variant(variant)) => variant,
948 _ => bug!("expected variant, found {}", self.hir_to_string(id)),
952 pub fn expect_foreign_item(&self, id: HirId) -> &'hir ForeignItem {
953 match self.find_by_hir_id(id) {
954 Some(Node::ForeignItem(item)) => item,
955 _ => bug!("expected foreign item, found {}", self.hir_to_string(id))
959 pub fn expect_expr(&self, id: NodeId) -> &'hir Expr {
960 let hir_id = self.node_to_hir_id(id);
961 self.expect_expr_by_hir_id(hir_id)
964 // FIXME(@ljedrz): replace the NodeId variant
965 pub fn expect_expr_by_hir_id(&self, id: HirId) -> &'hir Expr {
966 match self.find_by_hir_id(id) { // read recorded by find
967 Some(Node::Expr(expr)) => expr,
968 _ => bug!("expected expr, found {}", self.hir_to_string(id))
972 /// Returns the name associated with the given NodeId's AST.
973 pub fn name(&self, id: NodeId) -> Name {
974 let hir_id = self.node_to_hir_id(id);
975 self.name_by_hir_id(hir_id)
978 // FIXME(@ljedrz): replace the NodeId variant
979 pub fn name_by_hir_id(&self, id: HirId) -> Name {
980 match self.get_by_hir_id(id) {
981 Node::Item(i) => i.ident.name,
982 Node::ForeignItem(fi) => fi.ident.name,
983 Node::ImplItem(ii) => ii.ident.name,
984 Node::TraitItem(ti) => ti.ident.name,
985 Node::Variant(v) => v.node.ident.name,
986 Node::Field(f) => f.ident.name,
987 Node::Lifetime(lt) => lt.name.ident().name,
988 Node::GenericParam(param) => param.name.ident().name,
989 Node::Binding(&Pat { node: PatKind::Binding(_, _, l, _), .. }) => l.name,
990 Node::Ctor(..) => self.name_by_hir_id(self.get_parent_item(id)),
991 _ => bug!("no name for {}", self.hir_to_string(id))
995 /// Given a node ID, get a list of attributes associated with the AST
996 /// corresponding to the Node ID
997 pub fn attrs(&self, id: NodeId) -> &'hir [ast::Attribute] {
998 let hir_id = self.node_to_hir_id(id);
999 self.attrs_by_hir_id(hir_id)
1002 // FIXME(@ljedrz): replace the NodeId variant
1003 pub fn attrs_by_hir_id(&self, id: HirId) -> &'hir [ast::Attribute] {
1004 self.read_by_hir_id(id); // reveals attributes on the node
1005 let attrs = match self.find_entry(id).map(|entry| entry.node) {
1006 Some(Node::Local(l)) => Some(&l.attrs[..]),
1007 Some(Node::Item(i)) => Some(&i.attrs[..]),
1008 Some(Node::ForeignItem(fi)) => Some(&fi.attrs[..]),
1009 Some(Node::TraitItem(ref ti)) => Some(&ti.attrs[..]),
1010 Some(Node::ImplItem(ref ii)) => Some(&ii.attrs[..]),
1011 Some(Node::Variant(ref v)) => Some(&v.node.attrs[..]),
1012 Some(Node::Field(ref f)) => Some(&f.attrs[..]),
1013 Some(Node::Expr(ref e)) => Some(&*e.attrs),
1014 Some(Node::Stmt(ref s)) => Some(s.node.attrs()),
1015 Some(Node::GenericParam(param)) => Some(¶m.attrs[..]),
1016 // Unit/tuple structs/variants take the attributes straight from
1017 // the struct/variant definition.
1018 Some(Node::Ctor(..)) => return self.attrs_by_hir_id(self.get_parent_item(id)),
1019 Some(Node::Crate) => Some(&self.forest.krate.attrs[..]),
1022 attrs.unwrap_or(&[])
1025 /// Returns an iterator that yields the node id's with paths that
1026 /// match `parts`. (Requires `parts` is non-empty.)
1028 /// For example, if given `parts` equal to `["bar", "quux"]`, then
1029 /// the iterator will produce node id's for items with paths
1030 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
1031 /// any other such items it can find in the map.
1032 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
1033 -> NodesMatchingSuffix<'a, 'hir> {
1034 NodesMatchingSuffix {
1036 item_name: parts.last().unwrap(),
1037 in_which: &parts[..parts.len() - 1],
1038 idx: ast::CRATE_NODE_ID,
1042 pub fn span(&self, id: NodeId) -> Span {
1043 let hir_id = self.node_to_hir_id(id);
1044 self.span_by_hir_id(hir_id)
1047 // FIXME(@ljedrz): replace the NodeId variant
1048 pub fn span_by_hir_id(&self, hir_id: HirId) -> Span {
1049 self.read_by_hir_id(hir_id); // reveals span from node
1050 match self.find_entry(hir_id).map(|entry| entry.node) {
1051 Some(Node::Item(item)) => item.span,
1052 Some(Node::ForeignItem(foreign_item)) => foreign_item.span,
1053 Some(Node::TraitItem(trait_method)) => trait_method.span,
1054 Some(Node::ImplItem(impl_item)) => impl_item.span,
1055 Some(Node::Variant(variant)) => variant.span,
1056 Some(Node::Field(field)) => field.span,
1057 Some(Node::AnonConst(constant)) => self.body(constant.body).value.span,
1058 Some(Node::Expr(expr)) => expr.span,
1059 Some(Node::Stmt(stmt)) => stmt.span,
1060 Some(Node::PathSegment(seg)) => seg.ident.span,
1061 Some(Node::Ty(ty)) => ty.span,
1062 Some(Node::TraitRef(tr)) => tr.path.span,
1063 Some(Node::Binding(pat)) => pat.span,
1064 Some(Node::Pat(pat)) => pat.span,
1065 Some(Node::Block(block)) => block.span,
1066 Some(Node::Ctor(..)) => match self.find_by_hir_id(
1067 self.get_parent_node_by_hir_id(hir_id))
1069 Some(Node::Item(item)) => item.span,
1070 Some(Node::Variant(variant)) => variant.span,
1071 _ => unreachable!(),
1073 Some(Node::Lifetime(lifetime)) => lifetime.span,
1074 Some(Node::GenericParam(param)) => param.span,
1075 Some(Node::Visibility(&Spanned {
1076 node: VisibilityKind::Restricted { ref path, .. }, ..
1078 Some(Node::Visibility(v)) => bug!("unexpected Visibility {:?}", v),
1079 Some(Node::Local(local)) => local.span,
1080 Some(Node::MacroDef(macro_def)) => macro_def.span,
1081 Some(Node::Crate) => self.forest.krate.span,
1082 None => bug!("hir::map::Map::span: id not in map: {:?}", hir_id),
1086 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
1087 self.as_local_node_id(id).map(|id| self.span(id))
1090 pub fn node_to_string(&self, id: NodeId) -> String {
1091 node_id_to_string(self, id, true)
1094 // FIXME(@ljedrz): replace the NodeId variant
1095 pub fn hir_to_string(&self, id: HirId) -> String {
1096 hir_id_to_string(self, id, true)
1099 pub fn node_to_user_string(&self, id: NodeId) -> String {
1100 node_id_to_string(self, id, false)
1103 // FIXME(@ljedrz): replace the NodeId variant
1104 pub fn hir_to_user_string(&self, id: HirId) -> String {
1105 hir_id_to_string(self, id, false)
1108 pub fn node_to_pretty_string(&self, id: NodeId) -> String {
1109 print::to_string(self, |s| s.print_node(self.get(id)))
1112 // FIXME(@ljedrz): replace the NodeId variant
1113 pub fn hir_to_pretty_string(&self, id: HirId) -> String {
1114 print::to_string(self, |s| s.print_node(self.get_by_hir_id(id)))
1118 pub struct NodesMatchingSuffix<'a, 'hir:'a> {
1120 item_name: &'a String,
1121 in_which: &'a [String],
1125 impl<'a, 'hir> NodesMatchingSuffix<'a, 'hir> {
1126 /// Returns `true` only if some suffix of the module path for parent
1127 /// matches `self.in_which`.
1129 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
1130 /// returns true if parent's path ends with the suffix
1131 /// `x_0::x_1::...::x_k`.
1132 fn suffix_matches(&self, parent: NodeId) -> bool {
1133 let mut cursor = parent;
1134 for part in self.in_which.iter().rev() {
1135 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
1136 None => return false,
1137 Some((node_id, name)) => (node_id, name),
1139 if mod_name != &**part {
1142 cursor = self.map.get_parent(mod_id);
1146 // Finds the first mod in parent chain for `id`, along with
1149 // If `id` itself is a mod named `m` with parent `p`, then
1150 // returns `Some(id, m, p)`. If `id` has no mod in its parent
1151 // chain, then returns `None`.
1152 fn find_first_mod_parent<'a>(map: &'a Map<'_>, mut id: NodeId) -> Option<(NodeId, Name)> {
1154 if let Node::Item(item) = map.find(id)? {
1155 if item_is_mod(&item) {
1156 return Some((id, item.ident.name))
1159 let parent = map.get_parent(id);
1160 if parent == id { return None }
1164 fn item_is_mod(item: &Item) -> bool {
1166 ItemKind::Mod(_) => true,
1173 // We are looking at some node `n` with a given name and parent
1174 // id; do their names match what I am seeking?
1175 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
1176 name == &**self.item_name && self.suffix_matches(parent_of_n)
1180 impl<'a, 'hir> Iterator for NodesMatchingSuffix<'a, 'hir> {
1183 fn next(&mut self) -> Option<NodeId> {
1186 if idx.as_usize() >= self.map.entry_count() {
1189 self.idx = NodeId::from_u32(self.idx.as_u32() + 1);
1190 let hir_idx = self.map.node_to_hir_id(idx);
1191 let name = match self.map.find_entry(hir_idx).map(|entry| entry.node) {
1192 Some(Node::Item(n)) => n.name(),
1193 Some(Node::ForeignItem(n)) => n.name(),
1194 Some(Node::TraitItem(n)) => n.name(),
1195 Some(Node::ImplItem(n)) => n.name(),
1196 Some(Node::Variant(n)) => n.name(),
1197 Some(Node::Field(n)) => n.name(),
1200 if self.matches_names(self.map.get_parent(idx), name) {
1208 fn name(&self) -> Name;
1211 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
1213 impl Named for Item { fn name(&self) -> Name { self.ident.name } }
1214 impl Named for ForeignItem { fn name(&self) -> Name { self.ident.name } }
1215 impl Named for VariantKind { fn name(&self) -> Name { self.ident.name } }
1216 impl Named for StructField { fn name(&self) -> Name { self.ident.name } }
1217 impl Named for TraitItem { fn name(&self) -> Name { self.ident.name } }
1218 impl Named for ImplItem { fn name(&self) -> Name { self.ident.name } }
1220 pub fn map_crate<'hir>(sess: &crate::session::Session,
1221 cstore: &CrateStoreDyn,
1222 forest: &'hir Forest,
1223 definitions: &'hir Definitions)
1225 // Build the reverse mapping of `node_to_hir_id`.
1226 let hir_to_node_id = definitions.node_to_hir_id.iter_enumerated()
1227 .map(|(node_id, &hir_id)| (hir_id, node_id)).collect();
1229 let (map, crate_hash) = {
1230 let hcx = crate::ich::StableHashingContext::new(sess, &forest.krate, definitions, cstore);
1232 let mut collector = NodeCollector::root(sess,
1238 intravisit::walk_crate(&mut collector, &forest.krate);
1240 let crate_disambiguator = sess.local_crate_disambiguator();
1241 let cmdline_args = sess.opts.dep_tracking_hash();
1242 collector.finalize_and_compute_crate_hash(
1243 crate_disambiguator,
1251 dep_graph: forest.dep_graph.clone(),
1258 time(sess, "validate hir map", || {
1259 hir_id_validator::check_crate(&map);
1265 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1266 /// except it avoids creating a dependency on the whole crate.
1267 impl<'hir> print::PpAnn for Map<'hir> {
1268 fn nested(&self, state: &mut print::State<'_>, nested: print::Nested) -> io::Result<()> {
1270 Nested::Item(id) => state.print_item(self.expect_item_by_hir_id(id.id)),
1271 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1272 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1273 Nested::Body(id) => state.print_expr(&self.body(id).value),
1274 Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
1279 impl<'a> print::State<'a> {
1280 pub fn print_node(&mut self, node: Node<'_>) -> io::Result<()> {
1282 Node::Item(a) => self.print_item(&a),
1283 Node::ForeignItem(a) => self.print_foreign_item(&a),
1284 Node::TraitItem(a) => self.print_trait_item(a),
1285 Node::ImplItem(a) => self.print_impl_item(a),
1286 Node::Variant(a) => self.print_variant(&a),
1287 Node::AnonConst(a) => self.print_anon_const(&a),
1288 Node::Expr(a) => self.print_expr(&a),
1289 Node::Stmt(a) => self.print_stmt(&a),
1290 Node::PathSegment(a) => self.print_path_segment(&a),
1291 Node::Ty(a) => self.print_type(&a),
1292 Node::TraitRef(a) => self.print_trait_ref(&a),
1294 Node::Pat(a) => self.print_pat(&a),
1296 use syntax::print::pprust::PrintState;
1298 // containing cbox, will be closed by print-block at }
1299 self.cbox(print::indent_unit)?;
1300 // head-ibox, will be closed by print-block after {
1302 self.print_block(&a)
1304 Node::Lifetime(a) => self.print_lifetime(&a),
1305 Node::Visibility(a) => self.print_visibility(&a),
1306 Node::GenericParam(_) => bug!("cannot print Node::GenericParam"),
1307 Node::Field(_) => bug!("cannot print StructField"),
1308 // these cases do not carry enough information in the
1309 // hir_map to reconstruct their full structure for pretty
1311 Node::Ctor(..) => bug!("cannot print isolated Ctor"),
1312 Node::Local(a) => self.print_local_decl(&a),
1313 Node::MacroDef(_) => bug!("cannot print MacroDef"),
1314 Node::Crate => bug!("cannot print Crate"),
1319 fn node_id_to_string(map: &Map<'_>, id: NodeId, include_id: bool) -> String {
1320 let id_str = format!(" (id={})", id);
1321 let id_str = if include_id { &id_str[..] } else { "" };
1324 // This functionality is used for debugging, try to use TyCtxt to get
1325 // the user-friendly path, otherwise fall back to stringifying DefPath.
1326 crate::ty::tls::with_opt(|tcx| {
1327 if let Some(tcx) = tcx {
1328 let def_id = map.local_def_id(id);
1329 tcx.def_path_str(def_id)
1330 } else if let Some(path) = map.def_path_from_id(id) {
1331 path.data.into_iter().map(|elem| {
1332 elem.data.to_string()
1333 }).collect::<Vec<_>>().join("::")
1335 String::from("<missing path>")
1340 match map.find(id) {
1341 Some(Node::Item(item)) => {
1342 let item_str = match item.node {
1343 ItemKind::ExternCrate(..) => "extern crate",
1344 ItemKind::Use(..) => "use",
1345 ItemKind::Static(..) => "static",
1346 ItemKind::Const(..) => "const",
1347 ItemKind::Fn(..) => "fn",
1348 ItemKind::Mod(..) => "mod",
1349 ItemKind::ForeignMod(..) => "foreign mod",
1350 ItemKind::GlobalAsm(..) => "global asm",
1351 ItemKind::Ty(..) => "ty",
1352 ItemKind::Existential(..) => "existential type",
1353 ItemKind::Enum(..) => "enum",
1354 ItemKind::Struct(..) => "struct",
1355 ItemKind::Union(..) => "union",
1356 ItemKind::Trait(..) => "trait",
1357 ItemKind::TraitAlias(..) => "trait alias",
1358 ItemKind::Impl(..) => "impl",
1360 format!("{} {}{}", item_str, path_str(), id_str)
1362 Some(Node::ForeignItem(_)) => {
1363 format!("foreign item {}{}", path_str(), id_str)
1365 Some(Node::ImplItem(ii)) => {
1367 ImplItemKind::Const(..) => {
1368 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1370 ImplItemKind::Method(..) => {
1371 format!("method {} in {}{}", ii.ident, path_str(), id_str)
1373 ImplItemKind::Type(_) => {
1374 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1376 ImplItemKind::Existential(_) => {
1377 format!("assoc existential type {} in {}{}", ii.ident, path_str(), id_str)
1381 Some(Node::TraitItem(ti)) => {
1382 let kind = match ti.node {
1383 TraitItemKind::Const(..) => "assoc constant",
1384 TraitItemKind::Method(..) => "trait method",
1385 TraitItemKind::Type(..) => "assoc type",
1388 format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1390 Some(Node::Variant(ref variant)) => {
1391 format!("variant {} in {}{}",
1395 Some(Node::Field(ref field)) => {
1396 format!("field {} in {}{}",
1400 Some(Node::AnonConst(_)) => {
1401 format!("const {}{}", map.node_to_pretty_string(id), id_str)
1403 Some(Node::Expr(_)) => {
1404 format!("expr {}{}", map.node_to_pretty_string(id), id_str)
1406 Some(Node::Stmt(_)) => {
1407 format!("stmt {}{}", map.node_to_pretty_string(id), id_str)
1409 Some(Node::PathSegment(_)) => {
1410 format!("path segment {}{}", map.node_to_pretty_string(id), id_str)
1412 Some(Node::Ty(_)) => {
1413 format!("type {}{}", map.node_to_pretty_string(id), id_str)
1415 Some(Node::TraitRef(_)) => {
1416 format!("trait_ref {}{}", map.node_to_pretty_string(id), id_str)
1418 Some(Node::Binding(_)) => {
1419 format!("local {}{}", map.node_to_pretty_string(id), id_str)
1421 Some(Node::Pat(_)) => {
1422 format!("pat {}{}", map.node_to_pretty_string(id), id_str)
1424 Some(Node::Block(_)) => {
1425 format!("block {}{}", map.node_to_pretty_string(id), id_str)
1427 Some(Node::Local(_)) => {
1428 format!("local {}{}", map.node_to_pretty_string(id), id_str)
1430 Some(Node::Ctor(..)) => {
1431 format!("ctor {}{}", path_str(), id_str)
1433 Some(Node::Lifetime(_)) => {
1434 format!("lifetime {}{}", map.node_to_pretty_string(id), id_str)
1436 Some(Node::GenericParam(ref param)) => {
1437 format!("generic_param {:?}{}", param, id_str)
1439 Some(Node::Visibility(ref vis)) => {
1440 format!("visibility {:?}{}", vis, id_str)
1442 Some(Node::MacroDef(_)) => {
1443 format!("macro {}{}", path_str(), id_str)
1445 Some(Node::Crate) => String::from("root_crate"),
1446 None => format!("unknown node{}", id_str),
1450 // FIXME(@ljedrz): replace the NodeId variant
1451 fn hir_id_to_string(map: &Map<'_>, id: HirId, include_id: bool) -> String {
1452 let node_id = map.hir_to_node_id(id);
1453 node_id_to_string(map, node_id, include_id)
1456 pub fn def_kind(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> Option<DefKind> {
1457 if let Some(node_id) = tcx.hir().as_local_node_id(def_id) {
1458 tcx.hir().def_kind(node_id)
1460 bug!("Calling local def_kind query provider for upstream DefId: {:?}",