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_data_structures::fx::FxHashMap;
10 use rustc_data_structures::svh::Svh;
11 use rustc_hir::def::{DefKind, Res};
12 use rustc_hir::def_id::{DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX};
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;
23 use syntax::ast::{self, Name, NodeId};
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 /// Stores a crate and any number of inlined items from other crates.
133 pub struct Forest<'hir> {
135 pub dep_graph: DepGraph,
139 pub fn new(krate: Crate<'hir>, dep_graph: &DepGraph) -> Forest<'hir> {
140 Forest { krate, dep_graph: dep_graph.clone() }
143 pub fn krate(&self) -> &Crate<'hir> {
144 self.dep_graph.read(DepNode::new_no_params(DepKind::Krate));
148 /// This is used internally in the dependency tracking system.
149 /// Use the `krate` method to ensure your dependency on the
150 /// crate is tracked.
151 pub fn untracked_krate(&self) -> &Crate<'hir> {
156 /// This type is effectively a `HashMap<HirId, Entry<'hir>>`,
157 /// but it is implemented as 2 layers of arrays.
158 /// - first we have `A = IndexVec<DefIndex, B>` mapping `DefIndex`s to an inner value
159 /// - which is `B = IndexVec<ItemLocalId, Option<Entry<'hir>>` which gives you the `Entry`.
160 pub(super) type HirEntryMap<'hir> = IndexVec<DefIndex, IndexVec<ItemLocalId, Option<Entry<'hir>>>>;
162 /// Represents a mapping from `NodeId`s to AST elements and their parent `NodeId`s.
164 pub struct Map<'hir> {
165 /// The backing storage for all the AST nodes.
166 pub forest: &'hir Forest<'hir>,
168 /// Same as the dep_graph in forest, just available with one fewer
169 /// deref. This is a gratuitous micro-optimization.
170 pub dep_graph: DepGraph,
172 /// The SVH of the local crate.
175 map: HirEntryMap<'hir>,
177 definitions: Definitions,
179 /// The reverse mapping of `node_to_hir_id`.
180 hir_to_node_id: FxHashMap<HirId, NodeId>,
183 struct ParentHirIterator<'map, 'hir> {
185 map: &'map Map<'hir>,
188 impl<'map, 'hir> ParentHirIterator<'map, 'hir> {
189 fn new(current_id: HirId, map: &'map Map<'hir>) -> Self {
190 Self { current_id, map }
194 impl<'hir> Iterator for ParentHirIterator<'_, 'hir> {
195 type Item = (HirId, Node<'hir>);
197 fn next(&mut self) -> Option<Self::Item> {
198 if self.current_id == CRATE_HIR_ID {
202 // There are nodes that do not have entries, so we need to skip them.
203 let parent_id = self.map.get_parent_node(self.current_id);
205 if parent_id == self.current_id {
206 self.current_id = CRATE_HIR_ID;
210 self.current_id = parent_id;
211 if let Some(entry) = self.map.find_entry(parent_id) {
212 return Some((parent_id, entry.node));
214 // If this `HirId` doesn't have an `Entry`, skip it and look for its `parent_id`.
219 impl<'hir> Map<'hir> {
221 fn lookup(&self, id: HirId) -> Option<&Entry<'hir>> {
222 let local_map = self.map.get(id.owner)?;
223 local_map.get(id.local_id)?.as_ref()
226 /// Registers a read in the dependency graph of the AST node with
227 /// the given `id`. This needs to be called each time a public
228 /// function returns the HIR for a node -- in other words, when it
229 /// "reveals" the content of a node to the caller (who might not
230 /// otherwise have had access to those contents, and hence needs a
231 /// read recorded). If the function just returns a DefId or
232 /// HirId, no actual content was returned, so no read is needed.
233 pub fn read(&self, hir_id: HirId) {
234 if let Some(entry) = self.lookup(hir_id) {
235 self.dep_graph.read_index(entry.dep_node);
237 bug!("called `HirMap::read()` with invalid `HirId`: {:?}", hir_id)
242 pub fn definitions(&self) -> &Definitions {
246 pub fn def_key(&self, def_id: DefId) -> DefKey {
247 assert!(def_id.is_local());
248 self.definitions.def_key(def_id.index)
251 pub fn def_path_from_hir_id(&self, id: HirId) -> Option<DefPath> {
252 self.opt_local_def_id(id).map(|def_id| self.def_path(def_id))
255 pub fn def_path(&self, def_id: DefId) -> DefPath {
256 assert!(def_id.is_local());
257 self.definitions.def_path(def_id.index)
261 pub fn local_def_id_from_node_id(&self, node: NodeId) -> DefId {
262 self.opt_local_def_id_from_node_id(node).unwrap_or_else(|| {
263 let hir_id = self.node_to_hir_id(node);
265 "local_def_id_from_node_id: no entry for `{}`, which has a map of `{:?}`",
267 self.find_entry(hir_id)
273 pub fn local_def_id(&self, hir_id: HirId) -> DefId {
274 self.opt_local_def_id(hir_id).unwrap_or_else(|| {
276 "local_def_id: no entry for `{:?}`, which has a map of `{:?}`",
278 self.find_entry(hir_id)
284 pub fn opt_local_def_id(&self, hir_id: HirId) -> Option<DefId> {
285 let node_id = self.hir_to_node_id(hir_id);
286 self.definitions.opt_local_def_id(node_id)
290 pub fn opt_local_def_id_from_node_id(&self, node: NodeId) -> Option<DefId> {
291 self.definitions.opt_local_def_id(node)
295 pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
296 self.definitions.as_local_node_id(def_id)
300 pub fn as_local_hir_id(&self, def_id: DefId) -> Option<HirId> {
301 self.definitions.as_local_hir_id(def_id)
305 pub fn hir_to_node_id(&self, hir_id: HirId) -> NodeId {
306 self.hir_to_node_id[&hir_id]
310 pub fn node_to_hir_id(&self, node_id: NodeId) -> HirId {
311 self.definitions.node_to_hir_id(node_id)
315 pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> HirId {
316 self.definitions.def_index_to_hir_id(def_index)
320 pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
321 self.definitions.def_index_to_hir_id(def_id.to_def_id().index)
324 pub fn def_kind(&self, hir_id: HirId) -> Option<DefKind> {
325 let node = if let Some(node) = self.find(hir_id) { node } else { return None };
328 Node::Item(item) => match item.kind {
329 ItemKind::Static(..) => DefKind::Static,
330 ItemKind::Const(..) => DefKind::Const,
331 ItemKind::Fn(..) => DefKind::Fn,
332 ItemKind::Mod(..) => DefKind::Mod,
333 ItemKind::OpaqueTy(..) => DefKind::OpaqueTy,
334 ItemKind::TyAlias(..) => DefKind::TyAlias,
335 ItemKind::Enum(..) => DefKind::Enum,
336 ItemKind::Struct(..) => DefKind::Struct,
337 ItemKind::Union(..) => DefKind::Union,
338 ItemKind::Trait(..) => DefKind::Trait,
339 ItemKind::TraitAlias(..) => DefKind::TraitAlias,
340 ItemKind::ExternCrate(_)
342 | ItemKind::ForeignMod(..)
343 | ItemKind::GlobalAsm(..)
344 | ItemKind::Impl { .. } => return None,
346 Node::ForeignItem(item) => match item.kind {
347 ForeignItemKind::Fn(..) => DefKind::Fn,
348 ForeignItemKind::Static(..) => DefKind::Static,
349 ForeignItemKind::Type => DefKind::ForeignTy,
351 Node::TraitItem(item) => match item.kind {
352 TraitItemKind::Const(..) => DefKind::AssocConst,
353 TraitItemKind::Method(..) => DefKind::Method,
354 TraitItemKind::Type(..) => DefKind::AssocTy,
356 Node::ImplItem(item) => match item.kind {
357 ImplItemKind::Const(..) => DefKind::AssocConst,
358 ImplItemKind::Method(..) => DefKind::Method,
359 ImplItemKind::TyAlias(..) => DefKind::AssocTy,
360 ImplItemKind::OpaqueTy(..) => DefKind::AssocOpaqueTy,
362 Node::Variant(_) => DefKind::Variant,
363 Node::Ctor(variant_data) => {
364 // FIXME(eddyb) is this even possible, if we have a `Node::Ctor`?
365 if variant_data.ctor_hir_id().is_none() {
368 let ctor_of = match self.find(self.get_parent_node(hir_id)) {
369 Some(Node::Item(..)) => def::CtorOf::Struct,
370 Some(Node::Variant(..)) => def::CtorOf::Variant,
373 DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data))
379 | Node::PathSegment(_)
388 | Node::Visibility(_)
390 | Node::Crate => return None,
391 Node::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
392 Node::GenericParam(param) => match param.kind {
393 GenericParamKind::Lifetime { .. } => return None,
394 GenericParamKind::Type { .. } => DefKind::TyParam,
395 GenericParamKind::Const { .. } => DefKind::ConstParam,
400 fn find_entry(&self, id: HirId) -> Option<Entry<'hir>> {
401 self.lookup(id).cloned()
404 pub fn krate(&self) -> &'hir Crate<'hir> {
408 pub fn item(&self, id: HirId) -> &'hir Item<'hir> {
411 // N.B., intentionally bypass `self.forest.krate()` so that we
412 // do not trigger a read of the whole krate here
413 self.forest.krate.item(id)
416 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
417 self.read(id.hir_id);
419 // N.B., intentionally bypass `self.forest.krate()` so that we
420 // do not trigger a read of the whole krate here
421 self.forest.krate.trait_item(id)
424 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
425 self.read(id.hir_id);
427 // N.B., intentionally bypass `self.forest.krate()` so that we
428 // do not trigger a read of the whole krate here
429 self.forest.krate.impl_item(id)
432 pub fn body(&self, id: BodyId) -> &'hir Body<'hir> {
433 self.read(id.hir_id);
435 // N.B., intentionally bypass `self.forest.krate()` so that we
436 // do not trigger a read of the whole krate here
437 self.forest.krate.body(id)
440 pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnDecl<'hir>> {
441 if let Some(entry) = self.find_entry(hir_id) {
444 bug!("no entry for hir_id `{}`", hir_id)
448 pub fn fn_sig_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnSig<'hir>> {
449 if let Some(entry) = self.find_entry(hir_id) {
452 bug!("no entry for hir_id `{}`", hir_id)
456 /// Returns the `HirId` that corresponds to the definition of
457 /// which this is the body of, i.e., a `fn`, `const` or `static`
458 /// item (possibly associated), a closure, or a `hir::AnonConst`.
459 pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> HirId {
460 let parent = self.get_parent_node(hir_id);
461 assert!(self.lookup(parent).map_or(false, |e| e.is_body_owner(hir_id)));
465 pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
466 self.local_def_id(self.body_owner(id))
469 /// Given a `HirId`, returns the `BodyId` associated with it,
470 /// if the node is a body owner, otherwise returns `None`.
471 pub fn maybe_body_owned_by(&self, hir_id: HirId) -> Option<BodyId> {
472 if let Some(entry) = self.find_entry(hir_id) {
473 if self.dep_graph.is_fully_enabled() {
474 let hir_id_owner = hir_id.owner;
475 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
476 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
479 entry.associated_body()
481 bug!("no entry for id `{}`", hir_id)
485 /// Given a body owner's id, returns the `BodyId` associated with it.
486 pub fn body_owned_by(&self, id: HirId) -> BodyId {
487 self.maybe_body_owned_by(id).unwrap_or_else(|| {
490 "body_owned_by: {} has no associated body",
491 self.node_to_string(id)
496 pub fn body_owner_kind(&self, id: HirId) -> BodyOwnerKind {
498 Node::Item(&Item { kind: ItemKind::Const(..), .. })
499 | Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. })
500 | Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. })
501 | Node::AnonConst(_) => BodyOwnerKind::Const,
503 | Node::Item(&Item { kind: ItemKind::Fn(..), .. })
504 | Node::TraitItem(&TraitItem { kind: TraitItemKind::Method(..), .. })
505 | Node::ImplItem(&ImplItem { kind: ImplItemKind::Method(..), .. }) => BodyOwnerKind::Fn,
506 Node::Item(&Item { kind: ItemKind::Static(_, m, _), .. }) => BodyOwnerKind::Static(m),
507 Node::Expr(&Expr { kind: ExprKind::Closure(..), .. }) => BodyOwnerKind::Closure,
508 node => bug!("{:#?} is not a body node", node),
512 pub fn ty_param_owner(&self, id: HirId) -> HirId {
514 Node::Item(&Item { kind: ItemKind::Trait(..), .. })
515 | Node::Item(&Item { kind: ItemKind::TraitAlias(..), .. }) => id,
516 Node::GenericParam(_) => self.get_parent_node(id),
517 _ => bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id)),
521 pub fn ty_param_name(&self, id: HirId) -> Name {
523 Node::Item(&Item { kind: ItemKind::Trait(..), .. })
524 | Node::Item(&Item { kind: ItemKind::TraitAlias(..), .. }) => kw::SelfUpper,
525 Node::GenericParam(param) => param.name.ident().name,
526 _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
530 pub fn trait_impls(&self, trait_did: DefId) -> &'hir [HirId] {
531 self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
533 // N.B., intentionally bypass `self.forest.krate()` so that we
534 // do not trigger a read of the whole krate here
535 self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
538 /// Gets the attributes on the crate. This is preferable to
539 /// invoking `krate.attrs` because it registers a tighter
540 /// dep-graph access.
541 pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
542 let def_path_hash = self.definitions.def_path_hash(CRATE_DEF_INDEX);
544 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::Hir));
545 &self.forest.krate.attrs
548 pub fn get_module(&self, module: DefId) -> (&'hir Mod<'hir>, Span, HirId) {
549 let hir_id = self.as_local_hir_id(module).unwrap();
551 match self.find_entry(hir_id).unwrap().node {
552 Node::Item(&Item { span, kind: ItemKind::Mod(ref m), .. }) => (m, span, hir_id),
553 Node::Crate => (&self.forest.krate.module, self.forest.krate.span, hir_id),
554 node => panic!("not a module: {:?}", node),
558 pub fn visit_item_likes_in_module<V>(&self, module: DefId, visitor: &mut V)
560 V: ItemLikeVisitor<'hir>,
562 let hir_id = self.as_local_hir_id(module).unwrap();
564 // Read the module so we'll be re-executed if new items
565 // appear immediately under in the module. If some new item appears
566 // in some nested item in the module, we'll be re-executed due to reads
567 // in the expect_* calls the loops below
570 let module = &self.forest.krate.modules[&hir_id];
572 for id in &module.items {
573 visitor.visit_item(self.expect_item(*id));
576 for id in &module.trait_items {
577 visitor.visit_trait_item(self.expect_trait_item(id.hir_id));
580 for id in &module.impl_items {
581 visitor.visit_impl_item(self.expect_impl_item(id.hir_id));
585 /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found.
586 pub fn get(&self, id: HirId) -> Node<'hir> {
587 // read recorded by `find`
588 self.find(id).unwrap_or_else(|| bug!("couldn't find hir id {} in the HIR map", id))
591 pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
592 self.as_local_hir_id(id).map(|id| self.get(id)) // read recorded by `get`
595 pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics<'hir>> {
596 self.get_if_local(id).and_then(|node| match node {
597 Node::ImplItem(ref impl_item) => Some(&impl_item.generics),
598 Node::TraitItem(ref trait_item) => Some(&trait_item.generics),
599 Node::Item(ref item) => match item.kind {
600 ItemKind::Fn(_, ref generics, _)
601 | ItemKind::TyAlias(_, ref generics)
602 | ItemKind::Enum(_, ref generics)
603 | ItemKind::Struct(_, ref generics)
604 | ItemKind::Union(_, ref generics)
605 | ItemKind::Trait(_, _, ref generics, ..)
606 | ItemKind::TraitAlias(ref generics, _)
607 | ItemKind::Impl { ref generics, .. } => Some(generics),
614 /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
615 pub fn find(&self, hir_id: HirId) -> Option<Node<'hir>> {
618 .and_then(|entry| if let Node::Crate = entry.node { None } else { Some(entry.node) });
619 if result.is_some() {
625 /// Similar to `get_parent`; returns the parent HIR Id, or just `hir_id` if there
626 /// is no parent. Note that the parent may be `CRATE_HIR_ID`, which is not itself
627 /// present in the map, so passing the return value of `get_parent_node` to
628 /// `get` may in fact panic.
629 /// This function returns the immediate parent in the HIR, whereas `get_parent`
630 /// returns the enclosing item. Note that this might not be the actual parent
631 /// node in the HIR -- some kinds of nodes are not in the map and these will
632 /// never appear as the parent node. Thus, you can always walk the parent nodes
633 /// from a node to the root of the HIR (unless you get back the same ID here,
634 /// which can happen if the ID is not in the map itself or is just weird).
635 pub fn get_parent_node(&self, hir_id: HirId) -> HirId {
636 if self.dep_graph.is_fully_enabled() {
637 let hir_id_owner = hir_id.owner;
638 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
639 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
642 self.find_entry(hir_id).and_then(|x| x.parent_node()).unwrap_or(hir_id)
645 /// Checks if the node is an argument. An argument is a local variable whose
646 /// immediate parent is an item or a closure.
647 pub fn is_argument(&self, id: HirId) -> bool {
648 match self.find(id) {
649 Some(Node::Binding(_)) => (),
652 match self.find(self.get_parent_node(id)) {
653 Some(Node::Item(_)) | Some(Node::TraitItem(_)) | Some(Node::ImplItem(_)) => true,
654 Some(Node::Expr(e)) => match e.kind {
655 ExprKind::Closure(..) => true,
662 /// Whether the expression pointed at by `hir_id` belongs to a `const` evaluation context.
663 /// Used exclusively for diagnostics, to avoid suggestion function calls.
664 pub fn is_const_context(&self, hir_id: HirId) -> bool {
665 let parent_id = self.get_parent_item(hir_id);
666 match self.get(parent_id) {
667 Node::Item(&Item { kind: ItemKind::Const(..), .. })
668 | Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. })
669 | Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. })
671 | Node::Item(&Item { kind: ItemKind::Static(..), .. }) => true,
672 Node::Item(&Item { kind: ItemKind::Fn(ref sig, ..), .. }) => {
673 sig.header.constness == Constness::Const
679 /// Wether `hir_id` corresponds to a `mod` or a crate.
680 pub fn is_hir_id_module(&self, hir_id: HirId) -> bool {
681 match self.lookup(hir_id) {
682 Some(Entry { node: Node::Item(Item { kind: ItemKind::Mod(_), .. }), .. })
683 | Some(Entry { node: Node::Crate, .. }) => true,
688 /// Retrieves the `HirId` for `id`'s enclosing method, unless there's a
689 /// `while` or `loop` before reaching it, as block tail returns are not
690 /// available in them.
693 /// fn foo(x: usize) -> bool {
695 /// true // If `get_return_block` gets passed the `id` corresponding
696 /// } else { // to this, it will return `foo`'s `HirId`.
703 /// fn foo(x: usize) -> bool {
705 /// true // If `get_return_block` gets passed the `id` corresponding
706 /// } // to this, it will return `None`.
710 pub fn get_return_block(&self, id: HirId) -> Option<HirId> {
711 let mut iter = ParentHirIterator::new(id, &self).peekable();
712 let mut ignore_tail = false;
713 if let Some(entry) = self.find_entry(id) {
714 if let Node::Expr(Expr { kind: ExprKind::Ret(_), .. }) = entry.node {
715 // When dealing with `return` statements, we don't care about climbing only tail
720 while let Some((hir_id, node)) = iter.next() {
721 if let (Some((_, next_node)), false) = (iter.peek(), ignore_tail) {
723 Node::Block(Block { expr: None, .. }) => return None,
724 Node::Block(Block { expr: Some(expr), .. }) => {
725 if hir_id != expr.hir_id {
726 // The current node is not the tail expression of its parent.
735 | Node::ForeignItem(_)
737 | Node::Expr(Expr { kind: ExprKind::Closure(..), .. })
738 | Node::ImplItem(_) => return Some(hir_id),
739 Node::Expr(ref expr) => {
741 // Ignore `return`s on the first iteration
742 ExprKind::Loop(..) | ExprKind::Ret(..) => return None,
746 Node::Local(_) => return None,
753 /// Retrieves the `HirId` for `id`'s parent item, or `id` itself if no
754 /// parent item is in this map. The "parent item" is the closest parent node
755 /// in the HIR which is recorded by the map and is an item, either an item
756 /// in a module, trait, or impl.
757 pub fn get_parent_item(&self, hir_id: HirId) -> HirId {
758 for (hir_id, node) in ParentHirIterator::new(hir_id, &self) {
762 | Node::ForeignItem(_)
764 | Node::ImplItem(_) => return hir_id,
771 /// Returns the `DefId` of `id`'s nearest module parent, or `id` itself if no
772 /// module parent is in this map.
773 pub fn get_module_parent(&self, id: HirId) -> DefId {
774 self.local_def_id(self.get_module_parent_node(id))
777 /// Returns the `HirId` of `id`'s nearest module parent, or `id` itself if no
778 /// module parent is in this map.
779 pub fn get_module_parent_node(&self, hir_id: HirId) -> HirId {
780 for (hir_id, node) in ParentHirIterator::new(hir_id, &self) {
781 if let Node::Item(&Item { kind: ItemKind::Mod(_), .. }) = node {
788 /// When on a match arm tail expression or on a match arm, give back the enclosing `match`
791 /// Used by error reporting when there's a type error in a match arm caused by the `match`
792 /// expression needing to be unit.
793 pub fn get_match_if_cause(&self, hir_id: HirId) -> Option<&'hir Expr<'hir>> {
794 for (_, node) in ParentHirIterator::new(hir_id, &self) {
796 Node::Item(_) | Node::ForeignItem(_) | Node::TraitItem(_) | Node::ImplItem(_) => {
799 Node::Expr(expr) => match expr.kind {
800 ExprKind::Match(_, _, _) => return Some(expr),
803 Node::Stmt(stmt) => match stmt.kind {
804 StmtKind::Local(_) => break,
813 /// Returns the nearest enclosing scope. A scope is roughly an item or block.
814 pub fn get_enclosing_scope(&self, hir_id: HirId) -> Option<HirId> {
815 for (hir_id, node) in ParentHirIterator::new(hir_id, &self) {
817 Node::Item(i) => match i.kind {
821 | ItemKind::Struct(..)
822 | ItemKind::Union(..)
823 | ItemKind::Trait(..)
824 | ItemKind::Impl { .. } => true,
827 Node::ForeignItem(fi) => match fi.kind {
828 ForeignItemKind::Fn(..) => true,
831 Node::TraitItem(ti) => match ti.kind {
832 TraitItemKind::Method(..) => true,
835 Node::ImplItem(ii) => match ii.kind {
836 ImplItemKind::Method(..) => true,
839 Node::Block(_) => true,
848 /// Returns the defining scope for an opaque type definition.
849 pub fn get_defining_scope(&self, id: HirId) -> HirId {
852 scope = self.get_enclosing_scope(scope).unwrap_or(CRATE_HIR_ID);
853 if scope == CRATE_HIR_ID {
856 match self.get(scope) {
857 Node::Item(i) => match i.kind {
858 ItemKind::OpaqueTy(OpaqueTy { impl_trait_fn: None, .. }) => {}
868 pub fn get_parent_did(&self, id: HirId) -> DefId {
869 self.local_def_id(self.get_parent_item(id))
872 pub fn get_foreign_abi(&self, hir_id: HirId) -> Abi {
873 let parent = self.get_parent_item(hir_id);
874 if let Some(entry) = self.find_entry(parent) {
876 node: Node::Item(Item { kind: ItemKind::ForeignMod(ref nm), .. }), ..
879 self.read(hir_id); // reveals some of the content of a node
883 bug!("expected foreign mod or inlined parent, found {}", self.node_to_string(parent))
886 pub fn expect_item(&self, id: HirId) -> &'hir Item<'hir> {
887 match self.find(id) {
888 // read recorded by `find`
889 Some(Node::Item(item)) => item,
890 _ => bug!("expected item, found {}", self.node_to_string(id)),
894 pub fn expect_impl_item(&self, id: HirId) -> &'hir ImplItem<'hir> {
895 match self.find(id) {
896 Some(Node::ImplItem(item)) => item,
897 _ => bug!("expected impl item, found {}", self.node_to_string(id)),
901 pub fn expect_trait_item(&self, id: HirId) -> &'hir TraitItem<'hir> {
902 match self.find(id) {
903 Some(Node::TraitItem(item)) => item,
904 _ => bug!("expected trait item, found {}", self.node_to_string(id)),
908 pub fn expect_variant_data(&self, id: HirId) -> &'hir VariantData<'hir> {
909 match self.find(id) {
910 Some(Node::Item(i)) => match i.kind {
911 ItemKind::Struct(ref struct_def, _) | ItemKind::Union(ref struct_def, _) => {
914 _ => bug!("struct ID bound to non-struct {}", self.node_to_string(id)),
916 Some(Node::Variant(variant)) => &variant.data,
917 Some(Node::Ctor(data)) => data,
918 _ => bug!("expected struct or variant, found {}", self.node_to_string(id)),
922 pub fn expect_variant(&self, id: HirId) -> &'hir Variant<'hir> {
923 match self.find(id) {
924 Some(Node::Variant(variant)) => variant,
925 _ => bug!("expected variant, found {}", self.node_to_string(id)),
929 pub fn expect_foreign_item(&self, id: HirId) -> &'hir ForeignItem<'hir> {
930 match self.find(id) {
931 Some(Node::ForeignItem(item)) => item,
932 _ => bug!("expected foreign item, found {}", self.node_to_string(id)),
936 pub fn expect_expr(&self, id: HirId) -> &'hir Expr<'hir> {
937 match self.find(id) {
938 // read recorded by find
939 Some(Node::Expr(expr)) => expr,
940 _ => bug!("expected expr, found {}", self.node_to_string(id)),
944 pub fn opt_name(&self, id: HirId) -> Option<Name> {
945 Some(match self.get(id) {
946 Node::Item(i) => i.ident.name,
947 Node::ForeignItem(fi) => fi.ident.name,
948 Node::ImplItem(ii) => ii.ident.name,
949 Node::TraitItem(ti) => ti.ident.name,
950 Node::Variant(v) => v.ident.name,
951 Node::Field(f) => f.ident.name,
952 Node::Lifetime(lt) => lt.name.ident().name,
953 Node::GenericParam(param) => param.name.ident().name,
954 Node::Binding(&Pat { kind: PatKind::Binding(_, _, l, _), .. }) => l.name,
955 Node::Ctor(..) => self.name(self.get_parent_item(id)),
960 pub fn name(&self, id: HirId) -> Name {
961 match self.opt_name(id) {
963 None => bug!("no name for {}", self.node_to_string(id)),
967 /// Given a node ID, gets a list of attributes associated with the AST
968 /// corresponding to the node-ID.
969 pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] {
970 self.read(id); // reveals attributes on the node
971 let attrs = match self.find_entry(id).map(|entry| entry.node) {
972 Some(Node::Param(a)) => Some(&a.attrs[..]),
973 Some(Node::Local(l)) => Some(&l.attrs[..]),
974 Some(Node::Item(i)) => Some(&i.attrs[..]),
975 Some(Node::ForeignItem(fi)) => Some(&fi.attrs[..]),
976 Some(Node::TraitItem(ref ti)) => Some(&ti.attrs[..]),
977 Some(Node::ImplItem(ref ii)) => Some(&ii.attrs[..]),
978 Some(Node::Variant(ref v)) => Some(&v.attrs[..]),
979 Some(Node::Field(ref f)) => Some(&f.attrs[..]),
980 Some(Node::Expr(ref e)) => Some(&*e.attrs),
981 Some(Node::Stmt(ref s)) => Some(s.kind.attrs()),
982 Some(Node::Arm(ref a)) => Some(&*a.attrs),
983 Some(Node::GenericParam(param)) => Some(¶m.attrs[..]),
984 // Unit/tuple structs/variants take the attributes straight from
985 // the struct/variant definition.
986 Some(Node::Ctor(..)) => return self.attrs(self.get_parent_item(id)),
987 Some(Node::Crate) => Some(&self.forest.krate.attrs[..]),
993 /// Returns an iterator that yields all the hir ids in the map.
994 fn all_ids<'a>(&'a self) -> impl Iterator<Item = HirId> + 'a {
995 // This code is a bit awkward because the map is implemented as 2 levels of arrays,
996 // see the comment on `HirEntryMap`.
997 // Iterate over all the indices and return a reference to
998 // local maps and their index given that they exist.
999 self.map.iter_enumerated().flat_map(move |(owner, local_map)| {
1000 // Iterate over each valid entry in the local map.
1001 local_map.iter_enumerated().filter_map(move |(i, entry)| {
1002 entry.map(move |_| {
1003 // Reconstruct the `HirId` based on the 3 indices we used to find it.
1004 HirId { owner, local_id: i }
1010 /// Returns an iterator that yields the node id's with paths that
1011 /// match `parts`. (Requires `parts` is non-empty.)
1013 /// For example, if given `parts` equal to `["bar", "quux"]`, then
1014 /// the iterator will produce node id's for items with paths
1015 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
1016 /// any other such items it can find in the map.
1017 pub fn nodes_matching_suffix<'a>(
1019 parts: &'a [String],
1020 ) -> impl Iterator<Item = NodeId> + 'a {
1021 let nodes = NodesMatchingSuffix {
1023 item_name: parts.last().unwrap(),
1024 in_which: &parts[..parts.len() - 1],
1028 .filter(move |hir| nodes.matches_suffix(*hir))
1029 .map(move |hir| self.hir_to_node_id(hir))
1032 pub fn span(&self, hir_id: HirId) -> Span {
1033 self.read(hir_id); // reveals span from node
1034 match self.find_entry(hir_id).map(|entry| entry.node) {
1035 Some(Node::Param(param)) => param.span,
1036 Some(Node::Item(item)) => item.span,
1037 Some(Node::ForeignItem(foreign_item)) => foreign_item.span,
1038 Some(Node::TraitItem(trait_method)) => trait_method.span,
1039 Some(Node::ImplItem(impl_item)) => impl_item.span,
1040 Some(Node::Variant(variant)) => variant.span,
1041 Some(Node::Field(field)) => field.span,
1042 Some(Node::AnonConst(constant)) => self.body(constant.body).value.span,
1043 Some(Node::Expr(expr)) => expr.span,
1044 Some(Node::Stmt(stmt)) => stmt.span,
1045 Some(Node::PathSegment(seg)) => seg.ident.span,
1046 Some(Node::Ty(ty)) => ty.span,
1047 Some(Node::TraitRef(tr)) => tr.path.span,
1048 Some(Node::Binding(pat)) => pat.span,
1049 Some(Node::Pat(pat)) => pat.span,
1050 Some(Node::Arm(arm)) => arm.span,
1051 Some(Node::Block(block)) => block.span,
1052 Some(Node::Ctor(..)) => match self.find(self.get_parent_node(hir_id)) {
1053 Some(Node::Item(item)) => item.span,
1054 Some(Node::Variant(variant)) => variant.span,
1055 _ => unreachable!(),
1057 Some(Node::Lifetime(lifetime)) => lifetime.span,
1058 Some(Node::GenericParam(param)) => param.span,
1059 Some(Node::Visibility(&Spanned {
1060 node: VisibilityKind::Restricted { ref path, .. },
1063 Some(Node::Visibility(v)) => bug!("unexpected Visibility {:?}", v),
1064 Some(Node::Local(local)) => local.span,
1065 Some(Node::MacroDef(macro_def)) => macro_def.span,
1066 Some(Node::Crate) => self.forest.krate.span,
1067 None => bug!("hir::map::Map::span: id not in map: {:?}", hir_id),
1071 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
1072 self.as_local_hir_id(id).map(|id| self.span(id))
1075 pub fn res_span(&self, res: Res) -> Option<Span> {
1078 Res::Local(id) => Some(self.span(id)),
1079 res => self.span_if_local(res.opt_def_id()?),
1083 pub fn node_to_string(&self, id: HirId) -> String {
1084 hir_id_to_string(self, id, true)
1087 pub fn hir_to_user_string(&self, id: HirId) -> String {
1088 hir_id_to_string(self, id, false)
1091 pub fn hir_to_pretty_string(&self, id: HirId) -> String {
1092 print::to_string(self, |s| s.print_node(self.get(id)))
1096 impl<'hir> intravisit::Map<'hir> for Map<'hir> {
1097 fn body(&self, id: BodyId) -> &'hir Body<'hir> {
1101 fn item(&self, id: HirId) -> &'hir Item<'hir> {
1105 fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
1109 fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
1114 pub struct NodesMatchingSuffix<'a> {
1116 item_name: &'a String,
1117 in_which: &'a [String],
1120 impl<'a> NodesMatchingSuffix<'a> {
1121 /// Returns `true` only if some suffix of the module path for parent
1122 /// matches `self.in_which`.
1124 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
1125 /// returns true if parent's path ends with the suffix
1126 /// `x_0::x_1::...::x_k`.
1127 fn suffix_matches(&self, parent: HirId) -> bool {
1128 let mut cursor = parent;
1129 for part in self.in_which.iter().rev() {
1130 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
1131 None => return false,
1132 Some((node_id, name)) => (node_id, name),
1134 if mod_name.as_str() != *part {
1137 cursor = self.map.get_parent_item(mod_id);
1141 // Finds the first mod in parent chain for `id`, along with
1144 // If `id` itself is a mod named `m` with parent `p`, then
1145 // returns `Some(id, m, p)`. If `id` has no mod in its parent
1146 // chain, then returns `None`.
1147 fn find_first_mod_parent(map: &Map<'_>, mut id: HirId) -> Option<(HirId, Name)> {
1149 if let Node::Item(item) = map.find(id)? {
1150 if item_is_mod(&item) {
1151 return Some((id, item.ident.name));
1154 let parent = map.get_parent_item(id);
1161 fn item_is_mod(item: &Item<'_>) -> bool {
1163 ItemKind::Mod(_) => true,
1170 // We are looking at some node `n` with a given name and parent
1171 // id; do their names match what I am seeking?
1172 fn matches_names(&self, parent_of_n: HirId, name: Name) -> bool {
1173 name.as_str() == *self.item_name && self.suffix_matches(parent_of_n)
1176 fn matches_suffix(&self, hir: HirId) -> bool {
1177 let name = match self.map.find_entry(hir).map(|entry| entry.node) {
1178 Some(Node::Item(n)) => n.name(),
1179 Some(Node::ForeignItem(n)) => n.name(),
1180 Some(Node::TraitItem(n)) => n.name(),
1181 Some(Node::ImplItem(n)) => n.name(),
1182 Some(Node::Variant(n)) => n.name(),
1183 Some(Node::Field(n)) => n.name(),
1186 self.matches_names(self.map.get_parent_item(hir), name)
1191 fn name(&self) -> Name;
1194 impl<T: Named> Named for Spanned<T> {
1195 fn name(&self) -> Name {
1200 impl Named for Item<'_> {
1201 fn name(&self) -> Name {
1205 impl Named for ForeignItem<'_> {
1206 fn name(&self) -> Name {
1210 impl Named for Variant<'_> {
1211 fn name(&self) -> Name {
1215 impl Named for StructField<'_> {
1216 fn name(&self) -> Name {
1220 impl Named for TraitItem<'_> {
1221 fn name(&self) -> Name {
1225 impl Named for ImplItem<'_> {
1226 fn name(&self) -> Name {
1231 pub fn map_crate<'hir>(
1232 sess: &rustc_session::Session,
1233 cstore: &CrateStoreDyn,
1234 forest: &'hir Forest<'hir>,
1235 definitions: Definitions,
1237 let _prof_timer = sess.prof.generic_activity("build_hir_map");
1239 // Build the reverse mapping of `node_to_hir_id`.
1240 let hir_to_node_id = definitions
1243 .map(|(node_id, &hir_id)| (hir_id, node_id))
1246 let (map, crate_hash) = {
1247 let hcx = crate::ich::StableHashingContext::new(sess, &forest.krate, &definitions, cstore);
1249 let mut collector = NodeCollector::root(
1257 intravisit::walk_crate(&mut collector, &forest.krate);
1259 let crate_disambiguator = sess.local_crate_disambiguator();
1260 let cmdline_args = sess.opts.dep_tracking_hash();
1261 collector.finalize_and_compute_crate_hash(crate_disambiguator, cstore, cmdline_args)
1266 dep_graph: forest.dep_graph.clone(),
1273 sess.time("validate_HIR_map", || {
1274 hir_id_validator::check_crate(&map);
1280 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1281 /// except it avoids creating a dependency on the whole crate.
1282 impl<'hir> print::PpAnn for Map<'hir> {
1283 fn nested(&self, state: &mut print::State<'_>, nested: print::Nested) {
1285 Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1286 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1287 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1288 Nested::Body(id) => state.print_expr(&self.body(id).value),
1289 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
1294 fn hir_id_to_string(map: &Map<'_>, id: HirId, include_id: bool) -> String {
1295 let id_str = format!(" (hir_id={})", id);
1296 let id_str = if include_id { &id_str[..] } else { "" };
1299 // This functionality is used for debugging, try to use `TyCtxt` to get
1300 // the user-friendly path, otherwise fall back to stringifying `DefPath`.
1301 crate::ty::tls::with_opt(|tcx| {
1302 if let Some(tcx) = tcx {
1303 let def_id = map.local_def_id(id);
1304 tcx.def_path_str(def_id)
1305 } else if let Some(path) = map.def_path_from_hir_id(id) {
1308 .map(|elem| elem.data.to_string())
1309 .collect::<Vec<_>>()
1312 String::from("<missing path>")
1317 match map.find(id) {
1318 Some(Node::Item(item)) => {
1319 let item_str = match item.kind {
1320 ItemKind::ExternCrate(..) => "extern crate",
1321 ItemKind::Use(..) => "use",
1322 ItemKind::Static(..) => "static",
1323 ItemKind::Const(..) => "const",
1324 ItemKind::Fn(..) => "fn",
1325 ItemKind::Mod(..) => "mod",
1326 ItemKind::ForeignMod(..) => "foreign mod",
1327 ItemKind::GlobalAsm(..) => "global asm",
1328 ItemKind::TyAlias(..) => "ty",
1329 ItemKind::OpaqueTy(..) => "opaque type",
1330 ItemKind::Enum(..) => "enum",
1331 ItemKind::Struct(..) => "struct",
1332 ItemKind::Union(..) => "union",
1333 ItemKind::Trait(..) => "trait",
1334 ItemKind::TraitAlias(..) => "trait alias",
1335 ItemKind::Impl { .. } => "impl",
1337 format!("{} {}{}", item_str, path_str(), id_str)
1339 Some(Node::ForeignItem(_)) => format!("foreign item {}{}", path_str(), id_str),
1340 Some(Node::ImplItem(ii)) => match ii.kind {
1341 ImplItemKind::Const(..) => {
1342 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1344 ImplItemKind::Method(..) => format!("method {} in {}{}", ii.ident, path_str(), id_str),
1345 ImplItemKind::TyAlias(_) => {
1346 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1348 ImplItemKind::OpaqueTy(_) => {
1349 format!("assoc opaque type {} in {}{}", ii.ident, path_str(), id_str)
1352 Some(Node::TraitItem(ti)) => {
1353 let kind = match ti.kind {
1354 TraitItemKind::Const(..) => "assoc constant",
1355 TraitItemKind::Method(..) => "trait method",
1356 TraitItemKind::Type(..) => "assoc type",
1359 format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1361 Some(Node::Variant(ref variant)) => {
1362 format!("variant {} in {}{}", variant.ident, path_str(), id_str)
1364 Some(Node::Field(ref field)) => {
1365 format!("field {} in {}{}", field.ident, path_str(), id_str)
1367 Some(Node::AnonConst(_)) => format!("const {}{}", map.hir_to_pretty_string(id), id_str),
1368 Some(Node::Expr(_)) => format!("expr {}{}", map.hir_to_pretty_string(id), id_str),
1369 Some(Node::Stmt(_)) => format!("stmt {}{}", map.hir_to_pretty_string(id), id_str),
1370 Some(Node::PathSegment(_)) => {
1371 format!("path segment {}{}", map.hir_to_pretty_string(id), id_str)
1373 Some(Node::Ty(_)) => format!("type {}{}", map.hir_to_pretty_string(id), id_str),
1374 Some(Node::TraitRef(_)) => format!("trait_ref {}{}", map.hir_to_pretty_string(id), id_str),
1375 Some(Node::Binding(_)) => format!("local {}{}", map.hir_to_pretty_string(id), id_str),
1376 Some(Node::Pat(_)) => format!("pat {}{}", map.hir_to_pretty_string(id), id_str),
1377 Some(Node::Param(_)) => format!("param {}{}", map.hir_to_pretty_string(id), id_str),
1378 Some(Node::Arm(_)) => format!("arm {}{}", map.hir_to_pretty_string(id), id_str),
1379 Some(Node::Block(_)) => format!("block {}{}", map.hir_to_pretty_string(id), id_str),
1380 Some(Node::Local(_)) => format!("local {}{}", map.hir_to_pretty_string(id), id_str),
1381 Some(Node::Ctor(..)) => format!("ctor {}{}", path_str(), id_str),
1382 Some(Node::Lifetime(_)) => format!("lifetime {}{}", map.hir_to_pretty_string(id), id_str),
1383 Some(Node::GenericParam(ref param)) => format!("generic_param {:?}{}", param, id_str),
1384 Some(Node::Visibility(ref vis)) => format!("visibility {:?}{}", vis, id_str),
1385 Some(Node::MacroDef(_)) => format!("macro {}{}", path_str(), id_str),
1386 Some(Node::Crate) => String::from("root_crate"),
1387 None => format!("unknown node{}", id_str),
1391 pub fn provide(providers: &mut Providers<'_>) {
1392 providers.def_kind = |tcx, def_id| {
1393 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
1394 tcx.hir().def_kind(hir_id)
1396 bug!("calling local def_kind query provider for upstream DefId: {:?}", def_id);