1 use self::collector::NodeCollector;
2 pub use self::definitions::{
3 DefKey, DefPath, DefPathData, DefPathHash, Definitions, DisambiguatedDefPathData,
6 use crate::dep_graph::{DepGraph, DepKind, DepNode, DepNodeIndex};
7 use crate::middle::cstore::CrateStoreDyn;
8 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::{DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX};
14 use rustc_hir::intravisit;
15 use rustc_hir::itemlikevisit::ItemLikeVisitor;
16 use rustc_hir::print::Nested;
18 use rustc_index::vec::IndexVec;
19 use rustc_span::hygiene::MacroKind;
20 use rustc_span::source_map::Spanned;
21 use rustc_span::symbol::kw;
23 use rustc_target::spec::abi::Abi;
30 /// Represents an entry and its parent `HirId`.
31 #[derive(Copy, Clone, Debug)]
32 pub struct Entry<'hir> {
34 dep_node: DepNodeIndex,
38 impl<'hir> Entry<'hir> {
39 fn parent_node(self) -> Option<HirId> {
41 Node::Crate | Node::MacroDef(_) => None,
42 _ => Some(self.parent),
46 fn fn_decl(&self) -> 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::Method(ref sig, _) => Some(&sig.decl),
58 Node::ImplItem(ref item) => match item.kind {
59 ImplItemKind::Method(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(&self) -> 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::Method(sig, _) => Some(sig),
84 Node::ImplItem(item) => match &item.kind {
85 ImplItemKind::Method(sig, _) => Some(sig),
93 fn associated_body(self) -> 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))
104 | TraitItemKind::Method(_, TraitMethod::Provided(body)) => Some(body),
108 Node::ImplItem(item) => match item.kind {
109 ImplItemKind::Const(_, body) | ImplItemKind::Method(_, body) => Some(body),
113 Node::AnonConst(constant) => Some(constant.body),
115 Node::Expr(expr) => match expr.kind {
116 ExprKind::Closure(.., body, _, _) => Some(body),
124 fn is_body_owner(self, hir_id: HirId) -> bool {
125 match self.associated_body() {
126 Some(b) => b.hir_id == hir_id,
132 /// This type is effectively a `HashMap<HirId, Entry<'hir>>`,
133 /// but it is implemented as 2 layers of arrays.
134 /// - first we have `A = IndexVec<DefIndex, B>` mapping `DefIndex`s to an inner value
135 /// - which is `B = IndexVec<ItemLocalId, Option<Entry<'hir>>` which gives you the `Entry`.
136 pub(super) type HirEntryMap<'hir> = IndexVec<DefIndex, IndexVec<ItemLocalId, Option<Entry<'hir>>>>;
138 /// Represents a mapping from `NodeId`s to AST elements and their parent `NodeId`s.
140 pub struct Map<'hir> {
141 krate: &'hir Crate<'hir>,
143 pub dep_graph: DepGraph,
145 /// The SVH of the local crate.
148 map: HirEntryMap<'hir>,
150 definitions: Definitions,
152 /// The reverse mapping of `node_to_hir_id`.
153 hir_to_node_id: FxHashMap<HirId, NodeId>,
156 /// An iterator that walks up the ancestor tree of a given `HirId`.
157 /// Constructed using `tcx.hir().parent_iter(hir_id)`.
158 pub struct ParentHirIterator<'map, 'hir> {
160 map: &'map Map<'hir>,
163 impl<'hir> Iterator for ParentHirIterator<'_, 'hir> {
164 type Item = (HirId, Node<'hir>);
166 fn next(&mut self) -> Option<Self::Item> {
167 if self.current_id == CRATE_HIR_ID {
171 // There are nodes that do not have entries, so we need to skip them.
172 let parent_id = self.map.get_parent_node(self.current_id);
174 if parent_id == self.current_id {
175 self.current_id = CRATE_HIR_ID;
179 self.current_id = parent_id;
180 if let Some(entry) = self.map.find_entry(parent_id) {
181 return Some((parent_id, entry.node));
183 // If this `HirId` doesn't have an `Entry`, skip it and look for its `parent_id`.
188 impl<'hir> Map<'hir> {
189 /// This is used internally in the dependency tracking system.
190 /// Use the `krate` method to ensure your dependency on the
191 /// crate is tracked.
192 pub fn untracked_krate(&self) -> &Crate<'hir> {
197 fn lookup(&self, id: HirId) -> Option<&Entry<'hir>> {
198 let local_map = self.map.get(id.owner)?;
199 local_map.get(id.local_id)?.as_ref()
202 /// Registers a read in the dependency graph of the AST node with
203 /// the given `id`. This needs to be called each time a public
204 /// function returns the HIR for a node -- in other words, when it
205 /// "reveals" the content of a node to the caller (who might not
206 /// otherwise have had access to those contents, and hence needs a
207 /// read recorded). If the function just returns a DefId or
208 /// HirId, no actual content was returned, so no read is needed.
209 pub fn read(&self, hir_id: HirId) {
210 if let Some(entry) = self.lookup(hir_id) {
211 self.dep_graph.read_index(entry.dep_node);
213 bug!("called `HirMap::read()` with invalid `HirId`: {:?}", hir_id)
218 pub fn definitions(&self) -> &Definitions {
222 pub fn def_key(&self, def_id: DefId) -> DefKey {
223 assert!(def_id.is_local());
224 self.definitions.def_key(def_id.index)
227 pub fn def_path_from_hir_id(&self, id: HirId) -> Option<DefPath> {
228 self.opt_local_def_id(id).map(|def_id| self.def_path(def_id))
231 pub fn def_path(&self, def_id: DefId) -> DefPath {
232 assert!(def_id.is_local());
233 self.definitions.def_path(def_id.index)
237 pub fn local_def_id_from_node_id(&self, node: NodeId) -> DefId {
238 self.opt_local_def_id_from_node_id(node).unwrap_or_else(|| {
239 let hir_id = self.node_to_hir_id(node);
241 "local_def_id_from_node_id: no entry for `{}`, which has a map of `{:?}`",
243 self.find_entry(hir_id)
249 pub fn local_def_id(&self, hir_id: HirId) -> DefId {
250 self.opt_local_def_id(hir_id).unwrap_or_else(|| {
252 "local_def_id: no entry for `{:?}`, which has a map of `{:?}`",
254 self.find_entry(hir_id)
260 pub fn opt_local_def_id(&self, hir_id: HirId) -> Option<DefId> {
261 let node_id = self.hir_to_node_id(hir_id);
262 self.definitions.opt_local_def_id(node_id)
266 pub fn opt_local_def_id_from_node_id(&self, node: NodeId) -> Option<DefId> {
267 self.definitions.opt_local_def_id(node)
271 pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
272 self.definitions.as_local_node_id(def_id)
276 pub fn as_local_hir_id(&self, def_id: DefId) -> Option<HirId> {
277 self.definitions.as_local_hir_id(def_id)
281 pub fn hir_to_node_id(&self, hir_id: HirId) -> NodeId {
282 self.hir_to_node_id[&hir_id]
286 pub fn node_to_hir_id(&self, node_id: NodeId) -> HirId {
287 self.definitions.node_to_hir_id(node_id)
291 pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> HirId {
292 self.definitions.def_index_to_hir_id(def_index)
296 pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
297 self.definitions.def_index_to_hir_id(def_id.to_def_id().index)
300 pub fn def_kind(&self, hir_id: HirId) -> Option<DefKind> {
301 let node = if let Some(node) = self.find(hir_id) { node } else { return None };
304 Node::Item(item) => match item.kind {
305 ItemKind::Static(..) => DefKind::Static,
306 ItemKind::Const(..) => DefKind::Const,
307 ItemKind::Fn(..) => DefKind::Fn,
308 ItemKind::Mod(..) => DefKind::Mod,
309 ItemKind::OpaqueTy(..) => DefKind::OpaqueTy,
310 ItemKind::TyAlias(..) => DefKind::TyAlias,
311 ItemKind::Enum(..) => DefKind::Enum,
312 ItemKind::Struct(..) => DefKind::Struct,
313 ItemKind::Union(..) => DefKind::Union,
314 ItemKind::Trait(..) => DefKind::Trait,
315 ItemKind::TraitAlias(..) => DefKind::TraitAlias,
316 ItemKind::ExternCrate(_)
318 | ItemKind::ForeignMod(..)
319 | ItemKind::GlobalAsm(..)
320 | ItemKind::Impl { .. } => return None,
322 Node::ForeignItem(item) => match item.kind {
323 ForeignItemKind::Fn(..) => DefKind::Fn,
324 ForeignItemKind::Static(..) => DefKind::Static,
325 ForeignItemKind::Type => DefKind::ForeignTy,
327 Node::TraitItem(item) => match item.kind {
328 TraitItemKind::Const(..) => DefKind::AssocConst,
329 TraitItemKind::Method(..) => DefKind::Method,
330 TraitItemKind::Type(..) => DefKind::AssocTy,
332 Node::ImplItem(item) => match item.kind {
333 ImplItemKind::Const(..) => DefKind::AssocConst,
334 ImplItemKind::Method(..) => DefKind::Method,
335 ImplItemKind::TyAlias(..) => DefKind::AssocTy,
336 ImplItemKind::OpaqueTy(..) => DefKind::AssocOpaqueTy,
338 Node::Variant(_) => DefKind::Variant,
339 Node::Ctor(variant_data) => {
340 // FIXME(eddyb) is this even possible, if we have a `Node::Ctor`?
341 if variant_data.ctor_hir_id().is_none() {
344 let ctor_of = match self.find(self.get_parent_node(hir_id)) {
345 Some(Node::Item(..)) => def::CtorOf::Struct,
346 Some(Node::Variant(..)) => def::CtorOf::Variant,
349 DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data))
355 | Node::PathSegment(_)
364 | Node::Visibility(_)
366 | Node::Crate => return None,
367 Node::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
368 Node::GenericParam(param) => match param.kind {
369 GenericParamKind::Lifetime { .. } => return None,
370 GenericParamKind::Type { .. } => DefKind::TyParam,
371 GenericParamKind::Const { .. } => DefKind::ConstParam,
376 fn find_entry(&self, id: HirId) -> Option<Entry<'hir>> {
377 self.lookup(id).cloned()
380 pub fn item(&self, id: HirId) -> &'hir Item<'hir> {
383 // N.B., intentionally bypass `self.krate()` so that we
384 // do not trigger a read of the whole krate here
388 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
389 self.read(id.hir_id);
391 // N.B., intentionally bypass `self.krate()` so that we
392 // do not trigger a read of the whole krate here
393 self.krate.trait_item(id)
396 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
397 self.read(id.hir_id);
399 // N.B., intentionally bypass `self.krate()` so that we
400 // do not trigger a read of the whole krate here
401 self.krate.impl_item(id)
404 pub fn body(&self, id: BodyId) -> &'hir Body<'hir> {
405 self.read(id.hir_id);
407 // N.B., intentionally bypass `self.krate()` so that we
408 // do not trigger a read of the whole krate here
412 pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnDecl<'hir>> {
413 if let Some(entry) = self.find_entry(hir_id) {
416 bug!("no entry for hir_id `{}`", hir_id)
420 pub fn fn_sig_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnSig<'hir>> {
421 if let Some(entry) = self.find_entry(hir_id) {
424 bug!("no entry for hir_id `{}`", hir_id)
428 /// Returns the `HirId` that corresponds to the definition of
429 /// which this is the body of, i.e., a `fn`, `const` or `static`
430 /// item (possibly associated), a closure, or a `hir::AnonConst`.
431 pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> HirId {
432 let parent = self.get_parent_node(hir_id);
433 assert!(self.lookup(parent).map_or(false, |e| e.is_body_owner(hir_id)));
437 pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
438 self.local_def_id(self.body_owner(id))
441 /// Given a `HirId`, returns the `BodyId` associated with it,
442 /// if the node is a body owner, otherwise returns `None`.
443 pub fn maybe_body_owned_by(&self, hir_id: HirId) -> Option<BodyId> {
444 if let Some(entry) = self.find_entry(hir_id) {
445 if self.dep_graph.is_fully_enabled() {
446 let hir_id_owner = hir_id.owner;
447 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
448 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
451 entry.associated_body()
453 bug!("no entry for id `{}`", hir_id)
457 /// Given a body owner's id, returns the `BodyId` associated with it.
458 pub fn body_owned_by(&self, id: HirId) -> BodyId {
459 self.maybe_body_owned_by(id).unwrap_or_else(|| {
462 "body_owned_by: {} has no associated body",
463 self.node_to_string(id)
468 pub fn body_owner_kind(&self, id: HirId) -> BodyOwnerKind {
470 Node::Item(&Item { kind: ItemKind::Const(..), .. })
471 | Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. })
472 | Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. })
473 | Node::AnonConst(_) => BodyOwnerKind::Const,
475 | Node::Item(&Item { kind: ItemKind::Fn(..), .. })
476 | Node::TraitItem(&TraitItem { kind: TraitItemKind::Method(..), .. })
477 | Node::ImplItem(&ImplItem { kind: ImplItemKind::Method(..), .. }) => BodyOwnerKind::Fn,
478 Node::Item(&Item { kind: ItemKind::Static(_, m, _), .. }) => BodyOwnerKind::Static(m),
479 Node::Expr(&Expr { kind: ExprKind::Closure(..), .. }) => BodyOwnerKind::Closure,
480 node => bug!("{:#?} is not a body node", node),
484 pub fn ty_param_owner(&self, id: HirId) -> HirId {
486 Node::Item(&Item { kind: ItemKind::Trait(..), .. })
487 | Node::Item(&Item { kind: ItemKind::TraitAlias(..), .. }) => id,
488 Node::GenericParam(_) => self.get_parent_node(id),
489 _ => bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id)),
493 pub fn ty_param_name(&self, id: HirId) -> Name {
495 Node::Item(&Item { kind: ItemKind::Trait(..), .. })
496 | Node::Item(&Item { kind: ItemKind::TraitAlias(..), .. }) => kw::SelfUpper,
497 Node::GenericParam(param) => param.name.ident().name,
498 _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
502 pub fn trait_impls(&self, trait_did: DefId) -> &'hir [HirId] {
503 self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
505 // N.B., intentionally bypass `self.krate()` so that we
506 // do not trigger a read of the whole krate here
507 self.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
510 /// Gets the attributes on the crate. This is preferable to
511 /// invoking `krate.attrs` because it registers a tighter
512 /// dep-graph access.
513 pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
514 let def_path_hash = self.definitions.def_path_hash(CRATE_DEF_INDEX);
516 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::Hir));
520 pub fn get_module(&self, module: DefId) -> (&'hir Mod<'hir>, Span, HirId) {
521 let hir_id = self.as_local_hir_id(module).unwrap();
523 match self.find_entry(hir_id).unwrap().node {
524 Node::Item(&Item { span, kind: ItemKind::Mod(ref m), .. }) => (m, span, hir_id),
525 Node::Crate => (&self.krate.module, self.krate.span, hir_id),
526 node => panic!("not a module: {:?}", node),
530 pub fn visit_item_likes_in_module<V>(&self, module: DefId, visitor: &mut V)
532 V: ItemLikeVisitor<'hir>,
534 let hir_id = self.as_local_hir_id(module).unwrap();
536 // Read the module so we'll be re-executed if new items
537 // appear immediately under in the module. If some new item appears
538 // in some nested item in the module, we'll be re-executed due to reads
539 // in the expect_* calls the loops below
542 let module = &self.krate.modules[&hir_id];
544 for id in &module.items {
545 visitor.visit_item(self.expect_item(*id));
548 for id in &module.trait_items {
549 visitor.visit_trait_item(self.expect_trait_item(id.hir_id));
552 for id in &module.impl_items {
553 visitor.visit_impl_item(self.expect_impl_item(id.hir_id));
557 /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found.
558 pub fn get(&self, id: HirId) -> Node<'hir> {
559 // read recorded by `find`
560 self.find(id).unwrap_or_else(|| bug!("couldn't find hir id {} in the HIR map", id))
563 pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
564 self.as_local_hir_id(id).map(|id| self.get(id)) // read recorded by `get`
567 pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics<'hir>> {
568 self.get_if_local(id).and_then(|node| match node {
569 Node::ImplItem(ref impl_item) => Some(&impl_item.generics),
570 Node::TraitItem(ref trait_item) => Some(&trait_item.generics),
571 Node::Item(ref item) => match item.kind {
572 ItemKind::Fn(_, ref generics, _)
573 | ItemKind::TyAlias(_, ref generics)
574 | ItemKind::Enum(_, ref generics)
575 | ItemKind::Struct(_, ref generics)
576 | ItemKind::Union(_, ref generics)
577 | ItemKind::Trait(_, _, ref generics, ..)
578 | ItemKind::TraitAlias(ref generics, _)
579 | ItemKind::Impl { ref generics, .. } => Some(generics),
586 /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
587 pub fn find(&self, hir_id: HirId) -> Option<Node<'hir>> {
590 .and_then(|entry| if let Node::Crate = entry.node { None } else { Some(entry.node) });
591 if result.is_some() {
597 /// Similar to `get_parent`; returns the parent HIR Id, or just `hir_id` if there
598 /// is no parent. Note that the parent may be `CRATE_HIR_ID`, which is not itself
599 /// present in the map, so passing the return value of `get_parent_node` to
600 /// `get` may in fact panic.
601 /// This function returns the immediate parent in the HIR, whereas `get_parent`
602 /// returns the enclosing item. Note that this might not be the actual parent
603 /// node in the HIR -- some kinds of nodes are not in the map and these will
604 /// never appear as the parent node. Thus, you can always walk the parent nodes
605 /// from a node to the root of the HIR (unless you get back the same ID here,
606 /// which can happen if the ID is not in the map itself or is just weird).
607 pub fn get_parent_node(&self, hir_id: HirId) -> HirId {
608 if self.dep_graph.is_fully_enabled() {
609 let hir_id_owner = hir_id.owner;
610 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
611 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
614 self.find_entry(hir_id).and_then(|x| x.parent_node()).unwrap_or(hir_id)
617 /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
618 /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`.
619 pub fn parent_iter(&self, current_id: HirId) -> ParentHirIterator<'_, 'hir> {
620 ParentHirIterator { current_id, map: self }
623 /// Checks if the node is an argument. An argument is a local variable whose
624 /// immediate parent is an item or a closure.
625 pub fn is_argument(&self, id: HirId) -> bool {
626 match self.find(id) {
627 Some(Node::Binding(_)) => (),
630 match self.find(self.get_parent_node(id)) {
631 Some(Node::Item(_)) | Some(Node::TraitItem(_)) | Some(Node::ImplItem(_)) => true,
632 Some(Node::Expr(e)) => match e.kind {
633 ExprKind::Closure(..) => true,
640 /// Whether the expression pointed at by `hir_id` belongs to a `const` evaluation context.
641 /// Used exclusively for diagnostics, to avoid suggestion function calls.
642 pub fn is_const_context(&self, hir_id: HirId) -> bool {
643 let parent_id = self.get_parent_item(hir_id);
644 match self.get(parent_id) {
645 Node::Item(&Item { kind: ItemKind::Const(..), .. })
646 | Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. })
647 | Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. })
649 | Node::Item(&Item { kind: ItemKind::Static(..), .. }) => true,
650 Node::Item(&Item { kind: ItemKind::Fn(ref sig, ..), .. }) => {
651 sig.header.constness == Constness::Const
657 /// Wether `hir_id` corresponds to a `mod` or a crate.
658 pub fn is_hir_id_module(&self, hir_id: HirId) -> bool {
659 match self.lookup(hir_id) {
660 Some(Entry { node: Node::Item(Item { kind: ItemKind::Mod(_), .. }), .. })
661 | Some(Entry { node: Node::Crate, .. }) => true,
666 /// Retrieves the `HirId` for `id`'s enclosing method, unless there's a
667 /// `while` or `loop` before reaching it, as block tail returns are not
668 /// available in them.
671 /// fn foo(x: usize) -> bool {
673 /// true // If `get_return_block` gets passed the `id` corresponding
674 /// } else { // to this, it will return `foo`'s `HirId`.
681 /// fn foo(x: usize) -> bool {
683 /// true // If `get_return_block` gets passed the `id` corresponding
684 /// } // to this, it will return `None`.
688 pub fn get_return_block(&self, id: HirId) -> Option<HirId> {
689 let mut iter = self.parent_iter(id).peekable();
690 let mut ignore_tail = false;
691 if let Some(entry) = self.find_entry(id) {
692 if let Node::Expr(Expr { kind: ExprKind::Ret(_), .. }) = entry.node {
693 // When dealing with `return` statements, we don't care about climbing only tail
698 while let Some((hir_id, node)) = iter.next() {
699 if let (Some((_, next_node)), false) = (iter.peek(), ignore_tail) {
701 Node::Block(Block { expr: None, .. }) => return None,
702 Node::Block(Block { expr: Some(expr), .. }) => {
703 if hir_id != expr.hir_id {
704 // The current node is not the tail expression of its parent.
713 | Node::ForeignItem(_)
715 | Node::Expr(Expr { kind: ExprKind::Closure(..), .. })
716 | Node::ImplItem(_) => return Some(hir_id),
717 Node::Expr(ref expr) => {
719 // Ignore `return`s on the first iteration
720 ExprKind::Loop(..) | ExprKind::Ret(..) => return None,
724 Node::Local(_) => return None,
731 /// Retrieves the `HirId` for `id`'s parent item, or `id` itself if no
732 /// parent item is in this map. The "parent item" is the closest parent node
733 /// in the HIR which is recorded by the map and is an item, either an item
734 /// in a module, trait, or impl.
735 pub fn get_parent_item(&self, hir_id: HirId) -> HirId {
736 for (hir_id, node) in self.parent_iter(hir_id) {
740 | Node::ForeignItem(_)
742 | Node::ImplItem(_) => return hir_id,
749 /// Returns the `DefId` of `id`'s nearest module parent, or `id` itself if no
750 /// module parent is in this map.
751 pub fn get_module_parent(&self, id: HirId) -> DefId {
752 self.local_def_id(self.get_module_parent_node(id))
755 /// Returns the `HirId` of `id`'s nearest module parent, or `id` itself if no
756 /// module parent is in this map.
757 pub fn get_module_parent_node(&self, hir_id: HirId) -> HirId {
758 for (hir_id, node) in self.parent_iter(hir_id) {
759 if let Node::Item(&Item { kind: ItemKind::Mod(_), .. }) = node {
766 /// When on a match arm tail expression or on a match arm, give back the enclosing `match`
769 /// Used by error reporting when there's a type error in a match arm caused by the `match`
770 /// expression needing to be unit.
771 pub fn get_match_if_cause(&self, hir_id: HirId) -> Option<&'hir Expr<'hir>> {
772 for (_, node) in self.parent_iter(hir_id) {
774 Node::Item(_) | Node::ForeignItem(_) | Node::TraitItem(_) | Node::ImplItem(_) => {
777 Node::Expr(expr) => match expr.kind {
778 ExprKind::Match(_, _, _) => return Some(expr),
781 Node::Stmt(stmt) => match stmt.kind {
782 StmtKind::Local(_) => break,
791 /// Returns the nearest enclosing scope. A scope is roughly an item or block.
792 pub fn get_enclosing_scope(&self, hir_id: HirId) -> Option<HirId> {
793 for (hir_id, node) in self.parent_iter(hir_id) {
795 Node::Item(i) => match i.kind {
799 | ItemKind::Struct(..)
800 | ItemKind::Union(..)
801 | ItemKind::Trait(..)
802 | ItemKind::Impl { .. } => true,
805 Node::ForeignItem(fi) => match fi.kind {
806 ForeignItemKind::Fn(..) => true,
809 Node::TraitItem(ti) => match ti.kind {
810 TraitItemKind::Method(..) => true,
813 Node::ImplItem(ii) => match ii.kind {
814 ImplItemKind::Method(..) => true,
817 Node::Block(_) => true,
826 /// Returns the defining scope for an opaque type definition.
827 pub fn get_defining_scope(&self, id: HirId) -> HirId {
830 scope = self.get_enclosing_scope(scope).unwrap_or(CRATE_HIR_ID);
831 if scope == CRATE_HIR_ID {
834 match self.get(scope) {
835 Node::Item(i) => match i.kind {
836 ItemKind::OpaqueTy(OpaqueTy { impl_trait_fn: None, .. }) => {}
846 pub fn get_parent_did(&self, id: HirId) -> DefId {
847 self.local_def_id(self.get_parent_item(id))
850 pub fn get_foreign_abi(&self, hir_id: HirId) -> Abi {
851 let parent = self.get_parent_item(hir_id);
852 if let Some(entry) = self.find_entry(parent) {
854 node: Node::Item(Item { kind: ItemKind::ForeignMod(ref nm), .. }), ..
857 self.read(hir_id); // reveals some of the content of a node
861 bug!("expected foreign mod or inlined parent, found {}", self.node_to_string(parent))
864 pub fn expect_item(&self, id: HirId) -> &'hir Item<'hir> {
865 match self.find(id) {
866 // read recorded by `find`
867 Some(Node::Item(item)) => item,
868 _ => bug!("expected item, found {}", self.node_to_string(id)),
872 pub fn expect_impl_item(&self, id: HirId) -> &'hir ImplItem<'hir> {
873 match self.find(id) {
874 Some(Node::ImplItem(item)) => item,
875 _ => bug!("expected impl item, found {}", self.node_to_string(id)),
879 pub fn expect_trait_item(&self, id: HirId) -> &'hir TraitItem<'hir> {
880 match self.find(id) {
881 Some(Node::TraitItem(item)) => item,
882 _ => bug!("expected trait item, found {}", self.node_to_string(id)),
886 pub fn expect_variant_data(&self, id: HirId) -> &'hir VariantData<'hir> {
887 match self.find(id) {
888 Some(Node::Item(i)) => match i.kind {
889 ItemKind::Struct(ref struct_def, _) | ItemKind::Union(ref struct_def, _) => {
892 _ => bug!("struct ID bound to non-struct {}", self.node_to_string(id)),
894 Some(Node::Variant(variant)) => &variant.data,
895 Some(Node::Ctor(data)) => data,
896 _ => bug!("expected struct or variant, found {}", self.node_to_string(id)),
900 pub fn expect_variant(&self, id: HirId) -> &'hir Variant<'hir> {
901 match self.find(id) {
902 Some(Node::Variant(variant)) => variant,
903 _ => bug!("expected variant, found {}", self.node_to_string(id)),
907 pub fn expect_foreign_item(&self, id: HirId) -> &'hir ForeignItem<'hir> {
908 match self.find(id) {
909 Some(Node::ForeignItem(item)) => item,
910 _ => bug!("expected foreign item, found {}", self.node_to_string(id)),
914 pub fn expect_expr(&self, id: HirId) -> &'hir Expr<'hir> {
915 match self.find(id) {
916 // read recorded by find
917 Some(Node::Expr(expr)) => expr,
918 _ => bug!("expected expr, found {}", self.node_to_string(id)),
922 pub fn opt_name(&self, id: HirId) -> Option<Name> {
923 Some(match self.get(id) {
924 Node::Item(i) => i.ident.name,
925 Node::ForeignItem(fi) => fi.ident.name,
926 Node::ImplItem(ii) => ii.ident.name,
927 Node::TraitItem(ti) => ti.ident.name,
928 Node::Variant(v) => v.ident.name,
929 Node::Field(f) => f.ident.name,
930 Node::Lifetime(lt) => lt.name.ident().name,
931 Node::GenericParam(param) => param.name.ident().name,
932 Node::Binding(&Pat { kind: PatKind::Binding(_, _, l, _), .. }) => l.name,
933 Node::Ctor(..) => self.name(self.get_parent_item(id)),
938 pub fn name(&self, id: HirId) -> Name {
939 match self.opt_name(id) {
941 None => bug!("no name for {}", self.node_to_string(id)),
945 /// Given a node ID, gets a list of attributes associated with the AST
946 /// corresponding to the node-ID.
947 pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] {
948 self.read(id); // reveals attributes on the node
949 let attrs = match self.find_entry(id).map(|entry| entry.node) {
950 Some(Node::Param(a)) => Some(&a.attrs[..]),
951 Some(Node::Local(l)) => Some(&l.attrs[..]),
952 Some(Node::Item(i)) => Some(&i.attrs[..]),
953 Some(Node::ForeignItem(fi)) => Some(&fi.attrs[..]),
954 Some(Node::TraitItem(ref ti)) => Some(&ti.attrs[..]),
955 Some(Node::ImplItem(ref ii)) => Some(&ii.attrs[..]),
956 Some(Node::Variant(ref v)) => Some(&v.attrs[..]),
957 Some(Node::Field(ref f)) => Some(&f.attrs[..]),
958 Some(Node::Expr(ref e)) => Some(&*e.attrs),
959 Some(Node::Stmt(ref s)) => Some(s.kind.attrs()),
960 Some(Node::Arm(ref a)) => Some(&*a.attrs),
961 Some(Node::GenericParam(param)) => Some(¶m.attrs[..]),
962 // Unit/tuple structs/variants take the attributes straight from
963 // the struct/variant definition.
964 Some(Node::Ctor(..)) => return self.attrs(self.get_parent_item(id)),
965 Some(Node::Crate) => Some(&self.krate.attrs[..]),
971 /// Returns an iterator that yields all the hir ids in the map.
972 fn all_ids<'a>(&'a self) -> impl Iterator<Item = HirId> + 'a {
973 // This code is a bit awkward because the map is implemented as 2 levels of arrays,
974 // see the comment on `HirEntryMap`.
975 // Iterate over all the indices and return a reference to
976 // local maps and their index given that they exist.
977 self.map.iter_enumerated().flat_map(move |(owner, local_map)| {
978 // Iterate over each valid entry in the local map.
979 local_map.iter_enumerated().filter_map(move |(i, entry)| {
981 // Reconstruct the `HirId` based on the 3 indices we used to find it.
982 HirId { owner, local_id: i }
988 /// Returns an iterator that yields the node id's with paths that
989 /// match `parts`. (Requires `parts` is non-empty.)
991 /// For example, if given `parts` equal to `["bar", "quux"]`, then
992 /// the iterator will produce node id's for items with paths
993 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
994 /// any other such items it can find in the map.
995 pub fn nodes_matching_suffix<'a>(
998 ) -> impl Iterator<Item = NodeId> + 'a {
999 let nodes = NodesMatchingSuffix {
1001 item_name: parts.last().unwrap(),
1002 in_which: &parts[..parts.len() - 1],
1006 .filter(move |hir| nodes.matches_suffix(*hir))
1007 .map(move |hir| self.hir_to_node_id(hir))
1010 pub fn span(&self, hir_id: HirId) -> Span {
1011 self.read(hir_id); // reveals span from node
1012 match self.find_entry(hir_id).map(|entry| entry.node) {
1013 Some(Node::Param(param)) => param.span,
1014 Some(Node::Item(item)) => item.span,
1015 Some(Node::ForeignItem(foreign_item)) => foreign_item.span,
1016 Some(Node::TraitItem(trait_method)) => trait_method.span,
1017 Some(Node::ImplItem(impl_item)) => impl_item.span,
1018 Some(Node::Variant(variant)) => variant.span,
1019 Some(Node::Field(field)) => field.span,
1020 Some(Node::AnonConst(constant)) => self.body(constant.body).value.span,
1021 Some(Node::Expr(expr)) => expr.span,
1022 Some(Node::Stmt(stmt)) => stmt.span,
1023 Some(Node::PathSegment(seg)) => seg.ident.span,
1024 Some(Node::Ty(ty)) => ty.span,
1025 Some(Node::TraitRef(tr)) => tr.path.span,
1026 Some(Node::Binding(pat)) => pat.span,
1027 Some(Node::Pat(pat)) => pat.span,
1028 Some(Node::Arm(arm)) => arm.span,
1029 Some(Node::Block(block)) => block.span,
1030 Some(Node::Ctor(..)) => match self.find(self.get_parent_node(hir_id)) {
1031 Some(Node::Item(item)) => item.span,
1032 Some(Node::Variant(variant)) => variant.span,
1033 _ => unreachable!(),
1035 Some(Node::Lifetime(lifetime)) => lifetime.span,
1036 Some(Node::GenericParam(param)) => param.span,
1037 Some(Node::Visibility(&Spanned {
1038 node: VisibilityKind::Restricted { ref path, .. },
1041 Some(Node::Visibility(v)) => bug!("unexpected Visibility {:?}", v),
1042 Some(Node::Local(local)) => local.span,
1043 Some(Node::MacroDef(macro_def)) => macro_def.span,
1044 Some(Node::Crate) => self.krate.span,
1045 None => bug!("hir::map::Map::span: id not in map: {:?}", hir_id),
1049 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
1050 self.as_local_hir_id(id).map(|id| self.span(id))
1053 pub fn res_span(&self, res: Res) -> Option<Span> {
1056 Res::Local(id) => Some(self.span(id)),
1057 res => self.span_if_local(res.opt_def_id()?),
1061 pub fn node_to_string(&self, id: HirId) -> String {
1062 hir_id_to_string(self, id, true)
1065 pub fn hir_to_user_string(&self, id: HirId) -> String {
1066 hir_id_to_string(self, id, false)
1069 pub fn hir_to_pretty_string(&self, id: HirId) -> String {
1070 print::to_string(self, |s| s.print_node(self.get(id)))
1074 impl<'hir> intravisit::Map<'hir> for Map<'hir> {
1075 fn body(&self, id: BodyId) -> &'hir Body<'hir> {
1079 fn item(&self, id: HirId) -> &'hir Item<'hir> {
1083 fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
1087 fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
1092 pub struct NodesMatchingSuffix<'a> {
1094 item_name: &'a String,
1095 in_which: &'a [String],
1098 impl<'a> NodesMatchingSuffix<'a> {
1099 /// Returns `true` only if some suffix of the module path for parent
1100 /// matches `self.in_which`.
1102 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
1103 /// returns true if parent's path ends with the suffix
1104 /// `x_0::x_1::...::x_k`.
1105 fn suffix_matches(&self, parent: HirId) -> bool {
1106 let mut cursor = parent;
1107 for part in self.in_which.iter().rev() {
1108 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
1109 None => return false,
1110 Some((node_id, name)) => (node_id, name),
1112 if mod_name.as_str() != *part {
1115 cursor = self.map.get_parent_item(mod_id);
1119 // Finds the first mod in parent chain for `id`, along with
1122 // If `id` itself is a mod named `m` with parent `p`, then
1123 // returns `Some(id, m, p)`. If `id` has no mod in its parent
1124 // chain, then returns `None`.
1125 fn find_first_mod_parent(map: &Map<'_>, mut id: HirId) -> Option<(HirId, Name)> {
1127 if let Node::Item(item) = map.find(id)? {
1128 if item_is_mod(&item) {
1129 return Some((id, item.ident.name));
1132 let parent = map.get_parent_item(id);
1139 fn item_is_mod(item: &Item<'_>) -> bool {
1141 ItemKind::Mod(_) => true,
1148 // We are looking at some node `n` with a given name and parent
1149 // id; do their names match what I am seeking?
1150 fn matches_names(&self, parent_of_n: HirId, name: Name) -> bool {
1151 name.as_str() == *self.item_name && self.suffix_matches(parent_of_n)
1154 fn matches_suffix(&self, hir: HirId) -> bool {
1155 let name = match self.map.find_entry(hir).map(|entry| entry.node) {
1156 Some(Node::Item(n)) => n.name(),
1157 Some(Node::ForeignItem(n)) => n.name(),
1158 Some(Node::TraitItem(n)) => n.name(),
1159 Some(Node::ImplItem(n)) => n.name(),
1160 Some(Node::Variant(n)) => n.name(),
1161 Some(Node::Field(n)) => n.name(),
1164 self.matches_names(self.map.get_parent_item(hir), name)
1169 fn name(&self) -> Name;
1172 impl<T: Named> Named for Spanned<T> {
1173 fn name(&self) -> Name {
1178 impl Named for Item<'_> {
1179 fn name(&self) -> Name {
1183 impl Named for ForeignItem<'_> {
1184 fn name(&self) -> Name {
1188 impl Named for Variant<'_> {
1189 fn name(&self) -> Name {
1193 impl Named for StructField<'_> {
1194 fn name(&self) -> Name {
1198 impl Named for TraitItem<'_> {
1199 fn name(&self) -> Name {
1203 impl Named for ImplItem<'_> {
1204 fn name(&self) -> Name {
1209 pub fn map_crate<'hir>(
1210 sess: &rustc_session::Session,
1211 cstore: &CrateStoreDyn,
1212 krate: &'hir Crate<'hir>,
1213 dep_graph: DepGraph,
1214 definitions: Definitions,
1216 let _prof_timer = sess.prof.generic_activity("build_hir_map");
1218 // Build the reverse mapping of `node_to_hir_id`.
1219 let hir_to_node_id = definitions
1222 .map(|(node_id, &hir_id)| (hir_id, node_id))
1225 let (map, crate_hash) = {
1226 let hcx = crate::ich::StableHashingContext::new(sess, krate, &definitions, cstore);
1229 NodeCollector::root(sess, krate, &dep_graph, &definitions, &hir_to_node_id, hcx);
1230 intravisit::walk_crate(&mut collector, krate);
1232 let crate_disambiguator = sess.local_crate_disambiguator();
1233 let cmdline_args = sess.opts.dep_tracking_hash();
1234 collector.finalize_and_compute_crate_hash(crate_disambiguator, cstore, cmdline_args)
1237 let map = Map { krate, dep_graph, crate_hash, map, hir_to_node_id, definitions };
1239 sess.time("validate_HIR_map", || {
1240 hir_id_validator::check_crate(&map, sess);
1246 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1247 /// except it avoids creating a dependency on the whole crate.
1248 impl<'hir> print::PpAnn for Map<'hir> {
1249 fn nested(&self, state: &mut print::State<'_>, nested: print::Nested) {
1251 Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1252 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1253 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1254 Nested::Body(id) => state.print_expr(&self.body(id).value),
1255 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
1260 fn hir_id_to_string(map: &Map<'_>, id: HirId, include_id: bool) -> String {
1261 let id_str = format!(" (hir_id={})", id);
1262 let id_str = if include_id { &id_str[..] } else { "" };
1265 // This functionality is used for debugging, try to use `TyCtxt` to get
1266 // the user-friendly path, otherwise fall back to stringifying `DefPath`.
1267 crate::ty::tls::with_opt(|tcx| {
1268 if let Some(tcx) = tcx {
1269 let def_id = map.local_def_id(id);
1270 tcx.def_path_str(def_id)
1271 } else if let Some(path) = map.def_path_from_hir_id(id) {
1274 .map(|elem| elem.data.to_string())
1275 .collect::<Vec<_>>()
1278 String::from("<missing path>")
1283 match map.find(id) {
1284 Some(Node::Item(item)) => {
1285 let item_str = match item.kind {
1286 ItemKind::ExternCrate(..) => "extern crate",
1287 ItemKind::Use(..) => "use",
1288 ItemKind::Static(..) => "static",
1289 ItemKind::Const(..) => "const",
1290 ItemKind::Fn(..) => "fn",
1291 ItemKind::Mod(..) => "mod",
1292 ItemKind::ForeignMod(..) => "foreign mod",
1293 ItemKind::GlobalAsm(..) => "global asm",
1294 ItemKind::TyAlias(..) => "ty",
1295 ItemKind::OpaqueTy(..) => "opaque type",
1296 ItemKind::Enum(..) => "enum",
1297 ItemKind::Struct(..) => "struct",
1298 ItemKind::Union(..) => "union",
1299 ItemKind::Trait(..) => "trait",
1300 ItemKind::TraitAlias(..) => "trait alias",
1301 ItemKind::Impl { .. } => "impl",
1303 format!("{} {}{}", item_str, path_str(), id_str)
1305 Some(Node::ForeignItem(_)) => format!("foreign item {}{}", path_str(), id_str),
1306 Some(Node::ImplItem(ii)) => match ii.kind {
1307 ImplItemKind::Const(..) => {
1308 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1310 ImplItemKind::Method(..) => format!("method {} in {}{}", ii.ident, path_str(), id_str),
1311 ImplItemKind::TyAlias(_) => {
1312 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1314 ImplItemKind::OpaqueTy(_) => {
1315 format!("assoc opaque type {} in {}{}", ii.ident, path_str(), id_str)
1318 Some(Node::TraitItem(ti)) => {
1319 let kind = match ti.kind {
1320 TraitItemKind::Const(..) => "assoc constant",
1321 TraitItemKind::Method(..) => "trait method",
1322 TraitItemKind::Type(..) => "assoc type",
1325 format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1327 Some(Node::Variant(ref variant)) => {
1328 format!("variant {} in {}{}", variant.ident, path_str(), id_str)
1330 Some(Node::Field(ref field)) => {
1331 format!("field {} in {}{}", field.ident, path_str(), id_str)
1333 Some(Node::AnonConst(_)) => format!("const {}{}", map.hir_to_pretty_string(id), id_str),
1334 Some(Node::Expr(_)) => format!("expr {}{}", map.hir_to_pretty_string(id), id_str),
1335 Some(Node::Stmt(_)) => format!("stmt {}{}", map.hir_to_pretty_string(id), id_str),
1336 Some(Node::PathSegment(_)) => {
1337 format!("path segment {}{}", map.hir_to_pretty_string(id), id_str)
1339 Some(Node::Ty(_)) => format!("type {}{}", map.hir_to_pretty_string(id), id_str),
1340 Some(Node::TraitRef(_)) => format!("trait_ref {}{}", map.hir_to_pretty_string(id), id_str),
1341 Some(Node::Binding(_)) => format!("local {}{}", map.hir_to_pretty_string(id), id_str),
1342 Some(Node::Pat(_)) => format!("pat {}{}", map.hir_to_pretty_string(id), id_str),
1343 Some(Node::Param(_)) => format!("param {}{}", map.hir_to_pretty_string(id), id_str),
1344 Some(Node::Arm(_)) => format!("arm {}{}", map.hir_to_pretty_string(id), id_str),
1345 Some(Node::Block(_)) => format!("block {}{}", map.hir_to_pretty_string(id), id_str),
1346 Some(Node::Local(_)) => format!("local {}{}", map.hir_to_pretty_string(id), id_str),
1347 Some(Node::Ctor(..)) => format!("ctor {}{}", path_str(), id_str),
1348 Some(Node::Lifetime(_)) => format!("lifetime {}{}", map.hir_to_pretty_string(id), id_str),
1349 Some(Node::GenericParam(ref param)) => format!("generic_param {:?}{}", param, id_str),
1350 Some(Node::Visibility(ref vis)) => format!("visibility {:?}{}", vis, id_str),
1351 Some(Node::MacroDef(_)) => format!("macro {}{}", path_str(), id_str),
1352 Some(Node::Crate) => String::from("root_crate"),
1353 None => format!("unknown node{}", id_str),
1357 pub fn provide(providers: &mut Providers<'_>) {
1358 providers.def_kind = |tcx, def_id| {
1359 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
1360 tcx.hir().def_kind(hir_id)
1362 bug!("calling local def_kind query provider for upstream DefId: {:?}", def_id);