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 /// This is used internally in the dependency tracking system.
144 /// Use the `krate` method to ensure your dependency on the
145 /// crate is tracked.
146 pub fn untracked_krate(&self) -> &Crate<'hir> {
151 /// This type is effectively a `HashMap<HirId, Entry<'hir>>`,
152 /// but it is implemented as 2 layers of arrays.
153 /// - first we have `A = IndexVec<DefIndex, B>` mapping `DefIndex`s to an inner value
154 /// - which is `B = IndexVec<ItemLocalId, Option<Entry<'hir>>` which gives you the `Entry`.
155 pub(super) type HirEntryMap<'hir> = IndexVec<DefIndex, IndexVec<ItemLocalId, Option<Entry<'hir>>>>;
157 /// Represents a mapping from `NodeId`s to AST elements and their parent `NodeId`s.
159 pub struct Map<'hir> {
160 /// The backing storage for all the AST nodes.
161 pub forest: &'hir Forest<'hir>,
163 /// Same as the dep_graph in forest, just available with one fewer
164 /// deref. This is a gratuitous micro-optimization.
165 pub dep_graph: DepGraph,
167 /// The SVH of the local crate.
170 map: HirEntryMap<'hir>,
172 definitions: Definitions,
174 /// The reverse mapping of `node_to_hir_id`.
175 hir_to_node_id: FxHashMap<HirId, NodeId>,
178 struct ParentHirIterator<'map, 'hir> {
180 map: &'map Map<'hir>,
183 impl<'map, 'hir> ParentHirIterator<'map, 'hir> {
184 fn new(current_id: HirId, map: &'map Map<'hir>) -> Self {
185 Self { current_id, map }
189 impl<'hir> Iterator for ParentHirIterator<'_, 'hir> {
190 type Item = (HirId, Node<'hir>);
192 fn next(&mut self) -> Option<Self::Item> {
193 if self.current_id == CRATE_HIR_ID {
197 // There are nodes that do not have entries, so we need to skip them.
198 let parent_id = self.map.get_parent_node(self.current_id);
200 if parent_id == self.current_id {
201 self.current_id = CRATE_HIR_ID;
205 self.current_id = parent_id;
206 if let Some(entry) = self.map.find_entry(parent_id) {
207 return Some((parent_id, entry.node));
209 // If this `HirId` doesn't have an `Entry`, skip it and look for its `parent_id`.
214 impl<'hir> Map<'hir> {
216 fn lookup(&self, id: HirId) -> Option<&Entry<'hir>> {
217 let local_map = self.map.get(id.owner)?;
218 local_map.get(id.local_id)?.as_ref()
221 /// Registers a read in the dependency graph of the AST node with
222 /// the given `id`. This needs to be called each time a public
223 /// function returns the HIR for a node -- in other words, when it
224 /// "reveals" the content of a node to the caller (who might not
225 /// otherwise have had access to those contents, and hence needs a
226 /// read recorded). If the function just returns a DefId or
227 /// HirId, no actual content was returned, so no read is needed.
228 pub fn read(&self, hir_id: HirId) {
229 if let Some(entry) = self.lookup(hir_id) {
230 self.dep_graph.read_index(entry.dep_node);
232 bug!("called `HirMap::read()` with invalid `HirId`: {:?}", hir_id)
237 pub fn definitions(&self) -> &Definitions {
241 pub fn def_key(&self, def_id: DefId) -> DefKey {
242 assert!(def_id.is_local());
243 self.definitions.def_key(def_id.index)
246 pub fn def_path_from_hir_id(&self, id: HirId) -> Option<DefPath> {
247 self.opt_local_def_id(id).map(|def_id| self.def_path(def_id))
250 pub fn def_path(&self, def_id: DefId) -> DefPath {
251 assert!(def_id.is_local());
252 self.definitions.def_path(def_id.index)
256 pub fn local_def_id_from_node_id(&self, node: NodeId) -> DefId {
257 self.opt_local_def_id_from_node_id(node).unwrap_or_else(|| {
258 let hir_id = self.node_to_hir_id(node);
260 "local_def_id_from_node_id: no entry for `{}`, which has a map of `{:?}`",
262 self.find_entry(hir_id)
268 pub fn local_def_id(&self, hir_id: HirId) -> DefId {
269 self.opt_local_def_id(hir_id).unwrap_or_else(|| {
271 "local_def_id: no entry for `{:?}`, which has a map of `{:?}`",
273 self.find_entry(hir_id)
279 pub fn opt_local_def_id(&self, hir_id: HirId) -> Option<DefId> {
280 let node_id = self.hir_to_node_id(hir_id);
281 self.definitions.opt_local_def_id(node_id)
285 pub fn opt_local_def_id_from_node_id(&self, node: NodeId) -> Option<DefId> {
286 self.definitions.opt_local_def_id(node)
290 pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
291 self.definitions.as_local_node_id(def_id)
295 pub fn as_local_hir_id(&self, def_id: DefId) -> Option<HirId> {
296 self.definitions.as_local_hir_id(def_id)
300 pub fn hir_to_node_id(&self, hir_id: HirId) -> NodeId {
301 self.hir_to_node_id[&hir_id]
305 pub fn node_to_hir_id(&self, node_id: NodeId) -> HirId {
306 self.definitions.node_to_hir_id(node_id)
310 pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> HirId {
311 self.definitions.def_index_to_hir_id(def_index)
315 pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
316 self.definitions.def_index_to_hir_id(def_id.to_def_id().index)
319 pub fn def_kind(&self, hir_id: HirId) -> Option<DefKind> {
320 let node = if let Some(node) = self.find(hir_id) { node } else { return None };
323 Node::Item(item) => match item.kind {
324 ItemKind::Static(..) => DefKind::Static,
325 ItemKind::Const(..) => DefKind::Const,
326 ItemKind::Fn(..) => DefKind::Fn,
327 ItemKind::Mod(..) => DefKind::Mod,
328 ItemKind::OpaqueTy(..) => DefKind::OpaqueTy,
329 ItemKind::TyAlias(..) => DefKind::TyAlias,
330 ItemKind::Enum(..) => DefKind::Enum,
331 ItemKind::Struct(..) => DefKind::Struct,
332 ItemKind::Union(..) => DefKind::Union,
333 ItemKind::Trait(..) => DefKind::Trait,
334 ItemKind::TraitAlias(..) => DefKind::TraitAlias,
335 ItemKind::ExternCrate(_)
337 | ItemKind::ForeignMod(..)
338 | ItemKind::GlobalAsm(..)
339 | ItemKind::Impl { .. } => return None,
341 Node::ForeignItem(item) => match item.kind {
342 ForeignItemKind::Fn(..) => DefKind::Fn,
343 ForeignItemKind::Static(..) => DefKind::Static,
344 ForeignItemKind::Type => DefKind::ForeignTy,
346 Node::TraitItem(item) => match item.kind {
347 TraitItemKind::Const(..) => DefKind::AssocConst,
348 TraitItemKind::Method(..) => DefKind::Method,
349 TraitItemKind::Type(..) => DefKind::AssocTy,
351 Node::ImplItem(item) => match item.kind {
352 ImplItemKind::Const(..) => DefKind::AssocConst,
353 ImplItemKind::Method(..) => DefKind::Method,
354 ImplItemKind::TyAlias(..) => DefKind::AssocTy,
355 ImplItemKind::OpaqueTy(..) => DefKind::AssocOpaqueTy,
357 Node::Variant(_) => DefKind::Variant,
358 Node::Ctor(variant_data) => {
359 // FIXME(eddyb) is this even possible, if we have a `Node::Ctor`?
360 if variant_data.ctor_hir_id().is_none() {
363 let ctor_of = match self.find(self.get_parent_node(hir_id)) {
364 Some(Node::Item(..)) => def::CtorOf::Struct,
365 Some(Node::Variant(..)) => def::CtorOf::Variant,
368 DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data))
374 | Node::PathSegment(_)
383 | Node::Visibility(_)
385 | Node::Crate => return None,
386 Node::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
387 Node::GenericParam(param) => match param.kind {
388 GenericParamKind::Lifetime { .. } => return None,
389 GenericParamKind::Type { .. } => DefKind::TyParam,
390 GenericParamKind::Const { .. } => DefKind::ConstParam,
395 fn find_entry(&self, id: HirId) -> Option<Entry<'hir>> {
396 self.lookup(id).cloned()
399 pub fn item(&self, id: HirId) -> &'hir Item<'hir> {
402 // N.B., intentionally bypass `self.forest.krate()` so that we
403 // do not trigger a read of the whole krate here
404 self.forest.krate.item(id)
407 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
408 self.read(id.hir_id);
410 // N.B., intentionally bypass `self.forest.krate()` so that we
411 // do not trigger a read of the whole krate here
412 self.forest.krate.trait_item(id)
415 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
416 self.read(id.hir_id);
418 // N.B., intentionally bypass `self.forest.krate()` so that we
419 // do not trigger a read of the whole krate here
420 self.forest.krate.impl_item(id)
423 pub fn body(&self, id: BodyId) -> &'hir Body<'hir> {
424 self.read(id.hir_id);
426 // N.B., intentionally bypass `self.forest.krate()` so that we
427 // do not trigger a read of the whole krate here
428 self.forest.krate.body(id)
431 pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnDecl<'hir>> {
432 if let Some(entry) = self.find_entry(hir_id) {
435 bug!("no entry for hir_id `{}`", hir_id)
439 pub fn fn_sig_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnSig<'hir>> {
440 if let Some(entry) = self.find_entry(hir_id) {
443 bug!("no entry for hir_id `{}`", hir_id)
447 /// Returns the `HirId` that corresponds to the definition of
448 /// which this is the body of, i.e., a `fn`, `const` or `static`
449 /// item (possibly associated), a closure, or a `hir::AnonConst`.
450 pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> HirId {
451 let parent = self.get_parent_node(hir_id);
452 assert!(self.lookup(parent).map_or(false, |e| e.is_body_owner(hir_id)));
456 pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
457 self.local_def_id(self.body_owner(id))
460 /// Given a `HirId`, returns the `BodyId` associated with it,
461 /// if the node is a body owner, otherwise returns `None`.
462 pub fn maybe_body_owned_by(&self, hir_id: HirId) -> Option<BodyId> {
463 if let Some(entry) = self.find_entry(hir_id) {
464 if self.dep_graph.is_fully_enabled() {
465 let hir_id_owner = hir_id.owner;
466 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
467 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
470 entry.associated_body()
472 bug!("no entry for id `{}`", hir_id)
476 /// Given a body owner's id, returns the `BodyId` associated with it.
477 pub fn body_owned_by(&self, id: HirId) -> BodyId {
478 self.maybe_body_owned_by(id).unwrap_or_else(|| {
481 "body_owned_by: {} has no associated body",
482 self.node_to_string(id)
487 pub fn body_owner_kind(&self, id: HirId) -> BodyOwnerKind {
489 Node::Item(&Item { kind: ItemKind::Const(..), .. })
490 | Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. })
491 | Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. })
492 | Node::AnonConst(_) => BodyOwnerKind::Const,
494 | Node::Item(&Item { kind: ItemKind::Fn(..), .. })
495 | Node::TraitItem(&TraitItem { kind: TraitItemKind::Method(..), .. })
496 | Node::ImplItem(&ImplItem { kind: ImplItemKind::Method(..), .. }) => BodyOwnerKind::Fn,
497 Node::Item(&Item { kind: ItemKind::Static(_, m, _), .. }) => BodyOwnerKind::Static(m),
498 Node::Expr(&Expr { kind: ExprKind::Closure(..), .. }) => BodyOwnerKind::Closure,
499 node => bug!("{:#?} is not a body node", node),
503 pub fn ty_param_owner(&self, id: HirId) -> HirId {
505 Node::Item(&Item { kind: ItemKind::Trait(..), .. })
506 | Node::Item(&Item { kind: ItemKind::TraitAlias(..), .. }) => id,
507 Node::GenericParam(_) => self.get_parent_node(id),
508 _ => bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id)),
512 pub fn ty_param_name(&self, id: HirId) -> Name {
514 Node::Item(&Item { kind: ItemKind::Trait(..), .. })
515 | Node::Item(&Item { kind: ItemKind::TraitAlias(..), .. }) => kw::SelfUpper,
516 Node::GenericParam(param) => param.name.ident().name,
517 _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
521 pub fn trait_impls(&self, trait_did: DefId) -> &'hir [HirId] {
522 self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
524 // N.B., intentionally bypass `self.forest.krate()` so that we
525 // do not trigger a read of the whole krate here
526 self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
529 /// Gets the attributes on the crate. This is preferable to
530 /// invoking `krate.attrs` because it registers a tighter
531 /// dep-graph access.
532 pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
533 let def_path_hash = self.definitions.def_path_hash(CRATE_DEF_INDEX);
535 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::Hir));
536 &self.forest.krate.attrs
539 pub fn get_module(&self, module: DefId) -> (&'hir Mod<'hir>, Span, HirId) {
540 let hir_id = self.as_local_hir_id(module).unwrap();
542 match self.find_entry(hir_id).unwrap().node {
543 Node::Item(&Item { span, kind: ItemKind::Mod(ref m), .. }) => (m, span, hir_id),
544 Node::Crate => (&self.forest.krate.module, self.forest.krate.span, hir_id),
545 node => panic!("not a module: {:?}", node),
549 pub fn visit_item_likes_in_module<V>(&self, module: DefId, visitor: &mut V)
551 V: ItemLikeVisitor<'hir>,
553 let hir_id = self.as_local_hir_id(module).unwrap();
555 // Read the module so we'll be re-executed if new items
556 // appear immediately under in the module. If some new item appears
557 // in some nested item in the module, we'll be re-executed due to reads
558 // in the expect_* calls the loops below
561 let module = &self.forest.krate.modules[&hir_id];
563 for id in &module.items {
564 visitor.visit_item(self.expect_item(*id));
567 for id in &module.trait_items {
568 visitor.visit_trait_item(self.expect_trait_item(id.hir_id));
571 for id in &module.impl_items {
572 visitor.visit_impl_item(self.expect_impl_item(id.hir_id));
576 /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found.
577 pub fn get(&self, id: HirId) -> Node<'hir> {
578 // read recorded by `find`
579 self.find(id).unwrap_or_else(|| bug!("couldn't find hir id {} in the HIR map", id))
582 pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
583 self.as_local_hir_id(id).map(|id| self.get(id)) // read recorded by `get`
586 pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics<'hir>> {
587 self.get_if_local(id).and_then(|node| match node {
588 Node::ImplItem(ref impl_item) => Some(&impl_item.generics),
589 Node::TraitItem(ref trait_item) => Some(&trait_item.generics),
590 Node::Item(ref item) => match item.kind {
591 ItemKind::Fn(_, ref generics, _)
592 | ItemKind::TyAlias(_, ref generics)
593 | ItemKind::Enum(_, ref generics)
594 | ItemKind::Struct(_, ref generics)
595 | ItemKind::Union(_, ref generics)
596 | ItemKind::Trait(_, _, ref generics, ..)
597 | ItemKind::TraitAlias(ref generics, _)
598 | ItemKind::Impl { ref generics, .. } => Some(generics),
605 /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
606 pub fn find(&self, hir_id: HirId) -> Option<Node<'hir>> {
609 .and_then(|entry| if let Node::Crate = entry.node { None } else { Some(entry.node) });
610 if result.is_some() {
616 /// Similar to `get_parent`; returns the parent HIR Id, or just `hir_id` if there
617 /// is no parent. Note that the parent may be `CRATE_HIR_ID`, which is not itself
618 /// present in the map, so passing the return value of `get_parent_node` to
619 /// `get` may in fact panic.
620 /// This function returns the immediate parent in the HIR, whereas `get_parent`
621 /// returns the enclosing item. Note that this might not be the actual parent
622 /// node in the HIR -- some kinds of nodes are not in the map and these will
623 /// never appear as the parent node. Thus, you can always walk the parent nodes
624 /// from a node to the root of the HIR (unless you get back the same ID here,
625 /// which can happen if the ID is not in the map itself or is just weird).
626 pub fn get_parent_node(&self, hir_id: HirId) -> HirId {
627 if self.dep_graph.is_fully_enabled() {
628 let hir_id_owner = hir_id.owner;
629 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
630 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
633 self.find_entry(hir_id).and_then(|x| x.parent_node()).unwrap_or(hir_id)
636 /// Checks if the node is an argument. An argument is a local variable whose
637 /// immediate parent is an item or a closure.
638 pub fn is_argument(&self, id: HirId) -> bool {
639 match self.find(id) {
640 Some(Node::Binding(_)) => (),
643 match self.find(self.get_parent_node(id)) {
644 Some(Node::Item(_)) | Some(Node::TraitItem(_)) | Some(Node::ImplItem(_)) => true,
645 Some(Node::Expr(e)) => match e.kind {
646 ExprKind::Closure(..) => true,
653 /// Whether the expression pointed at by `hir_id` belongs to a `const` evaluation context.
654 /// Used exclusively for diagnostics, to avoid suggestion function calls.
655 pub fn is_const_context(&self, hir_id: HirId) -> bool {
656 let parent_id = self.get_parent_item(hir_id);
657 match self.get(parent_id) {
658 Node::Item(&Item { kind: ItemKind::Const(..), .. })
659 | Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. })
660 | Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. })
662 | Node::Item(&Item { kind: ItemKind::Static(..), .. }) => true,
663 Node::Item(&Item { kind: ItemKind::Fn(ref sig, ..), .. }) => {
664 sig.header.constness == Constness::Const
670 /// Wether `hir_id` corresponds to a `mod` or a crate.
671 pub fn is_hir_id_module(&self, hir_id: HirId) -> bool {
672 match self.lookup(hir_id) {
673 Some(Entry { node: Node::Item(Item { kind: ItemKind::Mod(_), .. }), .. })
674 | Some(Entry { node: Node::Crate, .. }) => true,
679 /// Retrieves the `HirId` for `id`'s enclosing method, unless there's a
680 /// `while` or `loop` before reaching it, as block tail returns are not
681 /// available in them.
684 /// fn foo(x: usize) -> bool {
686 /// true // If `get_return_block` gets passed the `id` corresponding
687 /// } else { // to this, it will return `foo`'s `HirId`.
694 /// fn foo(x: usize) -> bool {
696 /// true // If `get_return_block` gets passed the `id` corresponding
697 /// } // to this, it will return `None`.
701 pub fn get_return_block(&self, id: HirId) -> Option<HirId> {
702 let mut iter = ParentHirIterator::new(id, &self).peekable();
703 let mut ignore_tail = false;
704 if let Some(entry) = self.find_entry(id) {
705 if let Node::Expr(Expr { kind: ExprKind::Ret(_), .. }) = entry.node {
706 // When dealing with `return` statements, we don't care about climbing only tail
711 while let Some((hir_id, node)) = iter.next() {
712 if let (Some((_, next_node)), false) = (iter.peek(), ignore_tail) {
714 Node::Block(Block { expr: None, .. }) => return None,
715 Node::Block(Block { expr: Some(expr), .. }) => {
716 if hir_id != expr.hir_id {
717 // The current node is not the tail expression of its parent.
726 | Node::ForeignItem(_)
728 | Node::Expr(Expr { kind: ExprKind::Closure(..), .. })
729 | Node::ImplItem(_) => return Some(hir_id),
730 Node::Expr(ref expr) => {
732 // Ignore `return`s on the first iteration
733 ExprKind::Loop(..) | ExprKind::Ret(..) => return None,
737 Node::Local(_) => return None,
744 /// Retrieves the `HirId` for `id`'s parent item, or `id` itself if no
745 /// parent item is in this map. The "parent item" is the closest parent node
746 /// in the HIR which is recorded by the map and is an item, either an item
747 /// in a module, trait, or impl.
748 pub fn get_parent_item(&self, hir_id: HirId) -> HirId {
749 for (hir_id, node) in ParentHirIterator::new(hir_id, &self) {
753 | Node::ForeignItem(_)
755 | Node::ImplItem(_) => return hir_id,
762 /// Returns the `DefId` of `id`'s nearest module parent, or `id` itself if no
763 /// module parent is in this map.
764 pub fn get_module_parent(&self, id: HirId) -> DefId {
765 self.local_def_id(self.get_module_parent_node(id))
768 /// Returns the `HirId` of `id`'s nearest module parent, or `id` itself if no
769 /// module parent is in this map.
770 pub fn get_module_parent_node(&self, hir_id: HirId) -> HirId {
771 for (hir_id, node) in ParentHirIterator::new(hir_id, &self) {
772 if let Node::Item(&Item { kind: ItemKind::Mod(_), .. }) = node {
779 /// When on a match arm tail expression or on a match arm, give back the enclosing `match`
782 /// Used by error reporting when there's a type error in a match arm caused by the `match`
783 /// expression needing to be unit.
784 pub fn get_match_if_cause(&self, hir_id: HirId) -> Option<&'hir Expr<'hir>> {
785 for (_, node) in ParentHirIterator::new(hir_id, &self) {
787 Node::Item(_) | Node::ForeignItem(_) | Node::TraitItem(_) | Node::ImplItem(_) => {
790 Node::Expr(expr) => match expr.kind {
791 ExprKind::Match(_, _, _) => return Some(expr),
794 Node::Stmt(stmt) => match stmt.kind {
795 StmtKind::Local(_) => break,
804 /// Returns the nearest enclosing scope. A scope is roughly an item or block.
805 pub fn get_enclosing_scope(&self, hir_id: HirId) -> Option<HirId> {
806 for (hir_id, node) in ParentHirIterator::new(hir_id, &self) {
808 Node::Item(i) => match i.kind {
812 | ItemKind::Struct(..)
813 | ItemKind::Union(..)
814 | ItemKind::Trait(..)
815 | ItemKind::Impl { .. } => true,
818 Node::ForeignItem(fi) => match fi.kind {
819 ForeignItemKind::Fn(..) => true,
822 Node::TraitItem(ti) => match ti.kind {
823 TraitItemKind::Method(..) => true,
826 Node::ImplItem(ii) => match ii.kind {
827 ImplItemKind::Method(..) => true,
830 Node::Block(_) => true,
839 /// Returns the defining scope for an opaque type definition.
840 pub fn get_defining_scope(&self, id: HirId) -> HirId {
843 scope = self.get_enclosing_scope(scope).unwrap_or(CRATE_HIR_ID);
844 if scope == CRATE_HIR_ID {
847 match self.get(scope) {
848 Node::Item(i) => match i.kind {
849 ItemKind::OpaqueTy(OpaqueTy { impl_trait_fn: None, .. }) => {}
859 pub fn get_parent_did(&self, id: HirId) -> DefId {
860 self.local_def_id(self.get_parent_item(id))
863 pub fn get_foreign_abi(&self, hir_id: HirId) -> Abi {
864 let parent = self.get_parent_item(hir_id);
865 if let Some(entry) = self.find_entry(parent) {
867 node: Node::Item(Item { kind: ItemKind::ForeignMod(ref nm), .. }), ..
870 self.read(hir_id); // reveals some of the content of a node
874 bug!("expected foreign mod or inlined parent, found {}", self.node_to_string(parent))
877 pub fn expect_item(&self, id: HirId) -> &'hir Item<'hir> {
878 match self.find(id) {
879 // read recorded by `find`
880 Some(Node::Item(item)) => item,
881 _ => bug!("expected item, found {}", self.node_to_string(id)),
885 pub fn expect_impl_item(&self, id: HirId) -> &'hir ImplItem<'hir> {
886 match self.find(id) {
887 Some(Node::ImplItem(item)) => item,
888 _ => bug!("expected impl item, found {}", self.node_to_string(id)),
892 pub fn expect_trait_item(&self, id: HirId) -> &'hir TraitItem<'hir> {
893 match self.find(id) {
894 Some(Node::TraitItem(item)) => item,
895 _ => bug!("expected trait item, found {}", self.node_to_string(id)),
899 pub fn expect_variant_data(&self, id: HirId) -> &'hir VariantData<'hir> {
900 match self.find(id) {
901 Some(Node::Item(i)) => match i.kind {
902 ItemKind::Struct(ref struct_def, _) | ItemKind::Union(ref struct_def, _) => {
905 _ => bug!("struct ID bound to non-struct {}", self.node_to_string(id)),
907 Some(Node::Variant(variant)) => &variant.data,
908 Some(Node::Ctor(data)) => data,
909 _ => bug!("expected struct or variant, found {}", self.node_to_string(id)),
913 pub fn expect_variant(&self, id: HirId) -> &'hir Variant<'hir> {
914 match self.find(id) {
915 Some(Node::Variant(variant)) => variant,
916 _ => bug!("expected variant, found {}", self.node_to_string(id)),
920 pub fn expect_foreign_item(&self, id: HirId) -> &'hir ForeignItem<'hir> {
921 match self.find(id) {
922 Some(Node::ForeignItem(item)) => item,
923 _ => bug!("expected foreign item, found {}", self.node_to_string(id)),
927 pub fn expect_expr(&self, id: HirId) -> &'hir Expr<'hir> {
928 match self.find(id) {
929 // read recorded by find
930 Some(Node::Expr(expr)) => expr,
931 _ => bug!("expected expr, found {}", self.node_to_string(id)),
935 pub fn opt_name(&self, id: HirId) -> Option<Name> {
936 Some(match self.get(id) {
937 Node::Item(i) => i.ident.name,
938 Node::ForeignItem(fi) => fi.ident.name,
939 Node::ImplItem(ii) => ii.ident.name,
940 Node::TraitItem(ti) => ti.ident.name,
941 Node::Variant(v) => v.ident.name,
942 Node::Field(f) => f.ident.name,
943 Node::Lifetime(lt) => lt.name.ident().name,
944 Node::GenericParam(param) => param.name.ident().name,
945 Node::Binding(&Pat { kind: PatKind::Binding(_, _, l, _), .. }) => l.name,
946 Node::Ctor(..) => self.name(self.get_parent_item(id)),
951 pub fn name(&self, id: HirId) -> Name {
952 match self.opt_name(id) {
954 None => bug!("no name for {}", self.node_to_string(id)),
958 /// Given a node ID, gets a list of attributes associated with the AST
959 /// corresponding to the node-ID.
960 pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] {
961 self.read(id); // reveals attributes on the node
962 let attrs = match self.find_entry(id).map(|entry| entry.node) {
963 Some(Node::Param(a)) => Some(&a.attrs[..]),
964 Some(Node::Local(l)) => Some(&l.attrs[..]),
965 Some(Node::Item(i)) => Some(&i.attrs[..]),
966 Some(Node::ForeignItem(fi)) => Some(&fi.attrs[..]),
967 Some(Node::TraitItem(ref ti)) => Some(&ti.attrs[..]),
968 Some(Node::ImplItem(ref ii)) => Some(&ii.attrs[..]),
969 Some(Node::Variant(ref v)) => Some(&v.attrs[..]),
970 Some(Node::Field(ref f)) => Some(&f.attrs[..]),
971 Some(Node::Expr(ref e)) => Some(&*e.attrs),
972 Some(Node::Stmt(ref s)) => Some(s.kind.attrs()),
973 Some(Node::Arm(ref a)) => Some(&*a.attrs),
974 Some(Node::GenericParam(param)) => Some(¶m.attrs[..]),
975 // Unit/tuple structs/variants take the attributes straight from
976 // the struct/variant definition.
977 Some(Node::Ctor(..)) => return self.attrs(self.get_parent_item(id)),
978 Some(Node::Crate) => Some(&self.forest.krate.attrs[..]),
984 /// Returns an iterator that yields all the hir ids in the map.
985 fn all_ids<'a>(&'a self) -> impl Iterator<Item = HirId> + 'a {
986 // This code is a bit awkward because the map is implemented as 2 levels of arrays,
987 // see the comment on `HirEntryMap`.
988 // Iterate over all the indices and return a reference to
989 // local maps and their index given that they exist.
990 self.map.iter_enumerated().flat_map(move |(owner, local_map)| {
991 // Iterate over each valid entry in the local map.
992 local_map.iter_enumerated().filter_map(move |(i, entry)| {
994 // Reconstruct the `HirId` based on the 3 indices we used to find it.
995 HirId { owner, local_id: i }
1001 /// Returns an iterator that yields the node id's with paths that
1002 /// match `parts`. (Requires `parts` is non-empty.)
1004 /// For example, if given `parts` equal to `["bar", "quux"]`, then
1005 /// the iterator will produce node id's for items with paths
1006 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
1007 /// any other such items it can find in the map.
1008 pub fn nodes_matching_suffix<'a>(
1010 parts: &'a [String],
1011 ) -> impl Iterator<Item = NodeId> + 'a {
1012 let nodes = NodesMatchingSuffix {
1014 item_name: parts.last().unwrap(),
1015 in_which: &parts[..parts.len() - 1],
1019 .filter(move |hir| nodes.matches_suffix(*hir))
1020 .map(move |hir| self.hir_to_node_id(hir))
1023 pub fn span(&self, hir_id: HirId) -> Span {
1024 self.read(hir_id); // reveals span from node
1025 match self.find_entry(hir_id).map(|entry| entry.node) {
1026 Some(Node::Param(param)) => param.span,
1027 Some(Node::Item(item)) => item.span,
1028 Some(Node::ForeignItem(foreign_item)) => foreign_item.span,
1029 Some(Node::TraitItem(trait_method)) => trait_method.span,
1030 Some(Node::ImplItem(impl_item)) => impl_item.span,
1031 Some(Node::Variant(variant)) => variant.span,
1032 Some(Node::Field(field)) => field.span,
1033 Some(Node::AnonConst(constant)) => self.body(constant.body).value.span,
1034 Some(Node::Expr(expr)) => expr.span,
1035 Some(Node::Stmt(stmt)) => stmt.span,
1036 Some(Node::PathSegment(seg)) => seg.ident.span,
1037 Some(Node::Ty(ty)) => ty.span,
1038 Some(Node::TraitRef(tr)) => tr.path.span,
1039 Some(Node::Binding(pat)) => pat.span,
1040 Some(Node::Pat(pat)) => pat.span,
1041 Some(Node::Arm(arm)) => arm.span,
1042 Some(Node::Block(block)) => block.span,
1043 Some(Node::Ctor(..)) => match self.find(self.get_parent_node(hir_id)) {
1044 Some(Node::Item(item)) => item.span,
1045 Some(Node::Variant(variant)) => variant.span,
1046 _ => unreachable!(),
1048 Some(Node::Lifetime(lifetime)) => lifetime.span,
1049 Some(Node::GenericParam(param)) => param.span,
1050 Some(Node::Visibility(&Spanned {
1051 node: VisibilityKind::Restricted { ref path, .. },
1054 Some(Node::Visibility(v)) => bug!("unexpected Visibility {:?}", v),
1055 Some(Node::Local(local)) => local.span,
1056 Some(Node::MacroDef(macro_def)) => macro_def.span,
1057 Some(Node::Crate) => self.forest.krate.span,
1058 None => bug!("hir::map::Map::span: id not in map: {:?}", hir_id),
1062 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
1063 self.as_local_hir_id(id).map(|id| self.span(id))
1066 pub fn res_span(&self, res: Res) -> Option<Span> {
1069 Res::Local(id) => Some(self.span(id)),
1070 res => self.span_if_local(res.opt_def_id()?),
1074 pub fn node_to_string(&self, id: HirId) -> String {
1075 hir_id_to_string(self, id, true)
1078 pub fn hir_to_user_string(&self, id: HirId) -> String {
1079 hir_id_to_string(self, id, false)
1082 pub fn hir_to_pretty_string(&self, id: HirId) -> String {
1083 print::to_string(self, |s| s.print_node(self.get(id)))
1087 impl<'hir> intravisit::Map<'hir> for Map<'hir> {
1088 fn body(&self, id: BodyId) -> &'hir Body<'hir> {
1092 fn item(&self, id: HirId) -> &'hir Item<'hir> {
1096 fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
1100 fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
1105 pub struct NodesMatchingSuffix<'a> {
1107 item_name: &'a String,
1108 in_which: &'a [String],
1111 impl<'a> NodesMatchingSuffix<'a> {
1112 /// Returns `true` only if some suffix of the module path for parent
1113 /// matches `self.in_which`.
1115 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
1116 /// returns true if parent's path ends with the suffix
1117 /// `x_0::x_1::...::x_k`.
1118 fn suffix_matches(&self, parent: HirId) -> bool {
1119 let mut cursor = parent;
1120 for part in self.in_which.iter().rev() {
1121 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
1122 None => return false,
1123 Some((node_id, name)) => (node_id, name),
1125 if mod_name.as_str() != *part {
1128 cursor = self.map.get_parent_item(mod_id);
1132 // Finds the first mod in parent chain for `id`, along with
1135 // If `id` itself is a mod named `m` with parent `p`, then
1136 // returns `Some(id, m, p)`. If `id` has no mod in its parent
1137 // chain, then returns `None`.
1138 fn find_first_mod_parent(map: &Map<'_>, mut id: HirId) -> Option<(HirId, Name)> {
1140 if let Node::Item(item) = map.find(id)? {
1141 if item_is_mod(&item) {
1142 return Some((id, item.ident.name));
1145 let parent = map.get_parent_item(id);
1152 fn item_is_mod(item: &Item<'_>) -> bool {
1154 ItemKind::Mod(_) => true,
1161 // We are looking at some node `n` with a given name and parent
1162 // id; do their names match what I am seeking?
1163 fn matches_names(&self, parent_of_n: HirId, name: Name) -> bool {
1164 name.as_str() == *self.item_name && self.suffix_matches(parent_of_n)
1167 fn matches_suffix(&self, hir: HirId) -> bool {
1168 let name = match self.map.find_entry(hir).map(|entry| entry.node) {
1169 Some(Node::Item(n)) => n.name(),
1170 Some(Node::ForeignItem(n)) => n.name(),
1171 Some(Node::TraitItem(n)) => n.name(),
1172 Some(Node::ImplItem(n)) => n.name(),
1173 Some(Node::Variant(n)) => n.name(),
1174 Some(Node::Field(n)) => n.name(),
1177 self.matches_names(self.map.get_parent_item(hir), name)
1182 fn name(&self) -> Name;
1185 impl<T: Named> Named for Spanned<T> {
1186 fn name(&self) -> Name {
1191 impl Named for Item<'_> {
1192 fn name(&self) -> Name {
1196 impl Named for ForeignItem<'_> {
1197 fn name(&self) -> Name {
1201 impl Named for Variant<'_> {
1202 fn name(&self) -> Name {
1206 impl Named for StructField<'_> {
1207 fn name(&self) -> Name {
1211 impl Named for TraitItem<'_> {
1212 fn name(&self) -> Name {
1216 impl Named for ImplItem<'_> {
1217 fn name(&self) -> Name {
1222 pub fn map_crate<'hir>(
1223 sess: &rustc_session::Session,
1224 cstore: &CrateStoreDyn,
1225 forest: &'hir Forest<'hir>,
1226 definitions: Definitions,
1228 let _prof_timer = sess.prof.generic_activity("build_hir_map");
1230 // Build the reverse mapping of `node_to_hir_id`.
1231 let hir_to_node_id = definitions
1234 .map(|(node_id, &hir_id)| (hir_id, node_id))
1237 let (map, crate_hash) = {
1238 let hcx = crate::ich::StableHashingContext::new(sess, &forest.krate, &definitions, cstore);
1240 let mut collector = NodeCollector::root(
1248 intravisit::walk_crate(&mut collector, &forest.krate);
1250 let crate_disambiguator = sess.local_crate_disambiguator();
1251 let cmdline_args = sess.opts.dep_tracking_hash();
1252 collector.finalize_and_compute_crate_hash(crate_disambiguator, cstore, cmdline_args)
1257 dep_graph: forest.dep_graph.clone(),
1264 sess.time("validate_HIR_map", || {
1265 hir_id_validator::check_crate(&map);
1271 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1272 /// except it avoids creating a dependency on the whole crate.
1273 impl<'hir> print::PpAnn for Map<'hir> {
1274 fn nested(&self, state: &mut print::State<'_>, nested: print::Nested) {
1276 Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1277 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1278 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1279 Nested::Body(id) => state.print_expr(&self.body(id).value),
1280 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
1285 fn hir_id_to_string(map: &Map<'_>, id: HirId, include_id: bool) -> String {
1286 let id_str = format!(" (hir_id={})", id);
1287 let id_str = if include_id { &id_str[..] } else { "" };
1290 // This functionality is used for debugging, try to use `TyCtxt` to get
1291 // the user-friendly path, otherwise fall back to stringifying `DefPath`.
1292 crate::ty::tls::with_opt(|tcx| {
1293 if let Some(tcx) = tcx {
1294 let def_id = map.local_def_id(id);
1295 tcx.def_path_str(def_id)
1296 } else if let Some(path) = map.def_path_from_hir_id(id) {
1299 .map(|elem| elem.data.to_string())
1300 .collect::<Vec<_>>()
1303 String::from("<missing path>")
1308 match map.find(id) {
1309 Some(Node::Item(item)) => {
1310 let item_str = match item.kind {
1311 ItemKind::ExternCrate(..) => "extern crate",
1312 ItemKind::Use(..) => "use",
1313 ItemKind::Static(..) => "static",
1314 ItemKind::Const(..) => "const",
1315 ItemKind::Fn(..) => "fn",
1316 ItemKind::Mod(..) => "mod",
1317 ItemKind::ForeignMod(..) => "foreign mod",
1318 ItemKind::GlobalAsm(..) => "global asm",
1319 ItemKind::TyAlias(..) => "ty",
1320 ItemKind::OpaqueTy(..) => "opaque type",
1321 ItemKind::Enum(..) => "enum",
1322 ItemKind::Struct(..) => "struct",
1323 ItemKind::Union(..) => "union",
1324 ItemKind::Trait(..) => "trait",
1325 ItemKind::TraitAlias(..) => "trait alias",
1326 ItemKind::Impl { .. } => "impl",
1328 format!("{} {}{}", item_str, path_str(), id_str)
1330 Some(Node::ForeignItem(_)) => format!("foreign item {}{}", path_str(), id_str),
1331 Some(Node::ImplItem(ii)) => match ii.kind {
1332 ImplItemKind::Const(..) => {
1333 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1335 ImplItemKind::Method(..) => format!("method {} in {}{}", ii.ident, path_str(), id_str),
1336 ImplItemKind::TyAlias(_) => {
1337 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1339 ImplItemKind::OpaqueTy(_) => {
1340 format!("assoc opaque type {} in {}{}", ii.ident, path_str(), id_str)
1343 Some(Node::TraitItem(ti)) => {
1344 let kind = match ti.kind {
1345 TraitItemKind::Const(..) => "assoc constant",
1346 TraitItemKind::Method(..) => "trait method",
1347 TraitItemKind::Type(..) => "assoc type",
1350 format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1352 Some(Node::Variant(ref variant)) => {
1353 format!("variant {} in {}{}", variant.ident, path_str(), id_str)
1355 Some(Node::Field(ref field)) => {
1356 format!("field {} in {}{}", field.ident, path_str(), id_str)
1358 Some(Node::AnonConst(_)) => format!("const {}{}", map.hir_to_pretty_string(id), id_str),
1359 Some(Node::Expr(_)) => format!("expr {}{}", map.hir_to_pretty_string(id), id_str),
1360 Some(Node::Stmt(_)) => format!("stmt {}{}", map.hir_to_pretty_string(id), id_str),
1361 Some(Node::PathSegment(_)) => {
1362 format!("path segment {}{}", map.hir_to_pretty_string(id), id_str)
1364 Some(Node::Ty(_)) => format!("type {}{}", map.hir_to_pretty_string(id), id_str),
1365 Some(Node::TraitRef(_)) => format!("trait_ref {}{}", map.hir_to_pretty_string(id), id_str),
1366 Some(Node::Binding(_)) => format!("local {}{}", map.hir_to_pretty_string(id), id_str),
1367 Some(Node::Pat(_)) => format!("pat {}{}", map.hir_to_pretty_string(id), id_str),
1368 Some(Node::Param(_)) => format!("param {}{}", map.hir_to_pretty_string(id), id_str),
1369 Some(Node::Arm(_)) => format!("arm {}{}", map.hir_to_pretty_string(id), id_str),
1370 Some(Node::Block(_)) => format!("block {}{}", map.hir_to_pretty_string(id), id_str),
1371 Some(Node::Local(_)) => format!("local {}{}", map.hir_to_pretty_string(id), id_str),
1372 Some(Node::Ctor(..)) => format!("ctor {}{}", path_str(), id_str),
1373 Some(Node::Lifetime(_)) => format!("lifetime {}{}", map.hir_to_pretty_string(id), id_str),
1374 Some(Node::GenericParam(ref param)) => format!("generic_param {:?}{}", param, id_str),
1375 Some(Node::Visibility(ref vis)) => format!("visibility {:?}{}", vis, id_str),
1376 Some(Node::MacroDef(_)) => format!("macro {}{}", path_str(), id_str),
1377 Some(Node::Crate) => String::from("root_crate"),
1378 None => format!("unknown node{}", id_str),
1382 pub fn provide(providers: &mut Providers<'_>) {
1383 providers.def_kind = |tcx, def_id| {
1384 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
1385 tcx.hir().def_kind(hir_id)
1387 bug!("calling local def_kind query provider for upstream DefId: {:?}", def_id);