1 use self::collector::NodeCollector;
2 pub use self::def_collector::DefCollector;
3 pub use self::definitions::{
4 Definitions, DefKey, DefPath, DefPathData, DisambiguatedDefPathData, DefPathHash
7 use crate::dep_graph::{DepGraph, DepNode, DepKind, DepNodeIndex};
9 use crate::hir::DefKind;
10 use crate::hir::def_id::{CRATE_DEF_INDEX, DefId, LocalDefId};
11 use crate::hir::itemlikevisit::ItemLikeVisitor;
12 use crate::hir::print::Nested;
13 use crate::middle::cstore::CrateStoreDyn;
14 use crate::ty::query::Providers;
15 use crate::util::nodemap::FxHashMap;
16 use crate::util::common::time;
18 use rustc_target::spec::abi::Abi;
19 use rustc_data_structures::svh::Svh;
20 use rustc_index::vec::IndexVec;
21 use syntax::ast::{self, Name, NodeId};
22 use syntax::source_map::Spanned;
23 use syntax_pos::hygiene::MacroKind;
24 use syntax_pos::{Span, DUMMY_SP};
32 /// Represents an entry and its parent `HirId`.
33 #[derive(Copy, Clone, Debug)]
34 pub struct Entry<'hir> {
36 dep_node: DepNodeIndex,
40 impl<'hir> Entry<'hir> {
41 fn parent_node(self) -> Option<HirId> {
43 Node::Crate | Node::MacroDef(_) => None,
44 _ => Some(self.parent),
48 fn fn_decl(&self) -> Option<&'hir FnDecl> {
50 Node::Item(ref item) => {
52 ItemKind::Fn(ref sig, _, _) => Some(&sig.decl),
57 Node::TraitItem(ref item) => {
59 TraitItemKind::Method(ref sig, _) => Some(&sig.decl),
64 Node::ImplItem(ref item) => {
66 ImplItemKind::Method(ref sig, _) => Some(&sig.decl),
71 Node::Expr(ref expr) => {
73 ExprKind::Closure(_, ref fn_decl, ..) => Some(fn_decl),
82 fn associated_body(self) -> Option<BodyId> {
86 ItemKind::Const(_, body) |
87 ItemKind::Static(.., body) |
88 ItemKind::Fn(.., body) => Some(body),
93 Node::TraitItem(item) => {
95 TraitItemKind::Const(_, Some(body)) |
96 TraitItemKind::Method(_, TraitMethod::Provided(body)) => Some(body),
101 Node::ImplItem(item) => {
103 ImplItemKind::Const(_, body) |
104 ImplItemKind::Method(_, body) => Some(body),
109 Node::AnonConst(constant) => Some(constant.body),
111 Node::Expr(expr) => {
113 ExprKind::Closure(.., body, _, _) => Some(body),
122 fn is_body_owner(self, hir_id: HirId) -> bool {
123 match self.associated_body() {
124 Some(b) => b.hir_id == hir_id,
130 /// Stores a crate and any number of inlined items from other crates.
133 pub dep_graph: DepGraph,
137 pub fn new(krate: Crate, dep_graph: &DepGraph) -> Forest {
140 dep_graph: dep_graph.clone(),
144 pub fn krate(&self) -> &Crate {
145 self.dep_graph.read(DepNode::new_no_params(DepKind::Krate));
149 /// This is used internally in the dependency tracking system.
150 /// Use the `krate` method to ensure your dependency on the
151 /// crate is tracked.
152 pub fn untracked_krate(&self) -> &Crate {
157 /// This type is effectively a `HashMap<HirId, Entry<'hir>>`,
158 /// but it is implemented as 2 layers of arrays.
159 /// - first we have `A = IndexVec<DefIndex, B>` mapping `DefIndex`s to an inner value
160 /// - which is `B = IndexVec<ItemLocalId, Option<Entry<'hir>>` which gives you the `Entry`.
161 pub(super) type HirEntryMap<'hir> = IndexVec<DefIndex, IndexVec<ItemLocalId, Option<Entry<'hir>>>>;
163 /// Represents a mapping from `NodeId`s to AST elements and their parent `NodeId`s.
165 pub struct Map<'hir> {
166 /// The backing storage for all the AST nodes.
167 pub forest: &'hir Forest,
169 /// Same as the dep_graph in forest, just available with one fewer
170 /// deref. This is a gratuitous micro-optimization.
171 pub dep_graph: DepGraph,
173 /// The SVH of the local crate.
176 map: HirEntryMap<'hir>,
178 definitions: &'hir Definitions,
180 /// The reverse mapping of `node_to_hir_id`.
181 hir_to_node_id: FxHashMap<HirId, NodeId>,
184 struct ParentHirIterator<'map> {
186 map: &'map Map<'map>,
189 impl<'map> ParentHirIterator<'map> {
190 fn new(current_id: HirId, map: &'map Map<'map>) -> ParentHirIterator<'map> {
198 impl<'map> Iterator for ParentHirIterator<'map> {
199 type Item = (HirId, Node<'map>);
201 fn next(&mut self) -> Option<Self::Item> {
202 if self.current_id == CRATE_HIR_ID {
205 loop { // There are nodes that do not have entries, so we need to skip them.
206 let parent_id = self.map.get_parent_node(self.current_id);
208 if parent_id == self.current_id {
209 self.current_id = CRATE_HIR_ID;
213 self.current_id = parent_id;
214 if let Some(entry) = self.map.find_entry(parent_id) {
215 return Some((parent_id, entry.node));
217 // If this `HirId` doesn't have an `Entry`, skip it and look for its `parent_id`.
222 impl<'hir> Map<'hir> {
224 fn lookup(&self, id: HirId) -> Option<&Entry<'hir>> {
225 let local_map = self.map.get(id.owner)?;
226 local_map.get(id.local_id)?.as_ref()
229 /// Registers a read in the dependency graph of the AST node with
230 /// the given `id`. This needs to be called each time a public
231 /// function returns the HIR for a node -- in other words, when it
232 /// "reveals" the content of a node to the caller (who might not
233 /// otherwise have had access to those contents, and hence needs a
234 /// read recorded). If the function just returns a DefId or
235 /// HirId, no actual content was returned, so no read is needed.
236 pub fn read(&self, hir_id: HirId) {
237 if let Some(entry) = self.lookup(hir_id) {
238 self.dep_graph.read_index(entry.dep_node);
240 bug!("called `HirMap::read()` with invalid `HirId`: {:?}", hir_id)
245 pub fn definitions(&self) -> &'hir Definitions {
249 pub fn def_key(&self, def_id: DefId) -> DefKey {
250 assert!(def_id.is_local());
251 self.definitions.def_key(def_id.index)
254 pub fn def_path_from_hir_id(&self, id: HirId) -> Option<DefPath> {
255 self.opt_local_def_id(id).map(|def_id| {
256 self.def_path(def_id)
260 pub fn def_path(&self, def_id: DefId) -> DefPath {
261 assert!(def_id.is_local());
262 self.definitions.def_path(def_id.index)
266 pub fn local_def_id_from_node_id(&self, node: NodeId) -> DefId {
267 self.opt_local_def_id_from_node_id(node).unwrap_or_else(|| {
268 let hir_id = self.node_to_hir_id(node);
269 bug!("local_def_id_from_node_id: no entry for `{}`, which has a map of `{:?}`",
270 node, self.find_entry(hir_id))
275 pub fn local_def_id(&self, hir_id: HirId) -> DefId {
276 self.opt_local_def_id(hir_id).unwrap_or_else(|| {
277 bug!("local_def_id: no entry for `{:?}`, which has a map of `{:?}`",
278 hir_id, self.find_entry(hir_id))
283 pub fn opt_local_def_id(&self, hir_id: HirId) -> Option<DefId> {
284 let node_id = self.hir_to_node_id(hir_id);
285 self.definitions.opt_local_def_id(node_id)
289 pub fn opt_local_def_id_from_node_id(&self, node: NodeId) -> Option<DefId> {
290 self.definitions.opt_local_def_id(node)
294 pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
295 self.definitions.as_local_node_id(def_id)
299 pub fn as_local_hir_id(&self, def_id: DefId) -> Option<HirId> {
300 self.definitions.as_local_hir_id(def_id)
304 pub fn hir_to_node_id(&self, hir_id: HirId) -> NodeId {
305 self.hir_to_node_id[&hir_id]
309 pub fn node_to_hir_id(&self, node_id: NodeId) -> HirId {
310 self.definitions.node_to_hir_id(node_id)
314 pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> HirId {
315 self.definitions.def_index_to_hir_id(def_index)
319 pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
320 self.definitions.def_index_to_hir_id(def_id.to_def_id().index)
323 pub fn def_kind(&self, hir_id: HirId) -> Option<DefKind> {
324 let node = if let Some(node) = self.find(hir_id) {
331 Node::Item(item) => {
333 ItemKind::Static(..) => DefKind::Static,
334 ItemKind::Const(..) => DefKind::Const,
335 ItemKind::Fn(..) => DefKind::Fn,
336 ItemKind::Mod(..) => DefKind::Mod,
337 ItemKind::OpaqueTy(..) => DefKind::OpaqueTy,
338 ItemKind::TyAlias(..) => DefKind::TyAlias,
339 ItemKind::Enum(..) => DefKind::Enum,
340 ItemKind::Struct(..) => DefKind::Struct,
341 ItemKind::Union(..) => DefKind::Union,
342 ItemKind::Trait(..) => DefKind::Trait,
343 ItemKind::TraitAlias(..) => DefKind::TraitAlias,
344 ItemKind::ExternCrate(_) |
346 ItemKind::ForeignMod(..) |
347 ItemKind::GlobalAsm(..) |
348 ItemKind::Impl(..) => return None,
351 Node::ForeignItem(item) => {
353 ForeignItemKind::Fn(..) => DefKind::Fn,
354 ForeignItemKind::Static(..) => DefKind::Static,
355 ForeignItemKind::Type => DefKind::ForeignTy,
358 Node::TraitItem(item) => {
360 TraitItemKind::Const(..) => DefKind::AssocConst,
361 TraitItemKind::Method(..) => DefKind::Method,
362 TraitItemKind::Type(..) => DefKind::AssocTy,
365 Node::ImplItem(item) => {
367 ImplItemKind::Const(..) => DefKind::AssocConst,
368 ImplItemKind::Method(..) => DefKind::Method,
369 ImplItemKind::TyAlias(..) => DefKind::AssocTy,
370 ImplItemKind::OpaqueTy(..) => DefKind::AssocOpaqueTy,
373 Node::Variant(_) => DefKind::Variant,
374 Node::Ctor(variant_data) => {
375 // FIXME(eddyb) is this even possible, if we have a `Node::Ctor`?
376 if variant_data.ctor_hir_id().is_none() {
379 let ctor_of = match self.find(self.get_parent_node(hir_id)) {
380 Some(Node::Item(..)) => def::CtorOf::Struct,
381 Some(Node::Variant(..)) => def::CtorOf::Variant,
384 DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data))
390 Node::PathSegment(_) |
399 Node::Visibility(_) |
401 Node::Crate => return None,
402 Node::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
403 Node::GenericParam(param) => {
405 GenericParamKind::Lifetime { .. } => return None,
406 GenericParamKind::Type { .. } => DefKind::TyParam,
407 GenericParamKind::Const { .. } => DefKind::ConstParam,
413 fn find_entry(&self, id: HirId) -> Option<Entry<'hir>> {
414 self.lookup(id).cloned()
417 pub fn krate(&self) -> &'hir Crate {
421 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem {
422 self.read(id.hir_id);
424 // N.B., intentionally bypass `self.forest.krate()` so that we
425 // do not trigger a read of the whole krate here
426 self.forest.krate.trait_item(id)
429 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem {
430 self.read(id.hir_id);
432 // N.B., intentionally bypass `self.forest.krate()` so that we
433 // do not trigger a read of the whole krate here
434 self.forest.krate.impl_item(id)
437 pub fn body(&self, id: BodyId) -> &'hir Body {
438 self.read(id.hir_id);
440 // N.B., intentionally bypass `self.forest.krate()` so that we
441 // do not trigger a read of the whole krate here
442 self.forest.krate.body(id)
445 pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnDecl> {
446 if let Some(entry) = self.find_entry(hir_id) {
449 bug!("no entry for hir_id `{}`", hir_id)
453 /// Returns the `HirId` that corresponds to the definition of
454 /// which this is the body of, i.e., a `fn`, `const` or `static`
455 /// item (possibly associated), a closure, or a `hir::AnonConst`.
456 pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> HirId {
457 let parent = self.get_parent_node(hir_id);
458 assert!(self.lookup(parent).map_or(false, |e| e.is_body_owner(hir_id)));
462 pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
463 self.local_def_id(self.body_owner(id))
466 /// Given a `HirId`, returns the `BodyId` associated with it,
467 /// if the node is a body owner, otherwise returns `None`.
468 pub fn maybe_body_owned_by(&self, hir_id: HirId) -> Option<BodyId> {
469 if let Some(entry) = self.find_entry(hir_id) {
470 if self.dep_graph.is_fully_enabled() {
471 let hir_id_owner = hir_id.owner;
472 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
473 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
476 entry.associated_body()
478 bug!("no entry for id `{}`", hir_id)
482 /// Given a body owner's id, returns the `BodyId` associated with it.
483 pub fn body_owned_by(&self, id: HirId) -> BodyId {
484 self.maybe_body_owned_by(id).unwrap_or_else(|| {
485 span_bug!(self.span(id), "body_owned_by: {} has no associated body",
486 self.node_to_string(id));
490 pub fn body_owner_kind(&self, id: HirId) -> BodyOwnerKind {
492 Node::Item(&Item { kind: ItemKind::Const(..), .. }) |
493 Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. }) |
494 Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. }) |
495 Node::AnonConst(_) => {
499 Node::Item(&Item { kind: ItemKind::Fn(..), .. }) |
500 Node::TraitItem(&TraitItem { kind: TraitItemKind::Method(..), .. }) |
501 Node::ImplItem(&ImplItem { kind: ImplItemKind::Method(..), .. }) => {
504 Node::Item(&Item { kind: ItemKind::Static(_, m, _), .. }) => {
505 BodyOwnerKind::Static(m)
507 Node::Expr(&Expr { kind: ExprKind::Closure(..), .. }) => {
508 BodyOwnerKind::Closure
510 node => bug!("{:#?} is not a body node", node),
514 pub fn ty_param_owner(&self, id: HirId) -> HirId {
516 Node::Item(&Item { kind: ItemKind::Trait(..), .. }) |
517 Node::Item(&Item { kind: ItemKind::TraitAlias(..), .. }) => id,
518 Node::GenericParam(_) => self.get_parent_node(id),
519 _ => bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id))
523 pub fn ty_param_name(&self, id: HirId) -> Name {
525 Node::Item(&Item { kind: ItemKind::Trait(..), .. }) |
526 Node::Item(&Item { kind: ItemKind::TraitAlias(..), .. }) => kw::SelfUpper,
527 Node::GenericParam(param) => param.name.ident().name,
528 _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
532 pub fn trait_impls(&self, trait_did: DefId) -> &'hir [HirId] {
533 self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
535 // N.B., intentionally bypass `self.forest.krate()` so that we
536 // do not trigger a read of the whole krate here
537 self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
540 /// Gets the attributes on the crate. This is preferable to
541 /// invoking `krate.attrs` because it registers a tighter
542 /// dep-graph access.
543 pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
544 let def_path_hash = self.definitions.def_path_hash(CRATE_DEF_INDEX);
546 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::Hir));
547 &self.forest.krate.attrs
550 pub fn get_module(&self, module: DefId) -> (&'hir Mod, Span, HirId) {
551 let hir_id = self.as_local_hir_id(module).unwrap();
553 match self.find_entry(hir_id).unwrap().node {
556 kind: ItemKind::Mod(ref m),
558 }) => (m, span, hir_id),
559 Node::Crate => (&self.forest.krate.module, self.forest.krate.span, hir_id),
560 node => panic!("not a module: {:?}", node),
564 pub fn visit_item_likes_in_module<V>(&self, module: DefId, visitor: &mut V)
565 where V: ItemLikeVisitor<'hir>
567 let hir_id = self.as_local_hir_id(module).unwrap();
569 // Read the module so we'll be re-executed if new items
570 // appear immediately under in the module. If some new item appears
571 // in some nested item in the module, we'll be re-executed due to reads
572 // in the expect_* calls the loops below
575 let module = &self.forest.krate.modules[&hir_id];
577 for id in &module.items {
578 visitor.visit_item(self.expect_item(*id));
581 for id in &module.trait_items {
582 visitor.visit_trait_item(self.expect_trait_item(id.hir_id));
585 for id in &module.impl_items {
586 visitor.visit_impl_item(self.expect_impl_item(id.hir_id));
590 /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found.
591 pub fn get(&self, id: HirId) -> Node<'hir> {
592 // read recorded by `find`
593 self.find(id).unwrap_or_else(||
594 bug!("couldn't find hir id {} in the HIR map", id))
597 pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
598 self.as_local_hir_id(id).map(|id| self.get(id)) // read recorded by `get`
601 pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics> {
602 self.get_if_local(id).and_then(|node| {
604 Node::ImplItem(ref impl_item) => Some(&impl_item.generics),
605 Node::TraitItem(ref trait_item) => Some(&trait_item.generics),
606 Node::Item(ref item) => {
608 ItemKind::Fn(_, ref generics, _) |
609 ItemKind::TyAlias(_, ref generics) |
610 ItemKind::Enum(_, ref generics) |
611 ItemKind::Struct(_, ref generics) |
612 ItemKind::Union(_, ref generics) |
613 ItemKind::Trait(_, _, ref generics, ..) |
614 ItemKind::TraitAlias(ref generics, _) |
615 ItemKind::Impl(_, _, _, ref generics, ..) => Some(generics),
624 /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
625 pub fn find(&self, hir_id: HirId) -> Option<Node<'hir>> {
626 let result = self.find_entry(hir_id).and_then(|entry| {
627 if let Node::Crate = entry.node {
633 if result.is_some() {
639 /// Similar to `get_parent`; returns the parent HIR Id, or just `hir_id` if there
640 /// is no parent. Note that the parent may be `CRATE_HIR_ID`, which is not itself
641 /// present in the map, so passing the return value of `get_parent_node` to
642 /// `get` may in fact panic.
643 /// This function returns the immediate parent in the HIR, whereas `get_parent`
644 /// returns the enclosing item. Note that this might not be the actual parent
645 /// node in the HIR -- some kinds of nodes are not in the map and these will
646 /// never appear as the parent node. Thus, you can always walk the parent nodes
647 /// from a node to the root of the HIR (unless you get back the same ID here,
648 /// which can happen if the ID is not in the map itself or is just weird).
649 pub fn get_parent_node(&self, hir_id: HirId) -> HirId {
650 if self.dep_graph.is_fully_enabled() {
651 let hir_id_owner = hir_id.owner;
652 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
653 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
656 self.find_entry(hir_id)
657 .and_then(|x| x.parent_node())
661 /// Checks if the node is an argument. An argument is a local variable whose
662 /// immediate parent is an item or a closure.
663 pub fn is_argument(&self, id: HirId) -> bool {
664 match self.find(id) {
665 Some(Node::Binding(_)) => (),
668 match self.find(self.get_parent_node(id)) {
669 Some(Node::Item(_)) |
670 Some(Node::TraitItem(_)) |
671 Some(Node::ImplItem(_)) => true,
672 Some(Node::Expr(e)) => {
674 ExprKind::Closure(..) => true,
682 /// Whether the expression pointed at by `hir_id` belongs to a `const` evaluation context.
683 /// Used exclusively for diagnostics, to avoid suggestion function calls.
684 pub fn is_const_context(&self, hir_id: HirId) -> bool {
685 let parent_id = self.get_parent_item(hir_id);
686 match self.get(parent_id) {
688 kind: ItemKind::Const(..),
691 | Node::TraitItem(&TraitItem {
692 kind: TraitItemKind::Const(..),
695 | Node::ImplItem(&ImplItem {
696 kind: ImplItemKind::Const(..),
701 kind: ItemKind::Static(..),
705 kind: ItemKind::Fn(ref sig, ..),
707 }) => sig.header.constness == Constness::Const,
712 /// Wether `hir_id` corresponds to a `mod` or a crate.
713 pub fn is_hir_id_module(&self, hir_id: HirId) -> bool {
714 match self.lookup(hir_id) {
715 Some(Entry { node: Node::Item(Item { kind: ItemKind::Mod(_), .. }), .. }) |
716 Some(Entry { node: Node::Crate, .. }) => true,
721 /// Retrieves the `HirId` for `id`'s enclosing method, unless there's a
722 /// `while` or `loop` before reaching it, as block tail returns are not
723 /// available in them.
726 /// fn foo(x: usize) -> bool {
728 /// true // If `get_return_block` gets passed the `id` corresponding
729 /// } else { // to this, it will return `foo`'s `HirId`.
736 /// fn foo(x: usize) -> bool {
738 /// true // If `get_return_block` gets passed the `id` corresponding
739 /// } // to this, it will return `None`.
743 pub fn get_return_block(&self, id: HirId) -> Option<HirId> {
744 let mut iter = ParentHirIterator::new(id, &self).peekable();
745 let mut ignore_tail = false;
746 if let Some(entry) = self.find_entry(id) {
747 if let Node::Expr(Expr { kind: ExprKind::Ret(_), .. }) = entry.node {
748 // When dealing with `return` statements, we don't care about climbing only tail
753 while let Some((hir_id, node)) = iter.next() {
754 if let (Some((_, next_node)), false) = (iter.peek(), ignore_tail) {
756 Node::Block(Block { expr: None, .. }) => return None,
757 Node::Block(Block { expr: Some(expr), .. }) => {
758 if hir_id != expr.hir_id {
759 // The current node is not the tail expression of its parent.
768 Node::ForeignItem(_) |
770 Node::Expr(Expr { kind: ExprKind::Closure(..), ..}) |
771 Node::ImplItem(_) => return Some(hir_id),
772 Node::Expr(ref expr) => {
774 // Ignore `return`s on the first iteration
775 ExprKind::Loop(..) | ExprKind::Ret(..) => return None,
779 Node::Local(_) => return None,
786 /// Retrieves the `HirId` for `id`'s parent item, or `id` itself if no
787 /// parent item is in this map. The "parent item" is the closest parent node
788 /// in the HIR which is recorded by the map and is an item, either an item
789 /// in a module, trait, or impl.
790 pub fn get_parent_item(&self, hir_id: HirId) -> HirId {
791 for (hir_id, node) in ParentHirIterator::new(hir_id, &self) {
795 Node::ForeignItem(_) |
797 Node::ImplItem(_) => return hir_id,
804 /// Returns the `DefId` of `id`'s nearest module parent, or `id` itself if no
805 /// module parent is in this map.
806 pub fn get_module_parent(&self, id: HirId) -> DefId {
807 self.local_def_id(self.get_module_parent_node(id))
810 /// Returns the `HirId` of `id`'s nearest module parent, or `id` itself if no
811 /// module parent is in this map.
812 pub fn get_module_parent_node(&self, hir_id: HirId) -> HirId {
813 for (hir_id, node) in ParentHirIterator::new(hir_id, &self) {
814 if let Node::Item(&Item { kind: ItemKind::Mod(_), .. }) = node {
821 /// When on a match arm tail expression or on a match arm, give back the enclosing `match`
824 /// Used by error reporting when there's a type error in a match arm caused by the `match`
825 /// expression needing to be unit.
826 pub fn get_match_if_cause(&self, hir_id: HirId) -> Option<&Expr> {
827 for (_, node) in ParentHirIterator::new(hir_id, &self) {
830 Node::ForeignItem(_) |
832 Node::ImplItem(_) => break,
833 Node::Expr(expr) => match expr.kind {
834 ExprKind::Match(_, _, _) => return Some(expr),
837 Node::Stmt(stmt) => match stmt.kind {
838 StmtKind::Local(_) => break,
847 /// Returns the nearest enclosing scope. A scope is roughly an item or block.
848 pub fn get_enclosing_scope(&self, hir_id: HirId) -> Option<HirId> {
849 for (hir_id, node) in ParentHirIterator::new(hir_id, &self) {
856 | ItemKind::Struct(..)
857 | ItemKind::Union(..)
858 | ItemKind::Trait(..)
859 | ItemKind::Impl(..) => true,
863 Node::ForeignItem(fi) => {
865 ForeignItemKind::Fn(..) => true,
869 Node::TraitItem(ti) => {
871 TraitItemKind::Method(..) => true,
875 Node::ImplItem(ii) => {
877 ImplItemKind::Method(..) => true,
881 Node::Block(_) => true,
890 /// Returns the defining scope for an opaque type definition.
891 pub fn get_defining_scope(&self, id: HirId) -> HirId {
894 scope = self.get_enclosing_scope(scope).unwrap_or(CRATE_HIR_ID);
895 if scope == CRATE_HIR_ID {
898 match self.get(scope) {
901 ItemKind::OpaqueTy(OpaqueTy { impl_trait_fn: None, .. }) => {}
912 pub fn get_parent_did(&self, id: HirId) -> DefId {
913 self.local_def_id(self.get_parent_item(id))
916 pub fn get_foreign_abi(&self, hir_id: HirId) -> Abi {
917 let parent = self.get_parent_item(hir_id);
918 if let Some(entry) = self.find_entry(parent) {
920 node: Node::Item(Item { kind: ItemKind::ForeignMod(ref nm), .. }), .. } = entry
922 self.read(hir_id); // reveals some of the content of a node
926 bug!("expected foreign mod or inlined parent, found {}", self.node_to_string(parent))
929 pub fn expect_item(&self, id: HirId) -> &'hir Item {
930 match self.find(id) { // read recorded by `find`
931 Some(Node::Item(item)) => item,
932 _ => bug!("expected item, found {}", self.node_to_string(id))
936 pub fn expect_impl_item(&self, id: HirId) -> &'hir ImplItem {
937 match self.find(id) {
938 Some(Node::ImplItem(item)) => item,
939 _ => bug!("expected impl item, found {}", self.node_to_string(id))
943 pub fn expect_trait_item(&self, id: HirId) -> &'hir TraitItem {
944 match self.find(id) {
945 Some(Node::TraitItem(item)) => item,
946 _ => bug!("expected trait item, found {}", self.node_to_string(id))
950 pub fn expect_variant_data(&self, id: HirId) -> &'hir VariantData {
951 match self.find(id) {
952 Some(Node::Item(i)) => {
954 ItemKind::Struct(ref struct_def, _) |
955 ItemKind::Union(ref struct_def, _) => struct_def,
956 _ => bug!("struct ID bound to non-struct {}", self.node_to_string(id))
959 Some(Node::Variant(variant)) => &variant.data,
960 Some(Node::Ctor(data)) => data,
961 _ => bug!("expected struct or variant, found {}", self.node_to_string(id))
965 pub fn expect_variant(&self, id: HirId) -> &'hir Variant {
966 match self.find(id) {
967 Some(Node::Variant(variant)) => variant,
968 _ => bug!("expected variant, found {}", self.node_to_string(id)),
972 pub fn expect_foreign_item(&self, id: HirId) -> &'hir ForeignItem {
973 match self.find(id) {
974 Some(Node::ForeignItem(item)) => item,
975 _ => bug!("expected foreign item, found {}", self.node_to_string(id))
979 pub fn expect_expr(&self, id: HirId) -> &'hir Expr {
980 match self.find(id) { // read recorded by find
981 Some(Node::Expr(expr)) => expr,
982 _ => bug!("expected expr, found {}", self.node_to_string(id))
986 pub fn name(&self, id: HirId) -> Name {
988 Node::Item(i) => i.ident.name,
989 Node::ForeignItem(fi) => fi.ident.name,
990 Node::ImplItem(ii) => ii.ident.name,
991 Node::TraitItem(ti) => ti.ident.name,
992 Node::Variant(v) => v.ident.name,
993 Node::Field(f) => f.ident.name,
994 Node::Lifetime(lt) => lt.name.ident().name,
995 Node::GenericParam(param) => param.name.ident().name,
996 Node::Binding(&Pat { kind: PatKind::Binding(_, _, l, _), .. }) => l.name,
997 Node::Ctor(..) => self.name(self.get_parent_item(id)),
998 _ => bug!("no name for {}", self.node_to_string(id))
1002 /// Given a node ID, gets a list of attributes associated with the AST
1003 /// corresponding to the node-ID.
1004 pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] {
1005 self.read(id); // reveals attributes on the node
1006 let attrs = match self.find_entry(id).map(|entry| entry.node) {
1007 Some(Node::Param(a)) => Some(&a.attrs[..]),
1008 Some(Node::Local(l)) => Some(&l.attrs[..]),
1009 Some(Node::Item(i)) => Some(&i.attrs[..]),
1010 Some(Node::ForeignItem(fi)) => Some(&fi.attrs[..]),
1011 Some(Node::TraitItem(ref ti)) => Some(&ti.attrs[..]),
1012 Some(Node::ImplItem(ref ii)) => Some(&ii.attrs[..]),
1013 Some(Node::Variant(ref v)) => Some(&v.attrs[..]),
1014 Some(Node::Field(ref f)) => Some(&f.attrs[..]),
1015 Some(Node::Expr(ref e)) => Some(&*e.attrs),
1016 Some(Node::Stmt(ref s)) => Some(s.kind.attrs()),
1017 Some(Node::Arm(ref a)) => Some(&*a.attrs),
1018 Some(Node::GenericParam(param)) => Some(¶m.attrs[..]),
1019 // Unit/tuple structs/variants take the attributes straight from
1020 // the struct/variant definition.
1021 Some(Node::Ctor(..)) => return self.attrs(self.get_parent_item(id)),
1022 Some(Node::Crate) => Some(&self.forest.krate.attrs[..]),
1025 attrs.unwrap_or(&[])
1028 /// Returns an iterator that yields all the hir ids in the map.
1029 fn all_ids<'a>(&'a self) -> impl Iterator<Item = HirId> + 'a {
1030 // This code is a bit awkward because the map is implemented as 2 levels of arrays,
1031 // see the comment on `HirEntryMap`.
1032 // Iterate over all the indices and return a reference to
1033 // local maps and their index given that they exist.
1034 self.map.iter_enumerated().flat_map(move |(owner, local_map)| {
1035 // Iterate over each valid entry in the local map.
1036 local_map.iter_enumerated().filter_map(move |(i, entry)| entry.map(move |_| {
1037 // Reconstruct the `HirId` based on the 3 indices we used to find it.
1046 /// Returns an iterator that yields the node id's with paths that
1047 /// match `parts`. (Requires `parts` is non-empty.)
1049 /// For example, if given `parts` equal to `["bar", "quux"]`, then
1050 /// the iterator will produce node id's for items with paths
1051 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
1052 /// any other such items it can find in the map.
1053 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
1054 -> impl Iterator<Item = NodeId> + 'a {
1055 let nodes = NodesMatchingSuffix {
1057 item_name: parts.last().unwrap(),
1058 in_which: &parts[..parts.len() - 1],
1061 self.all_ids().filter(move |hir| nodes.matches_suffix(*hir)).map(move |hir| {
1062 self.hir_to_node_id(hir)
1066 pub fn span(&self, hir_id: HirId) -> Span {
1067 self.read(hir_id); // reveals span from node
1068 match self.find_entry(hir_id).map(|entry| entry.node) {
1069 Some(Node::Param(param)) => param.span,
1070 Some(Node::Item(item)) => item.span,
1071 Some(Node::ForeignItem(foreign_item)) => foreign_item.span,
1072 Some(Node::TraitItem(trait_method)) => trait_method.span,
1073 Some(Node::ImplItem(impl_item)) => impl_item.span,
1074 Some(Node::Variant(variant)) => variant.span,
1075 Some(Node::Field(field)) => field.span,
1076 Some(Node::AnonConst(constant)) => self.body(constant.body).value.span,
1077 Some(Node::Expr(expr)) => expr.span,
1078 Some(Node::Stmt(stmt)) => stmt.span,
1079 Some(Node::PathSegment(seg)) => seg.ident.span,
1080 Some(Node::Ty(ty)) => ty.span,
1081 Some(Node::TraitRef(tr)) => tr.path.span,
1082 Some(Node::Binding(pat)) => pat.span,
1083 Some(Node::Pat(pat)) => pat.span,
1084 Some(Node::Arm(arm)) => arm.span,
1085 Some(Node::Block(block)) => block.span,
1086 Some(Node::Ctor(..)) => match self.find(
1087 self.get_parent_node(hir_id))
1089 Some(Node::Item(item)) => item.span,
1090 Some(Node::Variant(variant)) => variant.span,
1091 _ => unreachable!(),
1093 Some(Node::Lifetime(lifetime)) => lifetime.span,
1094 Some(Node::GenericParam(param)) => param.span,
1095 Some(Node::Visibility(&Spanned {
1096 node: VisibilityKind::Restricted { ref path, .. }, ..
1098 Some(Node::Visibility(v)) => bug!("unexpected Visibility {:?}", v),
1099 Some(Node::Local(local)) => local.span,
1100 Some(Node::MacroDef(macro_def)) => macro_def.span,
1101 Some(Node::Crate) => self.forest.krate.span,
1102 None => bug!("hir::map::Map::span: id not in map: {:?}", hir_id),
1106 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
1107 self.as_local_hir_id(id).map(|id| self.span(id))
1110 pub fn res_span(&self, res: Res) -> Option<Span> {
1113 Res::Local(id) => Some(self.span(id)),
1114 res => self.span_if_local(res.opt_def_id()?),
1118 pub fn node_to_string(&self, id: HirId) -> String {
1119 hir_id_to_string(self, id, true)
1122 pub fn hir_to_user_string(&self, id: HirId) -> String {
1123 hir_id_to_string(self, id, false)
1126 pub fn hir_to_pretty_string(&self, id: HirId) -> String {
1127 print::to_string(self, |s| s.print_node(self.get(id)))
1131 pub struct NodesMatchingSuffix<'a> {
1133 item_name: &'a String,
1134 in_which: &'a [String],
1137 impl<'a> NodesMatchingSuffix<'a> {
1138 /// Returns `true` only if some suffix of the module path for parent
1139 /// matches `self.in_which`.
1141 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
1142 /// returns true if parent's path ends with the suffix
1143 /// `x_0::x_1::...::x_k`.
1144 fn suffix_matches(&self, parent: HirId) -> bool {
1145 let mut cursor = parent;
1146 for part in self.in_which.iter().rev() {
1147 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
1148 None => return false,
1149 Some((node_id, name)) => (node_id, name),
1151 if mod_name.as_str() != *part {
1154 cursor = self.map.get_parent_item(mod_id);
1158 // Finds the first mod in parent chain for `id`, along with
1161 // If `id` itself is a mod named `m` with parent `p`, then
1162 // returns `Some(id, m, p)`. If `id` has no mod in its parent
1163 // chain, then returns `None`.
1164 fn find_first_mod_parent(map: &Map<'_>, mut id: HirId) -> Option<(HirId, Name)> {
1166 if let Node::Item(item) = map.find(id)? {
1167 if item_is_mod(&item) {
1168 return Some((id, item.ident.name))
1171 let parent = map.get_parent_item(id);
1172 if parent == id { return None }
1176 fn item_is_mod(item: &Item) -> bool {
1178 ItemKind::Mod(_) => true,
1185 // We are looking at some node `n` with a given name and parent
1186 // id; do their names match what I am seeking?
1187 fn matches_names(&self, parent_of_n: HirId, name: Name) -> bool {
1188 name.as_str() == *self.item_name && self.suffix_matches(parent_of_n)
1191 fn matches_suffix(&self, hir: HirId) -> bool {
1192 let name = match self.map.find_entry(hir).map(|entry| entry.node) {
1193 Some(Node::Item(n)) => n.name(),
1194 Some(Node::ForeignItem(n)) => n.name(),
1195 Some(Node::TraitItem(n)) => n.name(),
1196 Some(Node::ImplItem(n)) => n.name(),
1197 Some(Node::Variant(n)) => n.name(),
1198 Some(Node::Field(n)) => n.name(),
1201 self.matches_names(self.map.get_parent_item(hir), name)
1206 fn name(&self) -> Name;
1209 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
1211 impl Named for Item { fn name(&self) -> Name { self.ident.name } }
1212 impl Named for ForeignItem { fn name(&self) -> Name { self.ident.name } }
1213 impl Named for Variant { fn name(&self) -> Name { self.ident.name } }
1214 impl Named for StructField { fn name(&self) -> Name { self.ident.name } }
1215 impl Named for TraitItem { fn name(&self) -> Name { self.ident.name } }
1216 impl Named for ImplItem { fn name(&self) -> Name { self.ident.name } }
1218 pub fn map_crate<'hir>(sess: &crate::session::Session,
1219 cstore: &CrateStoreDyn,
1220 forest: &'hir Forest,
1221 definitions: &'hir Definitions)
1223 let _prof_timer = sess.prof.generic_activity("build_hir_map");
1225 // Build the reverse mapping of `node_to_hir_id`.
1226 let hir_to_node_id = definitions.node_to_hir_id.iter_enumerated()
1227 .map(|(node_id, &hir_id)| (hir_id, node_id)).collect();
1229 let (map, crate_hash) = {
1230 let hcx = crate::ich::StableHashingContext::new(sess, &forest.krate, definitions, cstore);
1232 let mut collector = NodeCollector::root(sess,
1238 intravisit::walk_crate(&mut collector, &forest.krate);
1240 let crate_disambiguator = sess.local_crate_disambiguator();
1241 let cmdline_args = sess.opts.dep_tracking_hash();
1242 collector.finalize_and_compute_crate_hash(
1243 crate_disambiguator,
1251 dep_graph: forest.dep_graph.clone(),
1258 time(sess, "validate HIR map", || {
1259 hir_id_validator::check_crate(&map);
1265 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1266 /// except it avoids creating a dependency on the whole crate.
1267 impl<'hir> print::PpAnn for Map<'hir> {
1268 fn nested(&self, state: &mut print::State<'_>, nested: print::Nested) {
1270 Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1271 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1272 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1273 Nested::Body(id) => state.print_expr(&self.body(id).value),
1274 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat)
1279 impl<'a> print::State<'a> {
1280 pub fn print_node(&mut self, node: Node<'_>) {
1282 Node::Param(a) => self.print_param(&a),
1283 Node::Item(a) => self.print_item(&a),
1284 Node::ForeignItem(a) => self.print_foreign_item(&a),
1285 Node::TraitItem(a) => self.print_trait_item(a),
1286 Node::ImplItem(a) => self.print_impl_item(a),
1287 Node::Variant(a) => self.print_variant(&a),
1288 Node::AnonConst(a) => self.print_anon_const(&a),
1289 Node::Expr(a) => self.print_expr(&a),
1290 Node::Stmt(a) => self.print_stmt(&a),
1291 Node::PathSegment(a) => self.print_path_segment(&a),
1292 Node::Ty(a) => self.print_type(&a),
1293 Node::TraitRef(a) => self.print_trait_ref(&a),
1295 Node::Pat(a) => self.print_pat(&a),
1296 Node::Arm(a) => self.print_arm(&a),
1298 // Containing cbox, will be closed by print-block at `}`.
1299 self.cbox(print::INDENT_UNIT);
1300 // Head-ibox, will be closed by print-block after `{`.
1302 self.print_block(&a)
1304 Node::Lifetime(a) => self.print_lifetime(&a),
1305 Node::Visibility(a) => self.print_visibility(&a),
1306 Node::GenericParam(_) => bug!("cannot print Node::GenericParam"),
1307 Node::Field(_) => bug!("cannot print StructField"),
1308 // These cases do not carry enough information in the
1309 // `hir_map` to reconstruct their full structure for pretty
1311 Node::Ctor(..) => bug!("cannot print isolated Ctor"),
1312 Node::Local(a) => self.print_local_decl(&a),
1313 Node::MacroDef(_) => bug!("cannot print MacroDef"),
1314 Node::Crate => bug!("cannot print Crate"),
1319 fn hir_id_to_string(map: &Map<'_>, id: HirId, include_id: bool) -> String {
1320 let id_str = format!(" (hir_id={})", id);
1321 let id_str = if include_id { &id_str[..] } else { "" };
1324 // This functionality is used for debugging, try to use `TyCtxt` to get
1325 // the user-friendly path, otherwise fall back to stringifying `DefPath`.
1326 crate::ty::tls::with_opt(|tcx| {
1327 if let Some(tcx) = tcx {
1328 let def_id = map.local_def_id(id);
1329 tcx.def_path_str(def_id)
1330 } else if let Some(path) = map.def_path_from_hir_id(id) {
1331 path.data.into_iter().map(|elem| {
1332 elem.data.to_string()
1333 }).collect::<Vec<_>>().join("::")
1335 String::from("<missing path>")
1340 match map.find(id) {
1341 Some(Node::Item(item)) => {
1342 let item_str = match item.kind {
1343 ItemKind::ExternCrate(..) => "extern crate",
1344 ItemKind::Use(..) => "use",
1345 ItemKind::Static(..) => "static",
1346 ItemKind::Const(..) => "const",
1347 ItemKind::Fn(..) => "fn",
1348 ItemKind::Mod(..) => "mod",
1349 ItemKind::ForeignMod(..) => "foreign mod",
1350 ItemKind::GlobalAsm(..) => "global asm",
1351 ItemKind::TyAlias(..) => "ty",
1352 ItemKind::OpaqueTy(..) => "opaque type",
1353 ItemKind::Enum(..) => "enum",
1354 ItemKind::Struct(..) => "struct",
1355 ItemKind::Union(..) => "union",
1356 ItemKind::Trait(..) => "trait",
1357 ItemKind::TraitAlias(..) => "trait alias",
1358 ItemKind::Impl(..) => "impl",
1360 format!("{} {}{}", item_str, path_str(), id_str)
1362 Some(Node::ForeignItem(_)) => {
1363 format!("foreign item {}{}", path_str(), id_str)
1365 Some(Node::ImplItem(ii)) => {
1367 ImplItemKind::Const(..) => {
1368 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1370 ImplItemKind::Method(..) => {
1371 format!("method {} in {}{}", ii.ident, path_str(), id_str)
1373 ImplItemKind::TyAlias(_) => {
1374 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1376 ImplItemKind::OpaqueTy(_) => {
1377 format!("assoc opaque type {} in {}{}", ii.ident, path_str(), id_str)
1381 Some(Node::TraitItem(ti)) => {
1382 let kind = match ti.kind {
1383 TraitItemKind::Const(..) => "assoc constant",
1384 TraitItemKind::Method(..) => "trait method",
1385 TraitItemKind::Type(..) => "assoc type",
1388 format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1390 Some(Node::Variant(ref variant)) => {
1391 format!("variant {} in {}{}",
1395 Some(Node::Field(ref field)) => {
1396 format!("field {} in {}{}",
1400 Some(Node::AnonConst(_)) => {
1401 format!("const {}{}", map.hir_to_pretty_string(id), id_str)
1403 Some(Node::Expr(_)) => {
1404 format!("expr {}{}", map.hir_to_pretty_string(id), id_str)
1406 Some(Node::Stmt(_)) => {
1407 format!("stmt {}{}", map.hir_to_pretty_string(id), id_str)
1409 Some(Node::PathSegment(_)) => {
1410 format!("path segment {}{}", map.hir_to_pretty_string(id), id_str)
1412 Some(Node::Ty(_)) => {
1413 format!("type {}{}", map.hir_to_pretty_string(id), id_str)
1415 Some(Node::TraitRef(_)) => {
1416 format!("trait_ref {}{}", map.hir_to_pretty_string(id), id_str)
1418 Some(Node::Binding(_)) => {
1419 format!("local {}{}", map.hir_to_pretty_string(id), id_str)
1421 Some(Node::Pat(_)) => {
1422 format!("pat {}{}", map.hir_to_pretty_string(id), id_str)
1424 Some(Node::Param(_)) => {
1425 format!("param {}{}", map.hir_to_pretty_string(id), id_str)
1427 Some(Node::Arm(_)) => {
1428 format!("arm {}{}", map.hir_to_pretty_string(id), id_str)
1430 Some(Node::Block(_)) => {
1431 format!("block {}{}", map.hir_to_pretty_string(id), id_str)
1433 Some(Node::Local(_)) => {
1434 format!("local {}{}", map.hir_to_pretty_string(id), id_str)
1436 Some(Node::Ctor(..)) => {
1437 format!("ctor {}{}", path_str(), id_str)
1439 Some(Node::Lifetime(_)) => {
1440 format!("lifetime {}{}", map.hir_to_pretty_string(id), id_str)
1442 Some(Node::GenericParam(ref param)) => {
1443 format!("generic_param {:?}{}", param, id_str)
1445 Some(Node::Visibility(ref vis)) => {
1446 format!("visibility {:?}{}", vis, id_str)
1448 Some(Node::MacroDef(_)) => {
1449 format!("macro {}{}", path_str(), id_str)
1451 Some(Node::Crate) => String::from("root_crate"),
1452 None => format!("unknown node{}", id_str),
1456 pub fn provide(providers: &mut Providers<'_>) {
1457 providers.def_kind = |tcx, def_id| {
1458 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
1459 tcx.hir().def_kind(hir_id)
1461 bug!("calling local def_kind query provider for upstream DefId: {:?}",