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 `HirId` of `id`'s nearest module parent, or `id` itself if no
750 /// module parent is in this map.
751 pub(super) fn get_module_parent_node(&self, hir_id: HirId) -> HirId {
752 for (hir_id, node) in self.parent_iter(hir_id) {
753 if let Node::Item(&Item { kind: ItemKind::Mod(_), .. }) = node {
760 /// When on a match arm tail expression or on a match arm, give back the enclosing `match`
763 /// Used by error reporting when there's a type error in a match arm caused by the `match`
764 /// expression needing to be unit.
765 pub fn get_match_if_cause(&self, hir_id: HirId) -> Option<&'hir Expr<'hir>> {
766 for (_, node) in self.parent_iter(hir_id) {
768 Node::Item(_) | Node::ForeignItem(_) | Node::TraitItem(_) | Node::ImplItem(_) => {
771 Node::Expr(expr) => match expr.kind {
772 ExprKind::Match(_, _, _) => return Some(expr),
775 Node::Stmt(stmt) => match stmt.kind {
776 StmtKind::Local(_) => break,
785 /// Returns the nearest enclosing scope. A scope is roughly an item or block.
786 pub fn get_enclosing_scope(&self, hir_id: HirId) -> Option<HirId> {
787 for (hir_id, node) in self.parent_iter(hir_id) {
789 Node::Item(i) => match i.kind {
793 | ItemKind::Struct(..)
794 | ItemKind::Union(..)
795 | ItemKind::Trait(..)
796 | ItemKind::Impl { .. } => true,
799 Node::ForeignItem(fi) => match fi.kind {
800 ForeignItemKind::Fn(..) => true,
803 Node::TraitItem(ti) => match ti.kind {
804 TraitItemKind::Method(..) => true,
807 Node::ImplItem(ii) => match ii.kind {
808 ImplItemKind::Method(..) => true,
811 Node::Block(_) => true,
820 /// Returns the defining scope for an opaque type definition.
821 pub fn get_defining_scope(&self, id: HirId) -> HirId {
824 scope = self.get_enclosing_scope(scope).unwrap_or(CRATE_HIR_ID);
825 if scope == CRATE_HIR_ID {
828 match self.get(scope) {
829 Node::Item(i) => match i.kind {
830 ItemKind::OpaqueTy(OpaqueTy { impl_trait_fn: None, .. }) => {}
840 pub fn get_parent_did(&self, id: HirId) -> DefId {
841 self.local_def_id(self.get_parent_item(id))
844 pub fn get_foreign_abi(&self, hir_id: HirId) -> Abi {
845 let parent = self.get_parent_item(hir_id);
846 if let Some(entry) = self.find_entry(parent) {
848 node: Node::Item(Item { kind: ItemKind::ForeignMod(ref nm), .. }), ..
851 self.read(hir_id); // reveals some of the content of a node
855 bug!("expected foreign mod or inlined parent, found {}", self.node_to_string(parent))
858 pub fn expect_item(&self, id: HirId) -> &'hir Item<'hir> {
859 match self.find(id) {
860 // read recorded by `find`
861 Some(Node::Item(item)) => item,
862 _ => bug!("expected item, found {}", self.node_to_string(id)),
866 pub fn expect_impl_item(&self, id: HirId) -> &'hir ImplItem<'hir> {
867 match self.find(id) {
868 Some(Node::ImplItem(item)) => item,
869 _ => bug!("expected impl item, found {}", self.node_to_string(id)),
873 pub fn expect_trait_item(&self, id: HirId) -> &'hir TraitItem<'hir> {
874 match self.find(id) {
875 Some(Node::TraitItem(item)) => item,
876 _ => bug!("expected trait item, found {}", self.node_to_string(id)),
880 pub fn expect_variant_data(&self, id: HirId) -> &'hir VariantData<'hir> {
881 match self.find(id) {
882 Some(Node::Item(i)) => match i.kind {
883 ItemKind::Struct(ref struct_def, _) | ItemKind::Union(ref struct_def, _) => {
886 _ => bug!("struct ID bound to non-struct {}", self.node_to_string(id)),
888 Some(Node::Variant(variant)) => &variant.data,
889 Some(Node::Ctor(data)) => data,
890 _ => bug!("expected struct or variant, found {}", self.node_to_string(id)),
894 pub fn expect_variant(&self, id: HirId) -> &'hir Variant<'hir> {
895 match self.find(id) {
896 Some(Node::Variant(variant)) => variant,
897 _ => bug!("expected variant, found {}", self.node_to_string(id)),
901 pub fn expect_foreign_item(&self, id: HirId) -> &'hir ForeignItem<'hir> {
902 match self.find(id) {
903 Some(Node::ForeignItem(item)) => item,
904 _ => bug!("expected foreign item, found {}", self.node_to_string(id)),
908 pub fn expect_expr(&self, id: HirId) -> &'hir Expr<'hir> {
909 match self.find(id) {
910 // read recorded by find
911 Some(Node::Expr(expr)) => expr,
912 _ => bug!("expected expr, found {}", self.node_to_string(id)),
916 pub fn opt_name(&self, id: HirId) -> Option<Name> {
917 Some(match self.get(id) {
918 Node::Item(i) => i.ident.name,
919 Node::ForeignItem(fi) => fi.ident.name,
920 Node::ImplItem(ii) => ii.ident.name,
921 Node::TraitItem(ti) => ti.ident.name,
922 Node::Variant(v) => v.ident.name,
923 Node::Field(f) => f.ident.name,
924 Node::Lifetime(lt) => lt.name.ident().name,
925 Node::GenericParam(param) => param.name.ident().name,
926 Node::Binding(&Pat { kind: PatKind::Binding(_, _, l, _), .. }) => l.name,
927 Node::Ctor(..) => self.name(self.get_parent_item(id)),
932 pub fn name(&self, id: HirId) -> Name {
933 match self.opt_name(id) {
935 None => bug!("no name for {}", self.node_to_string(id)),
939 /// Given a node ID, gets a list of attributes associated with the AST
940 /// corresponding to the node-ID.
941 pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] {
942 self.read(id); // reveals attributes on the node
943 let attrs = match self.find_entry(id).map(|entry| entry.node) {
944 Some(Node::Param(a)) => Some(&a.attrs[..]),
945 Some(Node::Local(l)) => Some(&l.attrs[..]),
946 Some(Node::Item(i)) => Some(&i.attrs[..]),
947 Some(Node::ForeignItem(fi)) => Some(&fi.attrs[..]),
948 Some(Node::TraitItem(ref ti)) => Some(&ti.attrs[..]),
949 Some(Node::ImplItem(ref ii)) => Some(&ii.attrs[..]),
950 Some(Node::Variant(ref v)) => Some(&v.attrs[..]),
951 Some(Node::Field(ref f)) => Some(&f.attrs[..]),
952 Some(Node::Expr(ref e)) => Some(&*e.attrs),
953 Some(Node::Stmt(ref s)) => Some(s.kind.attrs()),
954 Some(Node::Arm(ref a)) => Some(&*a.attrs),
955 Some(Node::GenericParam(param)) => Some(¶m.attrs[..]),
956 // Unit/tuple structs/variants take the attributes straight from
957 // the struct/variant definition.
958 Some(Node::Ctor(..)) => return self.attrs(self.get_parent_item(id)),
959 Some(Node::Crate) => Some(&self.krate.attrs[..]),
965 /// Returns an iterator that yields all the hir ids in the map.
966 fn all_ids<'a>(&'a self) -> impl Iterator<Item = HirId> + 'a {
967 // This code is a bit awkward because the map is implemented as 2 levels of arrays,
968 // see the comment on `HirEntryMap`.
969 // Iterate over all the indices and return a reference to
970 // local maps and their index given that they exist.
971 self.map.iter_enumerated().flat_map(move |(owner, local_map)| {
972 // Iterate over each valid entry in the local map.
973 local_map.iter_enumerated().filter_map(move |(i, entry)| {
975 // Reconstruct the `HirId` based on the 3 indices we used to find it.
976 HirId { owner, local_id: i }
982 /// Returns an iterator that yields the node id's with paths that
983 /// match `parts`. (Requires `parts` is non-empty.)
985 /// For example, if given `parts` equal to `["bar", "quux"]`, then
986 /// the iterator will produce node id's for items with paths
987 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
988 /// any other such items it can find in the map.
989 pub fn nodes_matching_suffix<'a>(
992 ) -> impl Iterator<Item = NodeId> + 'a {
993 let nodes = NodesMatchingSuffix {
995 item_name: parts.last().unwrap(),
996 in_which: &parts[..parts.len() - 1],
1000 .filter(move |hir| nodes.matches_suffix(*hir))
1001 .map(move |hir| self.hir_to_node_id(hir))
1004 pub fn span(&self, hir_id: HirId) -> Span {
1005 self.read(hir_id); // reveals span from node
1006 match self.find_entry(hir_id).map(|entry| entry.node) {
1007 Some(Node::Param(param)) => param.span,
1008 Some(Node::Item(item)) => item.span,
1009 Some(Node::ForeignItem(foreign_item)) => foreign_item.span,
1010 Some(Node::TraitItem(trait_method)) => trait_method.span,
1011 Some(Node::ImplItem(impl_item)) => impl_item.span,
1012 Some(Node::Variant(variant)) => variant.span,
1013 Some(Node::Field(field)) => field.span,
1014 Some(Node::AnonConst(constant)) => self.body(constant.body).value.span,
1015 Some(Node::Expr(expr)) => expr.span,
1016 Some(Node::Stmt(stmt)) => stmt.span,
1017 Some(Node::PathSegment(seg)) => seg.ident.span,
1018 Some(Node::Ty(ty)) => ty.span,
1019 Some(Node::TraitRef(tr)) => tr.path.span,
1020 Some(Node::Binding(pat)) => pat.span,
1021 Some(Node::Pat(pat)) => pat.span,
1022 Some(Node::Arm(arm)) => arm.span,
1023 Some(Node::Block(block)) => block.span,
1024 Some(Node::Ctor(..)) => match self.find(self.get_parent_node(hir_id)) {
1025 Some(Node::Item(item)) => item.span,
1026 Some(Node::Variant(variant)) => variant.span,
1027 _ => unreachable!(),
1029 Some(Node::Lifetime(lifetime)) => lifetime.span,
1030 Some(Node::GenericParam(param)) => param.span,
1031 Some(Node::Visibility(&Spanned {
1032 node: VisibilityKind::Restricted { ref path, .. },
1035 Some(Node::Visibility(v)) => bug!("unexpected Visibility {:?}", v),
1036 Some(Node::Local(local)) => local.span,
1037 Some(Node::MacroDef(macro_def)) => macro_def.span,
1038 Some(Node::Crate) => self.krate.span,
1039 None => bug!("hir::map::Map::span: id not in map: {:?}", hir_id),
1043 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
1044 self.as_local_hir_id(id).map(|id| self.span(id))
1047 pub fn res_span(&self, res: Res) -> Option<Span> {
1050 Res::Local(id) => Some(self.span(id)),
1051 res => self.span_if_local(res.opt_def_id()?),
1055 pub fn node_to_string(&self, id: HirId) -> String {
1056 hir_id_to_string(self, id, true)
1059 pub fn hir_to_user_string(&self, id: HirId) -> String {
1060 hir_id_to_string(self, id, false)
1063 pub fn hir_to_pretty_string(&self, id: HirId) -> String {
1064 print::to_string(self, |s| s.print_node(self.get(id)))
1068 impl<'hir> intravisit::Map<'hir> for Map<'hir> {
1069 fn body(&self, id: BodyId) -> &'hir Body<'hir> {
1073 fn item(&self, id: HirId) -> &'hir Item<'hir> {
1077 fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
1081 fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
1086 pub struct NodesMatchingSuffix<'a> {
1088 item_name: &'a String,
1089 in_which: &'a [String],
1092 impl<'a> NodesMatchingSuffix<'a> {
1093 /// Returns `true` only if some suffix of the module path for parent
1094 /// matches `self.in_which`.
1096 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
1097 /// returns true if parent's path ends with the suffix
1098 /// `x_0::x_1::...::x_k`.
1099 fn suffix_matches(&self, parent: HirId) -> bool {
1100 let mut cursor = parent;
1101 for part in self.in_which.iter().rev() {
1102 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
1103 None => return false,
1104 Some((node_id, name)) => (node_id, name),
1106 if mod_name.as_str() != *part {
1109 cursor = self.map.get_parent_item(mod_id);
1113 // Finds the first mod in parent chain for `id`, along with
1116 // If `id` itself is a mod named `m` with parent `p`, then
1117 // returns `Some(id, m, p)`. If `id` has no mod in its parent
1118 // chain, then returns `None`.
1119 fn find_first_mod_parent(map: &Map<'_>, mut id: HirId) -> Option<(HirId, Name)> {
1121 if let Node::Item(item) = map.find(id)? {
1122 if item_is_mod(&item) {
1123 return Some((id, item.ident.name));
1126 let parent = map.get_parent_item(id);
1133 fn item_is_mod(item: &Item<'_>) -> bool {
1135 ItemKind::Mod(_) => true,
1142 // We are looking at some node `n` with a given name and parent
1143 // id; do their names match what I am seeking?
1144 fn matches_names(&self, parent_of_n: HirId, name: Name) -> bool {
1145 name.as_str() == *self.item_name && self.suffix_matches(parent_of_n)
1148 fn matches_suffix(&self, hir: HirId) -> bool {
1149 let name = match self.map.find_entry(hir).map(|entry| entry.node) {
1150 Some(Node::Item(n)) => n.name(),
1151 Some(Node::ForeignItem(n)) => n.name(),
1152 Some(Node::TraitItem(n)) => n.name(),
1153 Some(Node::ImplItem(n)) => n.name(),
1154 Some(Node::Variant(n)) => n.name(),
1155 Some(Node::Field(n)) => n.name(),
1158 self.matches_names(self.map.get_parent_item(hir), name)
1163 fn name(&self) -> Name;
1166 impl<T: Named> Named for Spanned<T> {
1167 fn name(&self) -> Name {
1172 impl Named for Item<'_> {
1173 fn name(&self) -> Name {
1177 impl Named for ForeignItem<'_> {
1178 fn name(&self) -> Name {
1182 impl Named for Variant<'_> {
1183 fn name(&self) -> Name {
1187 impl Named for StructField<'_> {
1188 fn name(&self) -> Name {
1192 impl Named for TraitItem<'_> {
1193 fn name(&self) -> Name {
1197 impl Named for ImplItem<'_> {
1198 fn name(&self) -> Name {
1203 pub fn map_crate<'hir>(
1204 sess: &rustc_session::Session,
1205 cstore: &CrateStoreDyn,
1206 krate: &'hir Crate<'hir>,
1207 dep_graph: DepGraph,
1208 definitions: Definitions,
1210 let _prof_timer = sess.prof.generic_activity("build_hir_map");
1212 // Build the reverse mapping of `node_to_hir_id`.
1213 let hir_to_node_id = definitions
1216 .map(|(node_id, &hir_id)| (hir_id, node_id))
1219 let (map, crate_hash) = {
1220 let hcx = crate::ich::StableHashingContext::new(sess, krate, &definitions, cstore);
1223 NodeCollector::root(sess, krate, &dep_graph, &definitions, &hir_to_node_id, hcx);
1224 intravisit::walk_crate(&mut collector, krate);
1226 let crate_disambiguator = sess.local_crate_disambiguator();
1227 let cmdline_args = sess.opts.dep_tracking_hash();
1228 collector.finalize_and_compute_crate_hash(crate_disambiguator, cstore, cmdline_args)
1231 let map = Map { krate, dep_graph, crate_hash, map, hir_to_node_id, definitions };
1233 sess.time("validate_HIR_map", || {
1234 hir_id_validator::check_crate(&map, sess);
1240 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1241 /// except it avoids creating a dependency on the whole crate.
1242 impl<'hir> print::PpAnn for Map<'hir> {
1243 fn nested(&self, state: &mut print::State<'_>, nested: print::Nested) {
1245 Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1246 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1247 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1248 Nested::Body(id) => state.print_expr(&self.body(id).value),
1249 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
1254 fn hir_id_to_string(map: &Map<'_>, id: HirId, include_id: bool) -> String {
1255 let id_str = format!(" (hir_id={})", id);
1256 let id_str = if include_id { &id_str[..] } else { "" };
1259 // This functionality is used for debugging, try to use `TyCtxt` to get
1260 // the user-friendly path, otherwise fall back to stringifying `DefPath`.
1261 crate::ty::tls::with_opt(|tcx| {
1262 if let Some(tcx) = tcx {
1263 let def_id = map.local_def_id(id);
1264 tcx.def_path_str(def_id)
1265 } else if let Some(path) = map.def_path_from_hir_id(id) {
1268 .map(|elem| elem.data.to_string())
1269 .collect::<Vec<_>>()
1272 String::from("<missing path>")
1277 match map.find(id) {
1278 Some(Node::Item(item)) => {
1279 let item_str = match item.kind {
1280 ItemKind::ExternCrate(..) => "extern crate",
1281 ItemKind::Use(..) => "use",
1282 ItemKind::Static(..) => "static",
1283 ItemKind::Const(..) => "const",
1284 ItemKind::Fn(..) => "fn",
1285 ItemKind::Mod(..) => "mod",
1286 ItemKind::ForeignMod(..) => "foreign mod",
1287 ItemKind::GlobalAsm(..) => "global asm",
1288 ItemKind::TyAlias(..) => "ty",
1289 ItemKind::OpaqueTy(..) => "opaque type",
1290 ItemKind::Enum(..) => "enum",
1291 ItemKind::Struct(..) => "struct",
1292 ItemKind::Union(..) => "union",
1293 ItemKind::Trait(..) => "trait",
1294 ItemKind::TraitAlias(..) => "trait alias",
1295 ItemKind::Impl { .. } => "impl",
1297 format!("{} {}{}", item_str, path_str(), id_str)
1299 Some(Node::ForeignItem(_)) => format!("foreign item {}{}", path_str(), id_str),
1300 Some(Node::ImplItem(ii)) => match ii.kind {
1301 ImplItemKind::Const(..) => {
1302 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1304 ImplItemKind::Method(..) => format!("method {} in {}{}", ii.ident, path_str(), id_str),
1305 ImplItemKind::TyAlias(_) => {
1306 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1308 ImplItemKind::OpaqueTy(_) => {
1309 format!("assoc opaque type {} in {}{}", ii.ident, path_str(), id_str)
1312 Some(Node::TraitItem(ti)) => {
1313 let kind = match ti.kind {
1314 TraitItemKind::Const(..) => "assoc constant",
1315 TraitItemKind::Method(..) => "trait method",
1316 TraitItemKind::Type(..) => "assoc type",
1319 format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1321 Some(Node::Variant(ref variant)) => {
1322 format!("variant {} in {}{}", variant.ident, path_str(), id_str)
1324 Some(Node::Field(ref field)) => {
1325 format!("field {} in {}{}", field.ident, path_str(), id_str)
1327 Some(Node::AnonConst(_)) => format!("const {}{}", map.hir_to_pretty_string(id), id_str),
1328 Some(Node::Expr(_)) => format!("expr {}{}", map.hir_to_pretty_string(id), id_str),
1329 Some(Node::Stmt(_)) => format!("stmt {}{}", map.hir_to_pretty_string(id), id_str),
1330 Some(Node::PathSegment(_)) => {
1331 format!("path segment {}{}", map.hir_to_pretty_string(id), id_str)
1333 Some(Node::Ty(_)) => format!("type {}{}", map.hir_to_pretty_string(id), id_str),
1334 Some(Node::TraitRef(_)) => format!("trait_ref {}{}", map.hir_to_pretty_string(id), id_str),
1335 Some(Node::Binding(_)) => format!("local {}{}", map.hir_to_pretty_string(id), id_str),
1336 Some(Node::Pat(_)) => format!("pat {}{}", map.hir_to_pretty_string(id), id_str),
1337 Some(Node::Param(_)) => format!("param {}{}", map.hir_to_pretty_string(id), id_str),
1338 Some(Node::Arm(_)) => format!("arm {}{}", map.hir_to_pretty_string(id), id_str),
1339 Some(Node::Block(_)) => format!("block {}{}", map.hir_to_pretty_string(id), id_str),
1340 Some(Node::Local(_)) => format!("local {}{}", map.hir_to_pretty_string(id), id_str),
1341 Some(Node::Ctor(..)) => format!("ctor {}{}", path_str(), id_str),
1342 Some(Node::Lifetime(_)) => format!("lifetime {}{}", map.hir_to_pretty_string(id), id_str),
1343 Some(Node::GenericParam(ref param)) => format!("generic_param {:?}{}", param, id_str),
1344 Some(Node::Visibility(ref vis)) => format!("visibility {:?}{}", vis, id_str),
1345 Some(Node::MacroDef(_)) => format!("macro {}{}", path_str(), id_str),
1346 Some(Node::Crate) => String::from("root_crate"),
1347 None => format!("unknown node{}", id_str),
1351 pub fn provide(providers: &mut Providers<'_>) {
1352 providers.def_kind = |tcx, def_id| {
1353 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
1354 tcx.hir().def_kind(hir_id)
1356 bug!("calling local def_kind query provider for upstream DefId: {:?}", def_id);