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::svh::Svh;
11 use rustc_hir::def::{DefKind, Res};
12 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE};
13 use rustc_hir::intravisit;
14 use rustc_hir::itemlikevisit::ItemLikeVisitor;
15 use rustc_hir::print::Nested;
17 use rustc_index::vec::IndexVec;
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;
28 pub use hir_id_validator::check_crate;
30 /// Represents an entry and its parent `HirId`.
31 #[derive(Copy, Clone, Debug)]
32 pub struct Entry<'hir> {
37 impl<'hir> Entry<'hir> {
38 fn parent_node(self) -> Option<HirId> {
40 Node::Crate(_) | Node::MacroDef(_) => None,
41 _ => Some(self.parent),
46 fn fn_decl<'hir>(node: Node<'hir>) -> Option<&'hir FnDecl<'hir>> {
48 Node::Item(ref item) => match item.kind {
49 ItemKind::Fn(ref sig, _, _) => Some(&sig.decl),
53 Node::TraitItem(ref item) => match item.kind {
54 TraitItemKind::Fn(ref sig, _) => Some(&sig.decl),
58 Node::ImplItem(ref item) => match item.kind {
59 ImplItemKind::Fn(ref sig, _) => Some(&sig.decl),
63 Node::Expr(ref expr) => match expr.kind {
64 ExprKind::Closure(_, ref fn_decl, ..) => Some(fn_decl),
72 fn fn_sig<'hir>(node: Node<'hir>) -> Option<&'hir FnSig<'hir>> {
74 Node::Item(item) => match &item.kind {
75 ItemKind::Fn(sig, _, _) => Some(sig),
79 Node::TraitItem(item) => match &item.kind {
80 TraitItemKind::Fn(sig, _) => Some(sig),
84 Node::ImplItem(item) => match &item.kind {
85 ImplItemKind::Fn(sig, _) => Some(sig),
93 fn associated_body<'hir>(node: Node<'hir>) -> Option<BodyId> {
95 Node::Item(item) => match item.kind {
96 ItemKind::Const(_, body) | ItemKind::Static(.., body) | ItemKind::Fn(.., body) => {
102 Node::TraitItem(item) => match item.kind {
103 TraitItemKind::Const(_, Some(body)) | TraitItemKind::Fn(_, TraitFn::Provided(body)) => {
109 Node::ImplItem(item) => match item.kind {
110 ImplItemKind::Const(_, body) | ImplItemKind::Fn(_, body) => Some(body),
114 Node::AnonConst(constant) => Some(constant.body),
116 Node::Expr(expr) => match expr.kind {
117 ExprKind::Closure(.., body, _, _) => Some(body),
125 fn is_body_owner<'hir>(node: Node<'hir>, hir_id: HirId) -> bool {
126 match associated_body(node) {
127 Some(b) => b.hir_id == hir_id,
132 pub(super) struct HirOwnerData<'hir> {
133 pub(super) signature: Option<&'hir HirOwner<'hir>>,
134 pub(super) with_bodies: Option<&'hir mut HirOwnerItems<'hir>>,
137 pub struct IndexedHir<'hir> {
138 /// The SVH of the local crate.
141 pub(super) map: IndexVec<LocalDefId, HirOwnerData<'hir>>,
144 #[derive(Copy, Clone)]
145 pub struct Map<'hir> {
146 pub(super) tcx: TyCtxt<'hir>,
149 /// An iterator that walks up the ancestor tree of a given `HirId`.
150 /// Constructed using `tcx.hir().parent_iter(hir_id)`.
151 pub struct ParentHirIterator<'map, 'hir> {
153 map: &'map Map<'hir>,
156 impl<'hir> Iterator for ParentHirIterator<'_, 'hir> {
157 type Item = (HirId, Node<'hir>);
159 fn next(&mut self) -> Option<Self::Item> {
160 if self.current_id == CRATE_HIR_ID {
164 // There are nodes that do not have entries, so we need to skip them.
165 let parent_id = self.map.get_parent_node(self.current_id);
167 if parent_id == self.current_id {
168 self.current_id = CRATE_HIR_ID;
172 self.current_id = parent_id;
173 if let Some(entry) = self.map.find_entry(parent_id) {
174 return Some((parent_id, entry.node));
176 // If this `HirId` doesn't have an `Entry`, skip it and look for its `parent_id`.
181 impl<'hir> Map<'hir> {
182 pub fn krate(&self) -> &'hir Crate<'hir> {
183 self.tcx.hir_crate(LOCAL_CRATE)
187 pub fn definitions(&self) -> &'hir Definitions {
188 &self.tcx.definitions
191 pub fn def_key(&self, def_id: LocalDefId) -> DefKey {
192 self.tcx.definitions.def_key(def_id)
195 pub fn def_path_from_hir_id(&self, id: HirId) -> Option<DefPath> {
196 self.opt_local_def_id(id).map(|def_id| self.def_path(def_id.expect_local()))
199 pub fn def_path(&self, def_id: LocalDefId) -> DefPath {
200 self.tcx.definitions.def_path(def_id)
203 // FIXME(eddyb) this function can and should return `LocalDefId`.
205 pub fn local_def_id_from_node_id(&self, node: NodeId) -> DefId {
206 self.opt_local_def_id_from_node_id(node).unwrap_or_else(|| {
207 let hir_id = self.node_to_hir_id(node);
209 "local_def_id_from_node_id: no entry for `{}`, which has a map of `{:?}`",
211 self.find_entry(hir_id)
216 // FIXME(eddyb) this function can and should return `LocalDefId`.
218 pub fn local_def_id(&self, hir_id: HirId) -> DefId {
219 self.opt_local_def_id(hir_id).unwrap_or_else(|| {
221 "local_def_id: no entry for `{:?}`, which has a map of `{:?}`",
223 self.find_entry(hir_id)
229 pub fn opt_local_def_id(&self, hir_id: HirId) -> Option<DefId> {
230 let node_id = self.hir_to_node_id(hir_id);
231 self.opt_local_def_id_from_node_id(node_id)
235 pub fn opt_local_def_id_from_node_id(&self, node: NodeId) -> Option<DefId> {
236 Some(self.tcx.definitions.opt_local_def_id(node)?.to_def_id())
240 pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
241 self.tcx.definitions.as_local_node_id(def_id)
245 pub fn as_local_hir_id(&self, def_id: DefId) -> Option<HirId> {
246 self.tcx.definitions.as_local_hir_id(def_id)
250 pub fn hir_to_node_id(&self, hir_id: HirId) -> NodeId {
251 self.tcx.definitions.hir_to_node_id(hir_id)
255 pub fn node_to_hir_id(&self, node_id: NodeId) -> HirId {
256 self.tcx.definitions.node_to_hir_id(node_id)
260 pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
261 self.tcx.definitions.local_def_id_to_hir_id(def_id)
264 pub fn def_kind(&self, hir_id: HirId) -> Option<DefKind> {
265 let node = self.find(hir_id)?;
268 Node::Item(item) => match item.kind {
269 ItemKind::Static(..) => DefKind::Static,
270 ItemKind::Const(..) => DefKind::Const,
271 ItemKind::Fn(..) => DefKind::Fn,
272 ItemKind::Mod(..) => DefKind::Mod,
273 ItemKind::OpaqueTy(..) => DefKind::OpaqueTy,
274 ItemKind::TyAlias(..) => DefKind::TyAlias,
275 ItemKind::Enum(..) => DefKind::Enum,
276 ItemKind::Struct(..) => DefKind::Struct,
277 ItemKind::Union(..) => DefKind::Union,
278 ItemKind::Trait(..) => DefKind::Trait,
279 ItemKind::TraitAlias(..) => DefKind::TraitAlias,
280 ItemKind::ExternCrate(_)
282 | ItemKind::ForeignMod(..)
283 | ItemKind::GlobalAsm(..)
284 | ItemKind::Impl { .. } => return None,
286 Node::ForeignItem(item) => match item.kind {
287 ForeignItemKind::Fn(..) => DefKind::Fn,
288 ForeignItemKind::Static(..) => DefKind::Static,
289 ForeignItemKind::Type => DefKind::ForeignTy,
291 Node::TraitItem(item) => match item.kind {
292 TraitItemKind::Const(..) => DefKind::AssocConst,
293 TraitItemKind::Fn(..) => DefKind::AssocFn,
294 TraitItemKind::Type(..) => DefKind::AssocTy,
296 Node::ImplItem(item) => match item.kind {
297 ImplItemKind::Const(..) => DefKind::AssocConst,
298 ImplItemKind::Fn(..) => DefKind::AssocFn,
299 ImplItemKind::TyAlias(..) => DefKind::AssocTy,
300 ImplItemKind::OpaqueTy(..) => DefKind::AssocOpaqueTy,
302 Node::Variant(_) => DefKind::Variant,
303 Node::Ctor(variant_data) => {
304 // FIXME(eddyb) is this even possible, if we have a `Node::Ctor`?
305 variant_data.ctor_hir_id()?;
307 let ctor_of = match self.find(self.get_parent_node(hir_id)) {
308 Some(Node::Item(..)) => def::CtorOf::Struct,
309 Some(Node::Variant(..)) => def::CtorOf::Variant,
312 DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data))
318 | Node::PathSegment(_)
327 | Node::Visibility(_)
329 | Node::Crate(_) => return None,
330 Node::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
331 Node::GenericParam(param) => match param.kind {
332 GenericParamKind::Lifetime { .. } => return None,
333 GenericParamKind::Type { .. } => DefKind::TyParam,
334 GenericParamKind::Const { .. } => DefKind::ConstParam,
339 fn find_entry(&self, id: HirId) -> Option<Entry<'hir>> {
340 Some(self.get_entry(id))
343 fn get_entry(&self, id: HirId) -> Entry<'hir> {
344 if id.local_id == ItemLocalId::from_u32(0) {
345 let owner = self.tcx.hir_owner(id.owner);
346 Entry { parent: owner.parent, node: owner.node }
348 let owner = self.tcx.hir_owner_items(id.owner);
349 let item = owner.items[id.local_id].as_ref().unwrap();
350 Entry { parent: HirId { owner: id.owner, local_id: item.parent }, node: item.node }
354 pub fn item(&self, id: HirId) -> &'hir Item<'hir> {
355 match self.find(id).unwrap() {
356 Node::Item(item) => item,
361 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
362 match self.find(id.hir_id).unwrap() {
363 Node::TraitItem(item) => item,
368 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
369 match self.find(id.hir_id).unwrap() {
370 Node::ImplItem(item) => item,
375 pub fn body(&self, id: BodyId) -> &'hir Body<'hir> {
376 self.tcx.hir_owner_items(id.hir_id.owner).bodies.get(&id.hir_id.local_id).unwrap()
379 pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnDecl<'hir>> {
380 if let Some(node) = self.find(hir_id) {
383 bug!("no node for hir_id `{}`", hir_id)
387 pub fn fn_sig_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnSig<'hir>> {
388 if let Some(node) = self.find(hir_id) {
391 bug!("no node for hir_id `{}`", hir_id)
395 /// Returns the `HirId` that corresponds to the definition of
396 /// which this is the body of, i.e., a `fn`, `const` or `static`
397 /// item (possibly associated), a closure, or a `hir::AnonConst`.
398 pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> HirId {
399 let parent = self.get_parent_node(hir_id);
400 assert!(self.find(parent).map_or(false, |n| is_body_owner(n, hir_id)));
404 // FIXME(eddyb) this function can and should return `LocalDefId`.
405 pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
406 self.local_def_id(self.body_owner(id))
409 /// Given a `HirId`, returns the `BodyId` associated with it,
410 /// if the node is a body owner, otherwise returns `None`.
411 pub fn maybe_body_owned_by(&self, hir_id: HirId) -> Option<BodyId> {
412 if let Some(node) = self.find(hir_id) {
413 associated_body(node)
415 bug!("no entry for id `{}`", hir_id)
419 /// Given a body owner's id, returns the `BodyId` associated with it.
420 pub fn body_owned_by(&self, id: HirId) -> BodyId {
421 self.maybe_body_owned_by(id).unwrap_or_else(|| {
424 "body_owned_by: {} has no associated body",
425 self.node_to_string(id)
430 pub fn body_owner_kind(&self, id: HirId) -> BodyOwnerKind {
432 Node::Item(&Item { kind: ItemKind::Const(..), .. })
433 | Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. })
434 | Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. })
435 | Node::AnonConst(_) => BodyOwnerKind::Const,
437 | Node::Item(&Item { kind: ItemKind::Fn(..), .. })
438 | Node::TraitItem(&TraitItem { kind: TraitItemKind::Fn(..), .. })
439 | Node::ImplItem(&ImplItem { kind: ImplItemKind::Fn(..), .. }) => BodyOwnerKind::Fn,
440 Node::Item(&Item { kind: ItemKind::Static(_, m, _), .. }) => BodyOwnerKind::Static(m),
441 Node::Expr(&Expr { kind: ExprKind::Closure(..), .. }) => BodyOwnerKind::Closure,
442 node => bug!("{:#?} is not a body node", node),
446 pub fn ty_param_owner(&self, id: HirId) -> HirId {
448 Node::Item(&Item { kind: ItemKind::Trait(..), .. })
449 | Node::Item(&Item { kind: ItemKind::TraitAlias(..), .. }) => id,
450 Node::GenericParam(_) => self.get_parent_node(id),
451 _ => bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id)),
455 pub fn ty_param_name(&self, id: HirId) -> Name {
457 Node::Item(&Item { kind: ItemKind::Trait(..), .. })
458 | Node::Item(&Item { kind: ItemKind::TraitAlias(..), .. }) => kw::SelfUpper,
459 Node::GenericParam(param) => param.name.ident().name,
460 _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
464 pub fn trait_impls(&self, trait_did: DefId) -> &'hir [HirId] {
465 self.tcx.all_local_trait_impls(LOCAL_CRATE).get(&trait_did).map_or(&[], |xs| &xs[..])
468 /// Gets the attributes on the crate. This is preferable to
469 /// invoking `krate.attrs` because it registers a tighter
470 /// dep-graph access.
471 pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
472 match self.get_entry(CRATE_HIR_ID).node {
473 Node::Crate(item) => item.attrs,
478 pub fn get_module(&self, module: DefId) -> (&'hir Mod<'hir>, Span, HirId) {
479 let hir_id = self.as_local_hir_id(module).unwrap();
480 match self.get_entry(hir_id).node {
481 Node::Item(&Item { span, kind: ItemKind::Mod(ref m), .. }) => (m, span, hir_id),
482 Node::Crate(item) => (&item.module, item.span, hir_id),
483 node => panic!("not a module: {:?}", node),
487 pub fn visit_item_likes_in_module<V>(&self, module: DefId, visitor: &mut V)
489 V: ItemLikeVisitor<'hir>,
491 let module = self.tcx.hir_module_items(module.expect_local());
493 for id in &module.items {
494 visitor.visit_item(self.expect_item(*id));
497 for id in &module.trait_items {
498 visitor.visit_trait_item(self.expect_trait_item(id.hir_id));
501 for id in &module.impl_items {
502 visitor.visit_impl_item(self.expect_impl_item(id.hir_id));
506 /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found.
507 pub fn get(&self, id: HirId) -> Node<'hir> {
508 self.find(id).unwrap_or_else(|| bug!("couldn't find hir id {} in the HIR map", id))
511 pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
512 self.as_local_hir_id(id).map(|id| self.get(id))
515 pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics<'hir>> {
516 self.get_if_local(id).and_then(|node| match node {
517 Node::ImplItem(ref impl_item) => Some(&impl_item.generics),
518 Node::TraitItem(ref trait_item) => Some(&trait_item.generics),
519 Node::Item(ref item) => match item.kind {
520 ItemKind::Fn(_, ref generics, _)
521 | ItemKind::TyAlias(_, ref generics)
522 | ItemKind::Enum(_, ref generics)
523 | ItemKind::Struct(_, ref generics)
524 | ItemKind::Union(_, ref generics)
525 | ItemKind::Trait(_, _, ref generics, ..)
526 | ItemKind::TraitAlias(ref generics, _)
527 | ItemKind::Impl { ref generics, .. } => Some(generics),
534 /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
535 pub fn find(&self, hir_id: HirId) -> Option<Node<'hir>> {
536 let node = self.get_entry(hir_id).node;
537 if let Node::Crate(..) = node { None } else { Some(node) }
540 /// Similar to `get_parent`; returns the parent HIR Id, or just `hir_id` if there
541 /// is no parent. Note that the parent may be `CRATE_HIR_ID`, which is not itself
542 /// present in the map, so passing the return value of `get_parent_node` to
543 /// `get` may in fact panic.
544 /// This function returns the immediate parent in the HIR, whereas `get_parent`
545 /// returns the enclosing item. Note that this might not be the actual parent
546 /// node in the HIR -- some kinds of nodes are not in the map and these will
547 /// never appear as the parent node. Thus, you can always walk the parent nodes
548 /// from a node to the root of the HIR (unless you get back the same ID here,
549 /// which can happen if the ID is not in the map itself or is just weird).
550 pub fn get_parent_node(&self, hir_id: HirId) -> HirId {
551 self.get_entry(hir_id).parent_node().unwrap_or(hir_id)
554 /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
555 /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`.
556 pub fn parent_iter(&self, current_id: HirId) -> ParentHirIterator<'_, 'hir> {
557 ParentHirIterator { current_id, map: self }
560 /// Checks if the node is an argument. An argument is a local variable whose
561 /// immediate parent is an item or a closure.
562 pub fn is_argument(&self, id: HirId) -> bool {
563 match self.find(id) {
564 Some(Node::Binding(_)) => (),
567 match self.find(self.get_parent_node(id)) {
568 Some(Node::Item(_)) | Some(Node::TraitItem(_)) | Some(Node::ImplItem(_)) => true,
569 Some(Node::Expr(e)) => match e.kind {
570 ExprKind::Closure(..) => true,
577 /// Whether the expression pointed at by `hir_id` belongs to a `const` evaluation context.
578 /// Used exclusively for diagnostics, to avoid suggestion function calls.
579 pub fn is_const_context(&self, hir_id: HirId) -> bool {
580 let parent_id = self.get_parent_item(hir_id);
581 match self.get(parent_id) {
582 Node::Item(&Item { kind: ItemKind::Const(..), .. })
583 | Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. })
584 | Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. })
586 | Node::Item(&Item { kind: ItemKind::Static(..), .. }) => true,
587 Node::Item(&Item { kind: ItemKind::Fn(ref sig, ..), .. }) => {
588 sig.header.constness == Constness::Const
594 /// Whether `hir_id` corresponds to a `mod` or a crate.
595 pub fn is_hir_id_module(&self, hir_id: HirId) -> bool {
596 match self.get_entry(hir_id) {
597 Entry { node: Node::Item(Item { kind: ItemKind::Mod(_), .. }), .. }
598 | Entry { node: Node::Crate(..), .. } => true,
603 /// Retrieves the `HirId` for `id`'s enclosing method, unless there's a
604 /// `while` or `loop` before reaching it, as block tail returns are not
605 /// available in them.
608 /// fn foo(x: usize) -> bool {
610 /// true // If `get_return_block` gets passed the `id` corresponding
611 /// } else { // to this, it will return `foo`'s `HirId`.
618 /// fn foo(x: usize) -> bool {
620 /// true // If `get_return_block` gets passed the `id` corresponding
621 /// } // to this, it will return `None`.
625 pub fn get_return_block(&self, id: HirId) -> Option<HirId> {
626 let mut iter = self.parent_iter(id).peekable();
627 let mut ignore_tail = false;
628 if let Some(entry) = self.find_entry(id) {
629 if let Node::Expr(Expr { kind: ExprKind::Ret(_), .. }) = entry.node {
630 // When dealing with `return` statements, we don't care about climbing only tail
635 while let Some((hir_id, node)) = iter.next() {
636 if let (Some((_, next_node)), false) = (iter.peek(), ignore_tail) {
638 Node::Block(Block { expr: None, .. }) => return None,
639 Node::Block(Block { expr: Some(expr), .. }) => {
640 if hir_id != expr.hir_id {
641 // The current node is not the tail expression of its parent.
650 | Node::ForeignItem(_)
652 | Node::Expr(Expr { kind: ExprKind::Closure(..), .. })
653 | Node::ImplItem(_) => return Some(hir_id),
654 Node::Expr(ref expr) => {
656 // Ignore `return`s on the first iteration
657 ExprKind::Loop(..) | ExprKind::Ret(..) => return None,
661 Node::Local(_) => return None,
668 /// Retrieves the `HirId` for `id`'s parent item, or `id` itself if no
669 /// parent item is in this map. The "parent item" is the closest parent node
670 /// in the HIR which is recorded by the map and is an item, either an item
671 /// in a module, trait, or impl.
672 pub fn get_parent_item(&self, hir_id: HirId) -> HirId {
673 for (hir_id, node) in self.parent_iter(hir_id) {
677 | Node::ForeignItem(_)
679 | Node::ImplItem(_) => return hir_id,
686 /// Returns the `HirId` of `id`'s nearest module parent, or `id` itself if no
687 /// module parent is in this map.
688 pub(super) fn get_module_parent_node(&self, hir_id: HirId) -> HirId {
689 for (hir_id, node) in self.parent_iter(hir_id) {
690 if let Node::Item(&Item { kind: ItemKind::Mod(_), .. }) = node {
697 /// When on a match arm tail expression or on a match arm, give back the enclosing `match`
700 /// Used by error reporting when there's a type error in a match arm caused by the `match`
701 /// expression needing to be unit.
702 pub fn get_match_if_cause(&self, hir_id: HirId) -> Option<&'hir Expr<'hir>> {
703 for (_, node) in self.parent_iter(hir_id) {
705 Node::Item(_) | Node::ForeignItem(_) | Node::TraitItem(_) | Node::ImplItem(_) => {
708 Node::Expr(expr) => match expr.kind {
709 ExprKind::Match(_, _, _) => return Some(expr),
712 Node::Stmt(stmt) => match stmt.kind {
713 StmtKind::Local(_) => break,
722 /// Returns the nearest enclosing scope. A scope is roughly an item or block.
723 pub fn get_enclosing_scope(&self, hir_id: HirId) -> Option<HirId> {
724 for (hir_id, node) in self.parent_iter(hir_id) {
726 Node::Item(i) => match i.kind {
730 | ItemKind::Struct(..)
731 | ItemKind::Union(..)
732 | ItemKind::Trait(..)
733 | ItemKind::Impl { .. } => true,
736 Node::ForeignItem(fi) => match fi.kind {
737 ForeignItemKind::Fn(..) => true,
740 Node::TraitItem(ti) => match ti.kind {
741 TraitItemKind::Fn(..) => true,
744 Node::ImplItem(ii) => match ii.kind {
745 ImplItemKind::Fn(..) => true,
748 Node::Block(_) => true,
757 /// Returns the defining scope for an opaque type definition.
758 pub fn get_defining_scope(&self, id: HirId) -> HirId {
761 scope = self.get_enclosing_scope(scope).unwrap_or(CRATE_HIR_ID);
762 if scope == CRATE_HIR_ID {
765 match self.get(scope) {
766 Node::Item(i) => match i.kind {
767 ItemKind::OpaqueTy(OpaqueTy { impl_trait_fn: None, .. }) => {}
777 // FIXME(eddyb) this function can and should return `LocalDefId`.
778 pub fn get_parent_did(&self, id: HirId) -> DefId {
779 self.local_def_id(self.get_parent_item(id))
782 pub fn get_foreign_abi(&self, hir_id: HirId) -> Abi {
783 let parent = self.get_parent_item(hir_id);
784 if let Some(entry) = self.find_entry(parent) {
786 node: Node::Item(Item { kind: ItemKind::ForeignMod(ref nm), .. }), ..
792 bug!("expected foreign mod or inlined parent, found {}", self.node_to_string(parent))
795 pub fn expect_item(&self, id: HirId) -> &'hir Item<'hir> {
796 match self.find(id) {
797 Some(Node::Item(item)) => item,
798 _ => bug!("expected item, found {}", self.node_to_string(id)),
802 pub fn expect_impl_item(&self, id: HirId) -> &'hir ImplItem<'hir> {
803 match self.find(id) {
804 Some(Node::ImplItem(item)) => item,
805 _ => bug!("expected impl item, found {}", self.node_to_string(id)),
809 pub fn expect_trait_item(&self, id: HirId) -> &'hir TraitItem<'hir> {
810 match self.find(id) {
811 Some(Node::TraitItem(item)) => item,
812 _ => bug!("expected trait item, found {}", self.node_to_string(id)),
816 pub fn expect_variant_data(&self, id: HirId) -> &'hir VariantData<'hir> {
817 match self.find(id) {
818 Some(Node::Item(i)) => match i.kind {
819 ItemKind::Struct(ref struct_def, _) | ItemKind::Union(ref struct_def, _) => {
822 _ => bug!("struct ID bound to non-struct {}", self.node_to_string(id)),
824 Some(Node::Variant(variant)) => &variant.data,
825 Some(Node::Ctor(data)) => data,
826 _ => bug!("expected struct or variant, found {}", self.node_to_string(id)),
830 pub fn expect_variant(&self, id: HirId) -> &'hir Variant<'hir> {
831 match self.find(id) {
832 Some(Node::Variant(variant)) => variant,
833 _ => bug!("expected variant, found {}", self.node_to_string(id)),
837 pub fn expect_foreign_item(&self, id: HirId) -> &'hir ForeignItem<'hir> {
838 match self.find(id) {
839 Some(Node::ForeignItem(item)) => item,
840 _ => bug!("expected foreign item, found {}", self.node_to_string(id)),
844 pub fn expect_expr(&self, id: HirId) -> &'hir Expr<'hir> {
845 match self.find(id) {
846 Some(Node::Expr(expr)) => expr,
847 _ => bug!("expected expr, found {}", self.node_to_string(id)),
851 pub fn opt_name(&self, id: HirId) -> Option<Name> {
852 Some(match self.get(id) {
853 Node::Item(i) => i.ident.name,
854 Node::ForeignItem(fi) => fi.ident.name,
855 Node::ImplItem(ii) => ii.ident.name,
856 Node::TraitItem(ti) => ti.ident.name,
857 Node::Variant(v) => v.ident.name,
858 Node::Field(f) => f.ident.name,
859 Node::Lifetime(lt) => lt.name.ident().name,
860 Node::GenericParam(param) => param.name.ident().name,
861 Node::Binding(&Pat { kind: PatKind::Binding(_, _, l, _), .. }) => l.name,
862 Node::Ctor(..) => self.name(self.get_parent_item(id)),
867 pub fn name(&self, id: HirId) -> Name {
868 match self.opt_name(id) {
870 None => bug!("no name for {}", self.node_to_string(id)),
874 /// Given a node ID, gets a list of attributes associated with the AST
875 /// corresponding to the node-ID.
876 pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] {
877 let attrs = match self.find_entry(id).map(|entry| entry.node) {
878 Some(Node::Param(a)) => Some(&a.attrs[..]),
879 Some(Node::Local(l)) => Some(&l.attrs[..]),
880 Some(Node::Item(i)) => Some(&i.attrs[..]),
881 Some(Node::ForeignItem(fi)) => Some(&fi.attrs[..]),
882 Some(Node::TraitItem(ref ti)) => Some(&ti.attrs[..]),
883 Some(Node::ImplItem(ref ii)) => Some(&ii.attrs[..]),
884 Some(Node::Variant(ref v)) => Some(&v.attrs[..]),
885 Some(Node::Field(ref f)) => Some(&f.attrs[..]),
886 Some(Node::Expr(ref e)) => Some(&*e.attrs),
887 Some(Node::Stmt(ref s)) => Some(s.kind.attrs()),
888 Some(Node::Arm(ref a)) => Some(&*a.attrs),
889 Some(Node::GenericParam(param)) => Some(¶m.attrs[..]),
890 // Unit/tuple structs/variants take the attributes straight from
891 // the struct/variant definition.
892 Some(Node::Ctor(..)) => return self.attrs(self.get_parent_item(id)),
893 Some(Node::Crate(item)) => Some(&item.attrs[..]),
899 pub fn span(&self, hir_id: HirId) -> Span {
900 match self.find_entry(hir_id).map(|entry| entry.node) {
901 Some(Node::Param(param)) => param.span,
902 Some(Node::Item(item)) => item.span,
903 Some(Node::ForeignItem(foreign_item)) => foreign_item.span,
904 Some(Node::TraitItem(trait_method)) => trait_method.span,
905 Some(Node::ImplItem(impl_item)) => impl_item.span,
906 Some(Node::Variant(variant)) => variant.span,
907 Some(Node::Field(field)) => field.span,
908 Some(Node::AnonConst(constant)) => self.body(constant.body).value.span,
909 Some(Node::Expr(expr)) => expr.span,
910 Some(Node::Stmt(stmt)) => stmt.span,
911 Some(Node::PathSegment(seg)) => seg.ident.span,
912 Some(Node::Ty(ty)) => ty.span,
913 Some(Node::TraitRef(tr)) => tr.path.span,
914 Some(Node::Binding(pat)) => pat.span,
915 Some(Node::Pat(pat)) => pat.span,
916 Some(Node::Arm(arm)) => arm.span,
917 Some(Node::Block(block)) => block.span,
918 Some(Node::Ctor(..)) => match self.find(self.get_parent_node(hir_id)) {
919 Some(Node::Item(item)) => item.span,
920 Some(Node::Variant(variant)) => variant.span,
923 Some(Node::Lifetime(lifetime)) => lifetime.span,
924 Some(Node::GenericParam(param)) => param.span,
925 Some(Node::Visibility(&Spanned {
926 node: VisibilityKind::Restricted { ref path, .. },
929 Some(Node::Visibility(v)) => bug!("unexpected Visibility {:?}", v),
930 Some(Node::Local(local)) => local.span,
931 Some(Node::MacroDef(macro_def)) => macro_def.span,
932 Some(Node::Crate(item)) => item.span,
933 None => bug!("hir::map::Map::span: id not in map: {:?}", hir_id),
937 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
938 self.as_local_hir_id(id).map(|id| self.span(id))
941 pub fn res_span(&self, res: Res) -> Option<Span> {
944 Res::Local(id) => Some(self.span(id)),
945 res => self.span_if_local(res.opt_def_id()?),
949 pub fn node_to_string(&self, id: HirId) -> String {
950 hir_id_to_string(self, id, true)
953 pub fn hir_to_user_string(&self, id: HirId) -> String {
954 hir_id_to_string(self, id, false)
957 pub fn hir_to_pretty_string(&self, id: HirId) -> String {
958 print::to_string(self, |s| s.print_node(self.get(id)))
962 impl<'hir> intravisit::Map<'hir> for Map<'hir> {
963 fn body(&self, id: BodyId) -> &'hir Body<'hir> {
967 fn item(&self, id: HirId) -> &'hir Item<'hir> {
971 fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
975 fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
981 fn name(&self) -> Name;
984 impl<T: Named> Named for Spanned<T> {
985 fn name(&self) -> Name {
990 impl Named for Item<'_> {
991 fn name(&self) -> Name {
995 impl Named for ForeignItem<'_> {
996 fn name(&self) -> Name {
1000 impl Named for Variant<'_> {
1001 fn name(&self) -> Name {
1005 impl Named for StructField<'_> {
1006 fn name(&self) -> Name {
1010 impl Named for TraitItem<'_> {
1011 fn name(&self) -> Name {
1015 impl Named for ImplItem<'_> {
1016 fn name(&self) -> Name {
1021 pub(super) fn index_hir<'tcx>(tcx: TyCtxt<'tcx>, cnum: CrateNum) -> &'tcx IndexedHir<'tcx> {
1022 assert_eq!(cnum, LOCAL_CRATE);
1024 let _prof_timer = tcx.sess.prof.generic_activity("build_hir_map");
1026 let (map, crate_hash) = {
1027 let hcx = tcx.create_stable_hashing_context();
1030 NodeCollector::root(tcx.sess, &**tcx.arena, tcx.untracked_crate, &tcx.definitions, hcx);
1031 intravisit::walk_crate(&mut collector, tcx.untracked_crate);
1033 let crate_disambiguator = tcx.sess.local_crate_disambiguator();
1034 let cmdline_args = tcx.sess.opts.dep_tracking_hash();
1035 collector.finalize_and_compute_crate_hash(crate_disambiguator, &*tcx.cstore, cmdline_args)
1038 let map = tcx.arena.alloc(IndexedHir { crate_hash, map });
1043 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1044 /// except it avoids creating a dependency on the whole crate.
1045 impl<'hir> print::PpAnn for Map<'hir> {
1046 fn nested(&self, state: &mut print::State<'_>, nested: print::Nested) {
1048 Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1049 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1050 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1051 Nested::Body(id) => state.print_expr(&self.body(id).value),
1052 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
1057 fn hir_id_to_string(map: &Map<'_>, id: HirId, include_id: bool) -> String {
1058 let id_str = format!(" (hir_id={})", id);
1059 let id_str = if include_id { &id_str[..] } else { "" };
1062 // This functionality is used for debugging, try to use `TyCtxt` to get
1063 // the user-friendly path, otherwise fall back to stringifying `DefPath`.
1064 crate::ty::tls::with_opt(|tcx| {
1065 if let Some(tcx) = tcx {
1066 let def_id = map.local_def_id(id);
1067 tcx.def_path_str(def_id)
1068 } else if let Some(path) = map.def_path_from_hir_id(id) {
1071 .map(|elem| elem.data.to_string())
1072 .collect::<Vec<_>>()
1075 String::from("<missing path>")
1080 match map.find(id) {
1081 Some(Node::Item(item)) => {
1082 let item_str = match item.kind {
1083 ItemKind::ExternCrate(..) => "extern crate",
1084 ItemKind::Use(..) => "use",
1085 ItemKind::Static(..) => "static",
1086 ItemKind::Const(..) => "const",
1087 ItemKind::Fn(..) => "fn",
1088 ItemKind::Mod(..) => "mod",
1089 ItemKind::ForeignMod(..) => "foreign mod",
1090 ItemKind::GlobalAsm(..) => "global asm",
1091 ItemKind::TyAlias(..) => "ty",
1092 ItemKind::OpaqueTy(..) => "opaque type",
1093 ItemKind::Enum(..) => "enum",
1094 ItemKind::Struct(..) => "struct",
1095 ItemKind::Union(..) => "union",
1096 ItemKind::Trait(..) => "trait",
1097 ItemKind::TraitAlias(..) => "trait alias",
1098 ItemKind::Impl { .. } => "impl",
1100 format!("{} {}{}", item_str, path_str(), id_str)
1102 Some(Node::ForeignItem(_)) => format!("foreign item {}{}", path_str(), id_str),
1103 Some(Node::ImplItem(ii)) => match ii.kind {
1104 ImplItemKind::Const(..) => {
1105 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1107 ImplItemKind::Fn(..) => format!("method {} in {}{}", ii.ident, path_str(), id_str),
1108 ImplItemKind::TyAlias(_) => {
1109 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1111 ImplItemKind::OpaqueTy(_) => {
1112 format!("assoc opaque type {} in {}{}", ii.ident, path_str(), id_str)
1115 Some(Node::TraitItem(ti)) => {
1116 let kind = match ti.kind {
1117 TraitItemKind::Const(..) => "assoc constant",
1118 TraitItemKind::Fn(..) => "trait method",
1119 TraitItemKind::Type(..) => "assoc type",
1122 format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1124 Some(Node::Variant(ref variant)) => {
1125 format!("variant {} in {}{}", variant.ident, path_str(), id_str)
1127 Some(Node::Field(ref field)) => {
1128 format!("field {} in {}{}", field.ident, path_str(), id_str)
1130 Some(Node::AnonConst(_)) => format!("const {}{}", map.hir_to_pretty_string(id), id_str),
1131 Some(Node::Expr(_)) => format!("expr {}{}", map.hir_to_pretty_string(id), id_str),
1132 Some(Node::Stmt(_)) => format!("stmt {}{}", map.hir_to_pretty_string(id), id_str),
1133 Some(Node::PathSegment(_)) => {
1134 format!("path segment {}{}", map.hir_to_pretty_string(id), id_str)
1136 Some(Node::Ty(_)) => format!("type {}{}", map.hir_to_pretty_string(id), id_str),
1137 Some(Node::TraitRef(_)) => format!("trait_ref {}{}", map.hir_to_pretty_string(id), id_str),
1138 Some(Node::Binding(_)) => format!("local {}{}", map.hir_to_pretty_string(id), id_str),
1139 Some(Node::Pat(_)) => format!("pat {}{}", map.hir_to_pretty_string(id), id_str),
1140 Some(Node::Param(_)) => format!("param {}{}", map.hir_to_pretty_string(id), id_str),
1141 Some(Node::Arm(_)) => format!("arm {}{}", map.hir_to_pretty_string(id), id_str),
1142 Some(Node::Block(_)) => format!("block {}{}", map.hir_to_pretty_string(id), id_str),
1143 Some(Node::Local(_)) => format!("local {}{}", map.hir_to_pretty_string(id), id_str),
1144 Some(Node::Ctor(..)) => format!("ctor {}{}", path_str(), id_str),
1145 Some(Node::Lifetime(_)) => format!("lifetime {}{}", map.hir_to_pretty_string(id), id_str),
1146 Some(Node::GenericParam(ref param)) => format!("generic_param {:?}{}", param, id_str),
1147 Some(Node::Visibility(ref vis)) => format!("visibility {:?}{}", vis, id_str),
1148 Some(Node::MacroDef(_)) => format!("macro {}{}", path_str(), id_str),
1149 Some(Node::Crate(..)) => String::from("root_crate"),
1150 None => format!("unknown node{}", id_str),
1154 pub fn provide(providers: &mut Providers<'_>) {
1155 providers.def_kind = |tcx, def_id| {
1156 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
1157 tcx.hir().def_kind(hir_id)
1159 bug!("calling local def_kind query provider for upstream DefId: {:?}", def_id);