1 use self::collector::NodeCollector;
2 pub use self::definitions::{
3 DefKey, DefPath, DefPathData, DefPathHash, Definitions, DisambiguatedDefPathData,
6 use crate::hir::{HirOwner, HirOwnerItems};
7 use crate::ty::query::Providers;
9 use rustc_ast::ast::{self, Name, NodeId};
10 use rustc_data_structures::fx::FxHashMap;
11 use rustc_data_structures::svh::Svh;
12 use rustc_hir::def::{DefKind, Res};
13 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, LOCAL_CRATE};
14 use rustc_hir::intravisit;
15 use rustc_hir::itemlikevisit::ItemLikeVisitor;
16 use rustc_hir::print::Nested;
18 use rustc_span::hygiene::MacroKind;
19 use rustc_span::source_map::Spanned;
20 use rustc_span::symbol::kw;
22 use rustc_target::spec::abi::Abi;
29 /// Represents an entry and its parent `HirId`.
30 #[derive(Copy, Clone, Debug)]
31 pub struct Entry<'hir> {
36 impl<'hir> Entry<'hir> {
37 fn parent_node(self) -> Option<HirId> {
39 Node::Crate(_) | Node::MacroDef(_) => None,
40 _ => Some(self.parent),
45 fn fn_decl<'hir>(node: Node<'hir>) -> Option<&'hir FnDecl<'hir>> {
47 Node::Item(ref item) => match item.kind {
48 ItemKind::Fn(ref sig, _, _) => Some(&sig.decl),
52 Node::TraitItem(ref item) => match item.kind {
53 TraitItemKind::Fn(ref sig, _) => Some(&sig.decl),
57 Node::ImplItem(ref item) => match item.kind {
58 ImplItemKind::Method(ref sig, _) => Some(&sig.decl),
62 Node::Expr(ref expr) => match expr.kind {
63 ExprKind::Closure(_, ref fn_decl, ..) => Some(fn_decl),
71 fn fn_sig<'hir>(node: Node<'hir>) -> Option<&'hir FnSig<'hir>> {
73 Node::Item(item) => match &item.kind {
74 ItemKind::Fn(sig, _, _) => Some(sig),
78 Node::TraitItem(item) => match &item.kind {
79 TraitItemKind::Fn(sig, _) => Some(sig),
83 Node::ImplItem(item) => match &item.kind {
84 ImplItemKind::Method(sig, _) => Some(sig),
92 fn associated_body<'hir>(node: Node<'hir>) -> Option<BodyId> {
94 Node::Item(item) => match item.kind {
95 ItemKind::Const(_, body) | ItemKind::Static(.., body) | ItemKind::Fn(.., body) => {
101 Node::TraitItem(item) => match item.kind {
102 TraitItemKind::Const(_, Some(body))
103 | TraitItemKind::Fn(_, TraitMethod::Provided(body)) => Some(body),
107 Node::ImplItem(item) => match item.kind {
108 ImplItemKind::Const(_, body) | ImplItemKind::Method(_, body) => Some(body),
112 Node::AnonConst(constant) => Some(constant.body),
114 Node::Expr(expr) => match expr.kind {
115 ExprKind::Closure(.., body, _, _) => Some(body),
123 fn is_body_owner<'hir>(node: Node<'hir>, hir_id: HirId) -> bool {
124 match associated_body(node) {
125 Some(b) => b.hir_id == hir_id,
130 pub struct IndexedHir<'hir> {
131 /// The SVH of the local crate.
134 pub(super) owner_map: FxHashMap<DefIndex, &'hir HirOwner<'hir>>,
135 pub(super) owner_items_map: FxHashMap<DefIndex, &'hir HirOwnerItems<'hir>>,
137 /// The reverse mapping of `node_to_hir_id`.
138 pub(super) hir_to_node_id: FxHashMap<HirId, NodeId>,
141 #[derive(Copy, Clone)]
142 pub struct Map<'hir> {
143 pub(super) tcx: TyCtxt<'hir>,
146 /// An iterator that walks up the ancestor tree of a given `HirId`.
147 /// Constructed using `tcx.hir().parent_iter(hir_id)`.
148 pub struct ParentHirIterator<'map, 'hir> {
150 map: &'map Map<'hir>,
153 impl<'hir> Iterator for ParentHirIterator<'_, 'hir> {
154 type Item = (HirId, Node<'hir>);
156 fn next(&mut self) -> Option<Self::Item> {
157 if self.current_id == CRATE_HIR_ID {
161 // There are nodes that do not have entries, so we need to skip them.
162 let parent_id = self.map.get_parent_node(self.current_id);
164 if parent_id == self.current_id {
165 self.current_id = CRATE_HIR_ID;
169 self.current_id = parent_id;
170 if let Some(entry) = self.map.find_entry(parent_id) {
171 return Some((parent_id, entry.node));
173 // If this `HirId` doesn't have an `Entry`, skip it and look for its `parent_id`.
178 impl<'hir> Map<'hir> {
179 pub fn krate(&self) -> &'hir Crate<'hir> {
180 self.tcx.hir_crate(LOCAL_CRATE)
184 pub fn definitions(&self) -> &'hir Definitions {
185 &self.tcx.definitions
188 pub fn def_key(&self, def_id: DefId) -> DefKey {
189 assert!(def_id.is_local());
190 self.tcx.definitions.def_key(def_id.index)
193 pub fn def_path_from_hir_id(&self, id: HirId) -> Option<DefPath> {
194 self.opt_local_def_id(id).map(|def_id| self.def_path(def_id))
197 pub fn def_path(&self, def_id: DefId) -> DefPath {
198 assert!(def_id.is_local());
199 self.tcx.definitions.def_path(def_id.index)
203 pub fn local_def_id_from_node_id(&self, node: NodeId) -> DefId {
204 self.opt_local_def_id_from_node_id(node).unwrap_or_else(|| {
205 let hir_id = self.node_to_hir_id(node);
207 "local_def_id_from_node_id: no entry for `{}`, which has a map of `{:?}`",
209 self.find_entry(hir_id)
215 pub fn local_def_id(&self, hir_id: HirId) -> DefId {
216 self.opt_local_def_id(hir_id).unwrap_or_else(|| {
218 "local_def_id: no entry for `{:?}`, which has a map of `{:?}`",
220 self.find_entry(hir_id)
226 pub fn opt_local_def_id(&self, hir_id: HirId) -> Option<DefId> {
227 let node_id = self.hir_to_node_id(hir_id);
228 self.tcx.definitions.opt_local_def_id(node_id)
232 pub fn opt_local_def_id_from_node_id(&self, node: NodeId) -> Option<DefId> {
233 self.tcx.definitions.opt_local_def_id(node)
237 pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
238 self.tcx.definitions.as_local_node_id(def_id)
242 pub fn as_local_hir_id(&self, def_id: DefId) -> Option<HirId> {
243 self.tcx.definitions.as_local_hir_id(def_id)
247 pub fn hir_to_node_id(&self, hir_id: HirId) -> NodeId {
248 self.tcx.index_hir(LOCAL_CRATE).hir_to_node_id[&hir_id]
252 pub fn node_to_hir_id(&self, node_id: NodeId) -> HirId {
253 self.tcx.definitions.node_to_hir_id(node_id)
257 pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> HirId {
258 self.tcx.definitions.def_index_to_hir_id(def_index)
262 pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
263 self.tcx.definitions.def_index_to_hir_id(def_id.to_def_id().index)
266 pub fn def_kind(&self, hir_id: HirId) -> Option<DefKind> {
267 let node = self.find(hir_id)?;
270 Node::Item(item) => match item.kind {
271 ItemKind::Static(..) => DefKind::Static,
272 ItemKind::Const(..) => DefKind::Const,
273 ItemKind::Fn(..) => DefKind::Fn,
274 ItemKind::Mod(..) => DefKind::Mod,
275 ItemKind::OpaqueTy(..) => DefKind::OpaqueTy,
276 ItemKind::TyAlias(..) => DefKind::TyAlias,
277 ItemKind::Enum(..) => DefKind::Enum,
278 ItemKind::Struct(..) => DefKind::Struct,
279 ItemKind::Union(..) => DefKind::Union,
280 ItemKind::Trait(..) => DefKind::Trait,
281 ItemKind::TraitAlias(..) => DefKind::TraitAlias,
282 ItemKind::ExternCrate(_)
284 | ItemKind::ForeignMod(..)
285 | ItemKind::GlobalAsm(..)
286 | ItemKind::Impl { .. } => return None,
288 Node::ForeignItem(item) => match item.kind {
289 ForeignItemKind::Fn(..) => DefKind::Fn,
290 ForeignItemKind::Static(..) => DefKind::Static,
291 ForeignItemKind::Type => DefKind::ForeignTy,
293 Node::TraitItem(item) => match item.kind {
294 TraitItemKind::Const(..) => DefKind::AssocConst,
295 TraitItemKind::Fn(..) => DefKind::AssocFn,
296 TraitItemKind::Type(..) => DefKind::AssocTy,
298 Node::ImplItem(item) => match item.kind {
299 ImplItemKind::Const(..) => DefKind::AssocConst,
300 ImplItemKind::Method(..) => DefKind::AssocFn,
301 ImplItemKind::TyAlias(..) => DefKind::AssocTy,
302 ImplItemKind::OpaqueTy(..) => DefKind::AssocOpaqueTy,
304 Node::Variant(_) => DefKind::Variant,
305 Node::Ctor(variant_data) => {
306 // FIXME(eddyb) is this even possible, if we have a `Node::Ctor`?
307 variant_data.ctor_hir_id()?;
309 let ctor_of = match self.find(self.get_parent_node(hir_id)) {
310 Some(Node::Item(..)) => def::CtorOf::Struct,
311 Some(Node::Variant(..)) => def::CtorOf::Variant,
314 DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data))
320 | Node::PathSegment(_)
329 | Node::Visibility(_)
331 | Node::Crate(_) => return None,
332 Node::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
333 Node::GenericParam(param) => match param.kind {
334 GenericParamKind::Lifetime { .. } => return None,
335 GenericParamKind::Type { .. } => DefKind::TyParam,
336 GenericParamKind::Const { .. } => DefKind::ConstParam,
341 fn find_entry(&self, id: HirId) -> Option<Entry<'hir>> {
342 Some(self.get_entry(id))
345 fn get_entry(&self, id: HirId) -> Entry<'hir> {
346 if id.local_id == ItemLocalId::from_u32_const(0) {
347 let owner = self.tcx.hir_owner(id.owner_def_id());
348 Entry { parent: owner.parent, node: owner.node }
350 let owner = self.tcx.hir_owner_items(id.owner_def_id());
351 let item = owner.items[id.local_id].as_ref().unwrap();
352 Entry { parent: HirId { owner: id.owner, local_id: item.parent }, node: item.node }
356 pub fn item(&self, id: HirId) -> &'hir Item<'hir> {
357 match self.find(id).unwrap() {
358 Node::Item(item) => item,
363 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
364 match self.find(id.hir_id).unwrap() {
365 Node::TraitItem(item) => item,
370 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
371 match self.find(id.hir_id).unwrap() {
372 Node::ImplItem(item) => item,
377 pub fn body(&self, id: BodyId) -> &'hir Body<'hir> {
379 .hir_owner_items(DefId::local(id.hir_id.owner))
381 .get(&id.hir_id.local_id)
385 pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnDecl<'hir>> {
386 if let Some(node) = self.find(hir_id) {
389 bug!("no node for hir_id `{}`", hir_id)
393 pub fn fn_sig_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnSig<'hir>> {
394 if let Some(node) = self.find(hir_id) {
397 bug!("no node for hir_id `{}`", hir_id)
401 /// Returns the `HirId` that corresponds to the definition of
402 /// which this is the body of, i.e., a `fn`, `const` or `static`
403 /// item (possibly associated), a closure, or a `hir::AnonConst`.
404 pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> HirId {
405 let parent = self.get_parent_node(hir_id);
406 assert!(self.find(parent).map_or(false, |n| is_body_owner(n, hir_id)));
410 pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
411 self.local_def_id(self.body_owner(id))
414 /// Given a `HirId`, returns the `BodyId` associated with it,
415 /// if the node is a body owner, otherwise returns `None`.
416 pub fn maybe_body_owned_by(&self, hir_id: HirId) -> Option<BodyId> {
417 if let Some(node) = self.find(hir_id) {
418 associated_body(node)
420 bug!("no entry for id `{}`", hir_id)
424 /// Given a body owner's id, returns the `BodyId` associated with it.
425 pub fn body_owned_by(&self, id: HirId) -> BodyId {
426 self.maybe_body_owned_by(id).unwrap_or_else(|| {
429 "body_owned_by: {} has no associated body",
430 self.node_to_string(id)
435 pub fn body_owner_kind(&self, id: HirId) -> BodyOwnerKind {
437 Node::Item(&Item { kind: ItemKind::Const(..), .. })
438 | Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. })
439 | Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. })
440 | Node::AnonConst(_) => BodyOwnerKind::Const,
442 | Node::Item(&Item { kind: ItemKind::Fn(..), .. })
443 | Node::TraitItem(&TraitItem { kind: TraitItemKind::Fn(..), .. })
444 | Node::ImplItem(&ImplItem { kind: ImplItemKind::Method(..), .. }) => BodyOwnerKind::Fn,
445 Node::Item(&Item { kind: ItemKind::Static(_, m, _), .. }) => BodyOwnerKind::Static(m),
446 Node::Expr(&Expr { kind: ExprKind::Closure(..), .. }) => BodyOwnerKind::Closure,
447 node => bug!("{:#?} is not a body node", node),
451 pub fn ty_param_owner(&self, id: HirId) -> HirId {
453 Node::Item(&Item { kind: ItemKind::Trait(..), .. })
454 | Node::Item(&Item { kind: ItemKind::TraitAlias(..), .. }) => id,
455 Node::GenericParam(_) => self.get_parent_node(id),
456 _ => bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id)),
460 pub fn ty_param_name(&self, id: HirId) -> Name {
462 Node::Item(&Item { kind: ItemKind::Trait(..), .. })
463 | Node::Item(&Item { kind: ItemKind::TraitAlias(..), .. }) => kw::SelfUpper,
464 Node::GenericParam(param) => param.name.ident().name,
465 _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
469 pub fn trait_impls(&self, trait_did: DefId) -> &'hir [HirId] {
470 self.tcx.all_local_trait_impls(LOCAL_CRATE).get(&trait_did).map_or(&[], |xs| &xs[..])
473 /// Gets the attributes on the crate. This is preferable to
474 /// invoking `krate.attrs` because it registers a tighter
475 /// dep-graph access.
476 pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
477 match self.get_entry(CRATE_HIR_ID).node {
478 Node::Crate(item) => item.attrs,
483 pub fn get_module(&self, module: DefId) -> (&'hir Mod<'hir>, Span, HirId) {
484 let hir_id = self.as_local_hir_id(module).unwrap();
485 match self.get_entry(hir_id).node {
486 Node::Item(&Item { span, kind: ItemKind::Mod(ref m), .. }) => (m, span, hir_id),
487 Node::Crate(item) => (&item.module, item.span, hir_id),
488 node => panic!("not a module: {:?}", node),
492 pub fn visit_item_likes_in_module<V>(&self, module: DefId, visitor: &mut V)
494 V: ItemLikeVisitor<'hir>,
496 let module = self.tcx.hir_module_items(module);
498 for id in &module.items {
499 visitor.visit_item(self.expect_item(*id));
502 for id in &module.trait_items {
503 visitor.visit_trait_item(self.expect_trait_item(id.hir_id));
506 for id in &module.impl_items {
507 visitor.visit_impl_item(self.expect_impl_item(id.hir_id));
511 /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found.
512 pub fn get(&self, id: HirId) -> Node<'hir> {
513 self.find(id).unwrap_or_else(|| bug!("couldn't find hir id {} in the HIR map", id))
516 pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
517 self.as_local_hir_id(id).map(|id| self.get(id))
520 pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics<'hir>> {
521 self.get_if_local(id).and_then(|node| match node {
522 Node::ImplItem(ref impl_item) => Some(&impl_item.generics),
523 Node::TraitItem(ref trait_item) => Some(&trait_item.generics),
524 Node::Item(ref item) => match item.kind {
525 ItemKind::Fn(_, ref generics, _)
526 | ItemKind::TyAlias(_, ref generics)
527 | ItemKind::Enum(_, ref generics)
528 | ItemKind::Struct(_, ref generics)
529 | ItemKind::Union(_, ref generics)
530 | ItemKind::Trait(_, _, ref generics, ..)
531 | ItemKind::TraitAlias(ref generics, _)
532 | ItemKind::Impl { ref generics, .. } => Some(generics),
539 /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
540 pub fn find(&self, hir_id: HirId) -> Option<Node<'hir>> {
541 let node = self.get_entry(hir_id).node;
542 if let Node::Crate(..) = node { None } else { Some(node) }
545 /// Similar to `get_parent`; returns the parent HIR Id, or just `hir_id` if there
546 /// is no parent. Note that the parent may be `CRATE_HIR_ID`, which is not itself
547 /// present in the map, so passing the return value of `get_parent_node` to
548 /// `get` may in fact panic.
549 /// This function returns the immediate parent in the HIR, whereas `get_parent`
550 /// returns the enclosing item. Note that this might not be the actual parent
551 /// node in the HIR -- some kinds of nodes are not in the map and these will
552 /// never appear as the parent node. Thus, you can always walk the parent nodes
553 /// from a node to the root of the HIR (unless you get back the same ID here,
554 /// which can happen if the ID is not in the map itself or is just weird).
555 pub fn get_parent_node(&self, hir_id: HirId) -> HirId {
556 self.get_entry(hir_id).parent_node().unwrap_or(hir_id)
559 /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
560 /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`.
561 pub fn parent_iter(&self, current_id: HirId) -> ParentHirIterator<'_, 'hir> {
562 ParentHirIterator { current_id, map: self }
565 /// Checks if the node is an argument. An argument is a local variable whose
566 /// immediate parent is an item or a closure.
567 pub fn is_argument(&self, id: HirId) -> bool {
568 match self.find(id) {
569 Some(Node::Binding(_)) => (),
572 match self.find(self.get_parent_node(id)) {
573 Some(Node::Item(_)) | Some(Node::TraitItem(_)) | Some(Node::ImplItem(_)) => true,
574 Some(Node::Expr(e)) => match e.kind {
575 ExprKind::Closure(..) => true,
582 /// Whether the expression pointed at by `hir_id` belongs to a `const` evaluation context.
583 /// Used exclusively for diagnostics, to avoid suggestion function calls.
584 pub fn is_const_context(&self, hir_id: HirId) -> bool {
585 let parent_id = self.get_parent_item(hir_id);
586 match self.get(parent_id) {
587 Node::Item(&Item { kind: ItemKind::Const(..), .. })
588 | Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. })
589 | Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. })
591 | Node::Item(&Item { kind: ItemKind::Static(..), .. }) => true,
592 Node::Item(&Item { kind: ItemKind::Fn(ref sig, ..), .. }) => {
593 sig.header.constness == Constness::Const
599 /// Whether `hir_id` corresponds to a `mod` or a crate.
600 pub fn is_hir_id_module(&self, hir_id: HirId) -> bool {
601 match self.get_entry(hir_id) {
602 Entry { node: Node::Item(Item { kind: ItemKind::Mod(_), .. }), .. }
603 | Entry { node: Node::Crate(..), .. } => true,
608 /// Retrieves the `HirId` for `id`'s enclosing method, unless there's a
609 /// `while` or `loop` before reaching it, as block tail returns are not
610 /// available in them.
613 /// fn foo(x: usize) -> bool {
615 /// true // If `get_return_block` gets passed the `id` corresponding
616 /// } else { // to this, it will return `foo`'s `HirId`.
623 /// fn foo(x: usize) -> bool {
625 /// true // If `get_return_block` gets passed the `id` corresponding
626 /// } // to this, it will return `None`.
630 pub fn get_return_block(&self, id: HirId) -> Option<HirId> {
631 let mut iter = self.parent_iter(id).peekable();
632 let mut ignore_tail = false;
633 if let Some(entry) = self.find_entry(id) {
634 if let Node::Expr(Expr { kind: ExprKind::Ret(_), .. }) = entry.node {
635 // When dealing with `return` statements, we don't care about climbing only tail
640 while let Some((hir_id, node)) = iter.next() {
641 if let (Some((_, next_node)), false) = (iter.peek(), ignore_tail) {
643 Node::Block(Block { expr: None, .. }) => return None,
644 Node::Block(Block { expr: Some(expr), .. }) => {
645 if hir_id != expr.hir_id {
646 // The current node is not the tail expression of its parent.
655 | Node::ForeignItem(_)
657 | Node::Expr(Expr { kind: ExprKind::Closure(..), .. })
658 | Node::ImplItem(_) => return Some(hir_id),
659 Node::Expr(ref expr) => {
661 // Ignore `return`s on the first iteration
662 ExprKind::Loop(..) | ExprKind::Ret(..) => return None,
666 Node::Local(_) => return None,
673 /// Retrieves the `HirId` for `id`'s parent item, or `id` itself if no
674 /// parent item is in this map. The "parent item" is the closest parent node
675 /// in the HIR which is recorded by the map and is an item, either an item
676 /// in a module, trait, or impl.
677 pub fn get_parent_item(&self, hir_id: HirId) -> HirId {
678 for (hir_id, node) in self.parent_iter(hir_id) {
682 | Node::ForeignItem(_)
684 | Node::ImplItem(_) => return hir_id,
691 /// Returns the `HirId` of `id`'s nearest module parent, or `id` itself if no
692 /// module parent is in this map.
693 pub(super) fn get_module_parent_node(&self, hir_id: HirId) -> HirId {
694 for (hir_id, node) in self.parent_iter(hir_id) {
695 if let Node::Item(&Item { kind: ItemKind::Mod(_), .. }) = node {
702 /// When on a match arm tail expression or on a match arm, give back the enclosing `match`
705 /// Used by error reporting when there's a type error in a match arm caused by the `match`
706 /// expression needing to be unit.
707 pub fn get_match_if_cause(&self, hir_id: HirId) -> Option<&'hir Expr<'hir>> {
708 for (_, node) in self.parent_iter(hir_id) {
710 Node::Item(_) | Node::ForeignItem(_) | Node::TraitItem(_) | Node::ImplItem(_) => {
713 Node::Expr(expr) => match expr.kind {
714 ExprKind::Match(_, _, _) => return Some(expr),
717 Node::Stmt(stmt) => match stmt.kind {
718 StmtKind::Local(_) => break,
727 /// Returns the nearest enclosing scope. A scope is roughly an item or block.
728 pub fn get_enclosing_scope(&self, hir_id: HirId) -> Option<HirId> {
729 for (hir_id, node) in self.parent_iter(hir_id) {
731 Node::Item(i) => match i.kind {
735 | ItemKind::Struct(..)
736 | ItemKind::Union(..)
737 | ItemKind::Trait(..)
738 | ItemKind::Impl { .. } => true,
741 Node::ForeignItem(fi) => match fi.kind {
742 ForeignItemKind::Fn(..) => true,
745 Node::TraitItem(ti) => match ti.kind {
746 TraitItemKind::Fn(..) => true,
749 Node::ImplItem(ii) => match ii.kind {
750 ImplItemKind::Method(..) => true,
753 Node::Block(_) => true,
762 /// Returns the defining scope for an opaque type definition.
763 pub fn get_defining_scope(&self, id: HirId) -> HirId {
766 scope = self.get_enclosing_scope(scope).unwrap_or(CRATE_HIR_ID);
767 if scope == CRATE_HIR_ID {
770 match self.get(scope) {
771 Node::Item(i) => match i.kind {
772 ItemKind::OpaqueTy(OpaqueTy { impl_trait_fn: None, .. }) => {}
782 pub fn get_parent_did(&self, id: HirId) -> DefId {
783 self.local_def_id(self.get_parent_item(id))
786 pub fn get_foreign_abi(&self, hir_id: HirId) -> Abi {
787 let parent = self.get_parent_item(hir_id);
788 if let Some(entry) = self.find_entry(parent) {
790 node: Node::Item(Item { kind: ItemKind::ForeignMod(ref nm), .. }), ..
796 bug!("expected foreign mod or inlined parent, found {}", self.node_to_string(parent))
799 pub fn expect_item(&self, id: HirId) -> &'hir Item<'hir> {
800 match self.find(id) {
801 Some(Node::Item(item)) => item,
802 _ => bug!("expected item, found {}", self.node_to_string(id)),
806 pub fn expect_impl_item(&self, id: HirId) -> &'hir ImplItem<'hir> {
807 match self.find(id) {
808 Some(Node::ImplItem(item)) => item,
809 _ => bug!("expected impl item, found {}", self.node_to_string(id)),
813 pub fn expect_trait_item(&self, id: HirId) -> &'hir TraitItem<'hir> {
814 match self.find(id) {
815 Some(Node::TraitItem(item)) => item,
816 _ => bug!("expected trait item, found {}", self.node_to_string(id)),
820 pub fn expect_variant_data(&self, id: HirId) -> &'hir VariantData<'hir> {
821 match self.find(id) {
822 Some(Node::Item(i)) => match i.kind {
823 ItemKind::Struct(ref struct_def, _) | ItemKind::Union(ref struct_def, _) => {
826 _ => bug!("struct ID bound to non-struct {}", self.node_to_string(id)),
828 Some(Node::Variant(variant)) => &variant.data,
829 Some(Node::Ctor(data)) => data,
830 _ => bug!("expected struct or variant, found {}", self.node_to_string(id)),
834 pub fn expect_variant(&self, id: HirId) -> &'hir Variant<'hir> {
835 match self.find(id) {
836 Some(Node::Variant(variant)) => variant,
837 _ => bug!("expected variant, found {}", self.node_to_string(id)),
841 pub fn expect_foreign_item(&self, id: HirId) -> &'hir ForeignItem<'hir> {
842 match self.find(id) {
843 Some(Node::ForeignItem(item)) => item,
844 _ => bug!("expected foreign item, found {}", self.node_to_string(id)),
848 pub fn expect_expr(&self, id: HirId) -> &'hir Expr<'hir> {
849 match self.find(id) {
850 Some(Node::Expr(expr)) => expr,
851 _ => bug!("expected expr, found {}", self.node_to_string(id)),
855 pub fn opt_name(&self, id: HirId) -> Option<Name> {
856 Some(match self.get(id) {
857 Node::Item(i) => i.ident.name,
858 Node::ForeignItem(fi) => fi.ident.name,
859 Node::ImplItem(ii) => ii.ident.name,
860 Node::TraitItem(ti) => ti.ident.name,
861 Node::Variant(v) => v.ident.name,
862 Node::Field(f) => f.ident.name,
863 Node::Lifetime(lt) => lt.name.ident().name,
864 Node::GenericParam(param) => param.name.ident().name,
865 Node::Binding(&Pat { kind: PatKind::Binding(_, _, l, _), .. }) => l.name,
866 Node::Ctor(..) => self.name(self.get_parent_item(id)),
871 pub fn name(&self, id: HirId) -> Name {
872 match self.opt_name(id) {
874 None => bug!("no name for {}", self.node_to_string(id)),
878 /// Given a node ID, gets a list of attributes associated with the AST
879 /// corresponding to the node-ID.
880 pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] {
881 let attrs = match self.find_entry(id).map(|entry| entry.node) {
882 Some(Node::Param(a)) => Some(&a.attrs[..]),
883 Some(Node::Local(l)) => Some(&l.attrs[..]),
884 Some(Node::Item(i)) => Some(&i.attrs[..]),
885 Some(Node::ForeignItem(fi)) => Some(&fi.attrs[..]),
886 Some(Node::TraitItem(ref ti)) => Some(&ti.attrs[..]),
887 Some(Node::ImplItem(ref ii)) => Some(&ii.attrs[..]),
888 Some(Node::Variant(ref v)) => Some(&v.attrs[..]),
889 Some(Node::Field(ref f)) => Some(&f.attrs[..]),
890 Some(Node::Expr(ref e)) => Some(&*e.attrs),
891 Some(Node::Stmt(ref s)) => Some(s.kind.attrs()),
892 Some(Node::Arm(ref a)) => Some(&*a.attrs),
893 Some(Node::GenericParam(param)) => Some(¶m.attrs[..]),
894 // Unit/tuple structs/variants take the attributes straight from
895 // the struct/variant definition.
896 Some(Node::Ctor(..)) => return self.attrs(self.get_parent_item(id)),
897 Some(Node::Crate(item)) => Some(&item.attrs[..]),
903 pub fn span(&self, hir_id: HirId) -> Span {
904 match self.find_entry(hir_id).map(|entry| entry.node) {
905 Some(Node::Param(param)) => param.span,
906 Some(Node::Item(item)) => item.span,
907 Some(Node::ForeignItem(foreign_item)) => foreign_item.span,
908 Some(Node::TraitItem(trait_method)) => trait_method.span,
909 Some(Node::ImplItem(impl_item)) => impl_item.span,
910 Some(Node::Variant(variant)) => variant.span,
911 Some(Node::Field(field)) => field.span,
912 Some(Node::AnonConst(constant)) => self.body(constant.body).value.span,
913 Some(Node::Expr(expr)) => expr.span,
914 Some(Node::Stmt(stmt)) => stmt.span,
915 Some(Node::PathSegment(seg)) => seg.ident.span,
916 Some(Node::Ty(ty)) => ty.span,
917 Some(Node::TraitRef(tr)) => tr.path.span,
918 Some(Node::Binding(pat)) => pat.span,
919 Some(Node::Pat(pat)) => pat.span,
920 Some(Node::Arm(arm)) => arm.span,
921 Some(Node::Block(block)) => block.span,
922 Some(Node::Ctor(..)) => match self.find(self.get_parent_node(hir_id)) {
923 Some(Node::Item(item)) => item.span,
924 Some(Node::Variant(variant)) => variant.span,
927 Some(Node::Lifetime(lifetime)) => lifetime.span,
928 Some(Node::GenericParam(param)) => param.span,
929 Some(Node::Visibility(&Spanned {
930 node: VisibilityKind::Restricted { ref path, .. },
933 Some(Node::Visibility(v)) => bug!("unexpected Visibility {:?}", v),
934 Some(Node::Local(local)) => local.span,
935 Some(Node::MacroDef(macro_def)) => macro_def.span,
936 Some(Node::Crate(item)) => item.span,
937 None => bug!("hir::map::Map::span: id not in map: {:?}", hir_id),
941 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
942 self.as_local_hir_id(id).map(|id| self.span(id))
945 pub fn res_span(&self, res: Res) -> Option<Span> {
948 Res::Local(id) => Some(self.span(id)),
949 res => self.span_if_local(res.opt_def_id()?),
953 pub fn node_to_string(&self, id: HirId) -> String {
954 hir_id_to_string(self, id, true)
957 pub fn hir_to_user_string(&self, id: HirId) -> String {
958 hir_id_to_string(self, id, false)
961 pub fn hir_to_pretty_string(&self, id: HirId) -> String {
962 print::to_string(self, |s| s.print_node(self.get(id)))
966 impl<'hir> intravisit::Map<'hir> for Map<'hir> {
967 fn body(&self, id: BodyId) -> &'hir Body<'hir> {
971 fn item(&self, id: HirId) -> &'hir Item<'hir> {
975 fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
979 fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
985 fn name(&self) -> Name;
988 impl<T: Named> Named for Spanned<T> {
989 fn name(&self) -> Name {
994 impl Named for Item<'_> {
995 fn name(&self) -> Name {
999 impl Named for ForeignItem<'_> {
1000 fn name(&self) -> Name {
1004 impl Named for Variant<'_> {
1005 fn name(&self) -> Name {
1009 impl Named for StructField<'_> {
1010 fn name(&self) -> Name {
1014 impl Named for TraitItem<'_> {
1015 fn name(&self) -> Name {
1019 impl Named for ImplItem<'_> {
1020 fn name(&self) -> Name {
1025 pub(super) fn index_hir<'tcx>(tcx: TyCtxt<'tcx>, cnum: CrateNum) -> &'tcx IndexedHir<'tcx> {
1026 assert_eq!(cnum, LOCAL_CRATE);
1028 let _prof_timer = tcx.sess.prof.generic_activity("build_hir_map");
1030 // Build the reverse mapping of `node_to_hir_id`.
1031 let hir_to_node_id = tcx
1035 .map(|(node_id, &hir_id)| (hir_id, node_id))
1038 let (owner_map, owner_items_map, crate_hash) = {
1039 let hcx = tcx.create_stable_hashing_context();
1041 let mut collector = NodeCollector::root(
1044 tcx.untracked_crate,
1049 intravisit::walk_crate(&mut collector, tcx.untracked_crate);
1051 let crate_disambiguator = tcx.sess.local_crate_disambiguator();
1052 let cmdline_args = tcx.sess.opts.dep_tracking_hash();
1053 collector.finalize_and_compute_crate_hash(crate_disambiguator, &*tcx.cstore, cmdline_args)
1056 let map = tcx.arena.alloc(IndexedHir {
1059 owner_items_map: owner_items_map.into_iter().map(|(k, v)| (k, &*v)).collect(),
1066 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1067 /// except it avoids creating a dependency on the whole crate.
1068 impl<'hir> print::PpAnn for Map<'hir> {
1069 fn nested(&self, state: &mut print::State<'_>, nested: print::Nested) {
1071 Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1072 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1073 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1074 Nested::Body(id) => state.print_expr(&self.body(id).value),
1075 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
1080 fn hir_id_to_string(map: &Map<'_>, id: HirId, include_id: bool) -> String {
1081 let id_str = format!(" (hir_id={})", id);
1082 let id_str = if include_id { &id_str[..] } else { "" };
1085 // This functionality is used for debugging, try to use `TyCtxt` to get
1086 // the user-friendly path, otherwise fall back to stringifying `DefPath`.
1087 crate::ty::tls::with_opt(|tcx| {
1088 if let Some(tcx) = tcx {
1089 let def_id = map.local_def_id(id);
1090 tcx.def_path_str(def_id)
1091 } else if let Some(path) = map.def_path_from_hir_id(id) {
1094 .map(|elem| elem.data.to_string())
1095 .collect::<Vec<_>>()
1098 String::from("<missing path>")
1103 match map.find(id) {
1104 Some(Node::Item(item)) => {
1105 let item_str = match item.kind {
1106 ItemKind::ExternCrate(..) => "extern crate",
1107 ItemKind::Use(..) => "use",
1108 ItemKind::Static(..) => "static",
1109 ItemKind::Const(..) => "const",
1110 ItemKind::Fn(..) => "fn",
1111 ItemKind::Mod(..) => "mod",
1112 ItemKind::ForeignMod(..) => "foreign mod",
1113 ItemKind::GlobalAsm(..) => "global asm",
1114 ItemKind::TyAlias(..) => "ty",
1115 ItemKind::OpaqueTy(..) => "opaque type",
1116 ItemKind::Enum(..) => "enum",
1117 ItemKind::Struct(..) => "struct",
1118 ItemKind::Union(..) => "union",
1119 ItemKind::Trait(..) => "trait",
1120 ItemKind::TraitAlias(..) => "trait alias",
1121 ItemKind::Impl { .. } => "impl",
1123 format!("{} {}{}", item_str, path_str(), id_str)
1125 Some(Node::ForeignItem(_)) => format!("foreign item {}{}", path_str(), id_str),
1126 Some(Node::ImplItem(ii)) => match ii.kind {
1127 ImplItemKind::Const(..) => {
1128 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1130 ImplItemKind::Method(..) => format!("method {} in {}{}", ii.ident, path_str(), id_str),
1131 ImplItemKind::TyAlias(_) => {
1132 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1134 ImplItemKind::OpaqueTy(_) => {
1135 format!("assoc opaque type {} in {}{}", ii.ident, path_str(), id_str)
1138 Some(Node::TraitItem(ti)) => {
1139 let kind = match ti.kind {
1140 TraitItemKind::Const(..) => "assoc constant",
1141 TraitItemKind::Fn(..) => "trait method",
1142 TraitItemKind::Type(..) => "assoc type",
1145 format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1147 Some(Node::Variant(ref variant)) => {
1148 format!("variant {} in {}{}", variant.ident, path_str(), id_str)
1150 Some(Node::Field(ref field)) => {
1151 format!("field {} in {}{}", field.ident, path_str(), id_str)
1153 Some(Node::AnonConst(_)) => format!("const {}{}", map.hir_to_pretty_string(id), id_str),
1154 Some(Node::Expr(_)) => format!("expr {}{}", map.hir_to_pretty_string(id), id_str),
1155 Some(Node::Stmt(_)) => format!("stmt {}{}", map.hir_to_pretty_string(id), id_str),
1156 Some(Node::PathSegment(_)) => {
1157 format!("path segment {}{}", map.hir_to_pretty_string(id), id_str)
1159 Some(Node::Ty(_)) => format!("type {}{}", map.hir_to_pretty_string(id), id_str),
1160 Some(Node::TraitRef(_)) => format!("trait_ref {}{}", map.hir_to_pretty_string(id), id_str),
1161 Some(Node::Binding(_)) => format!("local {}{}", map.hir_to_pretty_string(id), id_str),
1162 Some(Node::Pat(_)) => format!("pat {}{}", map.hir_to_pretty_string(id), id_str),
1163 Some(Node::Param(_)) => format!("param {}{}", map.hir_to_pretty_string(id), id_str),
1164 Some(Node::Arm(_)) => format!("arm {}{}", map.hir_to_pretty_string(id), id_str),
1165 Some(Node::Block(_)) => format!("block {}{}", map.hir_to_pretty_string(id), id_str),
1166 Some(Node::Local(_)) => format!("local {}{}", map.hir_to_pretty_string(id), id_str),
1167 Some(Node::Ctor(..)) => format!("ctor {}{}", path_str(), id_str),
1168 Some(Node::Lifetime(_)) => format!("lifetime {}{}", map.hir_to_pretty_string(id), id_str),
1169 Some(Node::GenericParam(ref param)) => format!("generic_param {:?}{}", param, id_str),
1170 Some(Node::Visibility(ref vis)) => format!("visibility {:?}{}", vis, id_str),
1171 Some(Node::MacroDef(_)) => format!("macro {}{}", path_str(), id_str),
1172 Some(Node::Crate(..)) => String::from("root_crate"),
1173 None => format!("unknown node{}", id_str),
1177 pub fn provide(providers: &mut Providers<'_>) {
1178 providers.def_kind = |tcx, def_id| {
1179 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
1180 tcx.hir().def_kind(hir_id)
1182 bug!("calling local def_kind query provider for upstream DefId: {:?}", def_id);