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::def_id::{CRATE_DEF_INDEX, DefId, LocalDefId};
11 use crate::middle::cstore::CrateStoreDyn;
13 use rustc_target::spec::abi::Abi;
14 use rustc_data_structures::svh::Svh;
15 use rustc_data_structures::indexed_vec::IndexVec;
16 use syntax::ast::{self, Name, NodeId};
17 use syntax::source_map::Spanned;
18 use syntax::ext::base::MacroKind;
19 use syntax_pos::{Span, DUMMY_SP};
22 use crate::hir::DefKind;
23 use crate::hir::itemlikevisit::ItemLikeVisitor;
24 use crate::hir::print::Nested;
25 use crate::util::nodemap::FxHashMap;
26 use crate::util::common::time;
28 use std::result::Result::Err;
29 use crate::ty::query::Providers;
37 /// Represents an entry and its parent `HirId`.
38 #[derive(Copy, Clone, Debug)]
39 pub struct Entry<'hir> {
41 dep_node: DepNodeIndex,
45 impl<'hir> Entry<'hir> {
46 fn parent_node(self) -> Option<HirId> {
48 Node::Crate | Node::MacroDef(_) => None,
49 _ => Some(self.parent),
53 fn fn_decl(&self) -> Option<&'hir FnDecl> {
55 Node::Item(ref item) => {
57 ItemKind::Fn(ref fn_decl, _, _, _) => Some(fn_decl),
62 Node::TraitItem(ref item) => {
64 TraitItemKind::Method(ref method_sig, _) => Some(&method_sig.decl),
69 Node::ImplItem(ref item) => {
71 ImplItemKind::Method(ref method_sig, _) => Some(&method_sig.decl),
76 Node::Expr(ref expr) => {
78 ExprKind::Closure(_, ref fn_decl, ..) => Some(fn_decl),
87 fn associated_body(self) -> Option<BodyId> {
91 ItemKind::Const(_, body) |
92 ItemKind::Static(.., body) |
93 ItemKind::Fn(_, _, _, body) => Some(body),
98 Node::TraitItem(item) => {
100 TraitItemKind::Const(_, Some(body)) |
101 TraitItemKind::Method(_, TraitMethod::Provided(body)) => Some(body),
106 Node::ImplItem(item) => {
108 ImplItemKind::Const(_, body) |
109 ImplItemKind::Method(_, body) => Some(body),
114 Node::AnonConst(constant) => Some(constant.body),
116 Node::Expr(expr) => {
118 ExprKind::Closure(.., body, _, _) => Some(body),
127 fn is_body_owner(self, hir_id: HirId) -> bool {
128 match self.associated_body() {
129 Some(b) => b.hir_id == hir_id,
135 /// Stores a crate and any number of inlined items from other crates.
138 pub dep_graph: DepGraph,
142 pub fn new(krate: Crate, dep_graph: &DepGraph) -> Forest {
145 dep_graph: dep_graph.clone(),
149 pub fn krate(&self) -> &Crate {
150 self.dep_graph.read(DepNode::new_no_params(DepKind::Krate));
154 /// This is used internally in the dependency tracking system.
155 /// Use the `krate` method to ensure your dependency on the
156 /// crate is tracked.
157 pub fn untracked_krate(&self) -> &Crate {
162 /// This type is effectively a `HashMap<HirId, Entry<'hir>>`,
163 /// but it is implemented as 2 layers of arrays.
164 /// - first we have `A = Vec<Option<B>>` mapping a `DefIndex`'s index to an inner value
165 /// - which is `B = IndexVec<ItemLocalId, Option<Entry<'hir>>` which gives you the `Entry`.
166 pub(super) type HirEntryMap<'hir> = Vec<Option<IndexVec<ItemLocalId, Option<Entry<'hir>>>>>;
168 /// Represents a mapping from `NodeId`s to AST elements and their parent `NodeId`s.
170 pub struct Map<'hir> {
171 /// The backing storage for all the AST nodes.
172 pub forest: &'hir Forest,
174 /// Same as the dep_graph in forest, just available with one fewer
175 /// deref. This is a gratuitous micro-optimization.
176 pub dep_graph: DepGraph,
178 /// The SVH of the local crate.
181 map: HirEntryMap<'hir>,
183 definitions: &'hir Definitions,
185 /// The reverse mapping of `node_to_hir_id`.
186 hir_to_node_id: FxHashMap<HirId, NodeId>,
189 impl<'hir> Map<'hir> {
191 fn lookup(&self, id: HirId) -> Option<&Entry<'hir>> {
192 let local_map = self.map.get(id.owner.index())?;
193 local_map.as_ref()?.get(id.local_id)?.as_ref()
196 /// Registers a read in the dependency graph of the AST node with
197 /// the given `id`. This needs to be called each time a public
198 /// function returns the HIR for a node -- in other words, when it
199 /// "reveals" the content of a node to the caller (who might not
200 /// otherwise have had access to those contents, and hence needs a
201 /// read recorded). If the function just returns a DefId or
202 /// HirId, no actual content was returned, so no read is needed.
203 pub fn read(&self, hir_id: HirId) {
204 if let Some(entry) = self.lookup(hir_id) {
205 self.dep_graph.read_index(entry.dep_node);
207 bug!("called `HirMap::read()` with invalid `HirId`: {:?}", hir_id)
212 pub fn definitions(&self) -> &'hir Definitions {
216 pub fn def_key(&self, def_id: DefId) -> DefKey {
217 assert!(def_id.is_local());
218 self.definitions.def_key(def_id.index)
221 pub fn def_path_from_hir_id(&self, id: HirId) -> Option<DefPath> {
222 self.opt_local_def_id(id).map(|def_id| {
223 self.def_path(def_id)
227 pub fn def_path(&self, def_id: DefId) -> DefPath {
228 assert!(def_id.is_local());
229 self.definitions.def_path(def_id.index)
233 pub fn local_def_id_from_node_id(&self, node: NodeId) -> DefId {
234 self.opt_local_def_id_from_node_id(node).unwrap_or_else(|| {
235 let hir_id = self.node_to_hir_id(node);
236 bug!("local_def_id_from_node_id: no entry for `{}`, which has a map of `{:?}`",
237 node, self.find_entry(hir_id))
242 pub fn local_def_id(&self, hir_id: HirId) -> DefId {
243 self.opt_local_def_id(hir_id).unwrap_or_else(|| {
244 bug!("local_def_id: no entry for `{:?}`, which has a map of `{:?}`",
245 hir_id, self.find_entry(hir_id))
250 pub fn opt_local_def_id(&self, hir_id: HirId) -> Option<DefId> {
251 let node_id = self.hir_to_node_id(hir_id);
252 self.definitions.opt_local_def_id(node_id)
256 pub fn opt_local_def_id_from_node_id(&self, node: NodeId) -> Option<DefId> {
257 self.definitions.opt_local_def_id(node)
261 pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
262 self.definitions.as_local_node_id(def_id)
266 pub fn as_local_hir_id(&self, def_id: DefId) -> Option<HirId> {
267 self.definitions.as_local_hir_id(def_id)
271 pub fn hir_to_node_id(&self, hir_id: HirId) -> NodeId {
272 self.hir_to_node_id[&hir_id]
276 pub fn node_to_hir_id(&self, node_id: NodeId) -> HirId {
277 self.definitions.node_to_hir_id(node_id)
281 pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> HirId {
282 self.definitions.def_index_to_hir_id(def_index)
286 pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
287 self.definitions.def_index_to_hir_id(def_id.to_def_id().index)
290 fn def_kind(&self, hir_id: HirId) -> Option<DefKind> {
291 let node = if let Some(node) = self.find(hir_id) {
298 Node::Item(item) => {
300 ItemKind::Static(..) => DefKind::Static,
301 ItemKind::Const(..) => DefKind::Const,
302 ItemKind::Fn(..) => DefKind::Fn,
303 ItemKind::Mod(..) => DefKind::Mod,
304 ItemKind::Existential(..) => DefKind::Existential,
305 ItemKind::Ty(..) => DefKind::TyAlias,
306 ItemKind::Enum(..) => DefKind::Enum,
307 ItemKind::Struct(..) => DefKind::Struct,
308 ItemKind::Union(..) => DefKind::Union,
309 ItemKind::Trait(..) => DefKind::Trait,
310 ItemKind::TraitAlias(..) => DefKind::TraitAlias,
311 ItemKind::ExternCrate(_) |
313 ItemKind::ForeignMod(..) |
314 ItemKind::GlobalAsm(..) |
315 ItemKind::Impl(..) => return None,
318 Node::ForeignItem(item) => {
320 ForeignItemKind::Fn(..) => DefKind::Fn,
321 ForeignItemKind::Static(..) => DefKind::Static,
322 ForeignItemKind::Type => DefKind::ForeignTy,
325 Node::TraitItem(item) => {
327 TraitItemKind::Const(..) => DefKind::AssocConst,
328 TraitItemKind::Method(..) => DefKind::Method,
329 TraitItemKind::Type(..) => DefKind::AssocTy,
332 Node::ImplItem(item) => {
334 ImplItemKind::Const(..) => DefKind::AssocConst,
335 ImplItemKind::Method(..) => DefKind::Method,
336 ImplItemKind::Type(..) => DefKind::AssocTy,
337 ImplItemKind::Existential(..) => DefKind::AssocExistential,
340 Node::Variant(_) => DefKind::Variant,
341 Node::Ctor(variant_data) => {
342 // FIXME(eddyb) is this even possible, if we have a `Node::Ctor`?
343 if variant_data.ctor_hir_id().is_none() {
346 let ctor_of = match self.find(self.get_parent_node(hir_id)) {
347 Some(Node::Item(..)) => def::CtorOf::Struct,
348 Some(Node::Variant(..)) => def::CtorOf::Variant,
351 DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data))
357 Node::PathSegment(_) |
366 Node::Visibility(_) |
368 Node::Crate => return None,
369 Node::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
370 Node::GenericParam(param) => {
372 GenericParamKind::Lifetime { .. } => return None,
373 GenericParamKind::Type { .. } => DefKind::TyParam,
374 GenericParamKind::Const { .. } => DefKind::ConstParam,
380 fn find_entry(&self, id: HirId) -> Option<Entry<'hir>> {
381 self.lookup(id).cloned()
384 pub fn krate(&self) -> &'hir Crate {
388 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem {
389 self.read(id.hir_id);
391 // N.B., intentionally bypass `self.forest.krate()` so that we
392 // do not trigger a read of the whole krate here
393 self.forest.krate.trait_item(id)
396 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem {
397 self.read(id.hir_id);
399 // N.B., intentionally bypass `self.forest.krate()` so that we
400 // do not trigger a read of the whole krate here
401 self.forest.krate.impl_item(id)
404 pub fn body(&self, id: BodyId) -> &'hir Body {
405 self.read(id.hir_id);
407 // N.B., intentionally bypass `self.forest.krate()` so that we
408 // do not trigger a read of the whole krate here
409 self.forest.krate.body(id)
412 pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnDecl> {
413 if let Some(entry) = self.find_entry(hir_id) {
416 bug!("no entry for hir_id `{}`", hir_id)
420 /// Returns the `HirId` that corresponds to the definition of
421 /// which this is the body of, i.e., a `fn`, `const` or `static`
422 /// item (possibly associated), a closure, or a `hir::AnonConst`.
423 pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> HirId {
424 let parent = self.get_parent_node(hir_id);
425 assert!(self.lookup(parent).map_or(false, |e| e.is_body_owner(hir_id)));
429 pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
430 self.local_def_id(self.body_owner(id))
433 /// Given a `HirId`, returns the `BodyId` associated with it,
434 /// if the node is a body owner, otherwise returns `None`.
435 pub fn maybe_body_owned_by(&self, hir_id: HirId) -> Option<BodyId> {
436 if let Some(entry) = self.find_entry(hir_id) {
437 if self.dep_graph.is_fully_enabled() {
438 let hir_id_owner = hir_id.owner;
439 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
440 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
443 entry.associated_body()
445 bug!("no entry for id `{}`", hir_id)
449 /// Given a body owner's id, returns the `BodyId` associated with it.
450 pub fn body_owned_by(&self, id: HirId) -> BodyId {
451 self.maybe_body_owned_by(id).unwrap_or_else(|| {
452 span_bug!(self.span(id), "body_owned_by: {} has no associated body",
453 self.node_to_string(id));
457 pub fn body_owner_kind(&self, id: HirId) -> BodyOwnerKind {
459 Node::Item(&Item { node: ItemKind::Const(..), .. }) |
460 Node::TraitItem(&TraitItem { node: TraitItemKind::Const(..), .. }) |
461 Node::ImplItem(&ImplItem { node: ImplItemKind::Const(..), .. }) |
462 Node::AnonConst(_) => {
466 Node::Item(&Item { node: ItemKind::Fn(..), .. }) |
467 Node::TraitItem(&TraitItem { node: TraitItemKind::Method(..), .. }) |
468 Node::ImplItem(&ImplItem { node: ImplItemKind::Method(..), .. }) => {
471 Node::Item(&Item { node: ItemKind::Static(_, m, _), .. }) => {
472 BodyOwnerKind::Static(m)
474 Node::Expr(&Expr { node: ExprKind::Closure(..), .. }) => {
475 BodyOwnerKind::Closure
477 node => bug!("{:#?} is not a body node", node),
481 pub fn ty_param_owner(&self, id: HirId) -> HirId {
483 Node::Item(&Item { node: ItemKind::Trait(..), .. }) |
484 Node::Item(&Item { node: ItemKind::TraitAlias(..), .. }) => id,
485 Node::GenericParam(_) => self.get_parent_node(id),
486 _ => bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id))
490 pub fn ty_param_name(&self, id: HirId) -> Name {
492 Node::Item(&Item { node: ItemKind::Trait(..), .. }) |
493 Node::Item(&Item { node: ItemKind::TraitAlias(..), .. }) => kw::SelfUpper,
494 Node::GenericParam(param) => param.name.ident().name,
495 _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
499 pub fn trait_impls(&self, trait_did: DefId) -> &'hir [HirId] {
500 self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
502 // N.B., intentionally bypass `self.forest.krate()` so that we
503 // do not trigger a read of the whole krate here
504 self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
507 /// Gets the attributes on the crate. This is preferable to
508 /// invoking `krate.attrs` because it registers a tighter
509 /// dep-graph access.
510 pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
511 let def_path_hash = self.definitions.def_path_hash(CRATE_DEF_INDEX);
513 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::Hir));
514 &self.forest.krate.attrs
517 pub fn get_module(&self, module: DefId) -> (&'hir Mod, Span, HirId)
519 let hir_id = self.as_local_hir_id(module).unwrap();
521 match self.find_entry(hir_id).unwrap().node {
524 node: ItemKind::Mod(ref m),
526 }) => (m, span, hir_id),
527 Node::Crate => (&self.forest.krate.module, self.forest.krate.span, hir_id),
528 _ => panic!("not a module")
532 pub fn visit_item_likes_in_module<V>(&self, module: DefId, visitor: &mut V)
533 where V: ItemLikeVisitor<'hir>
535 let hir_id = self.as_local_hir_id(module).unwrap();
537 // Read the module so we'll be re-executed if new items
538 // appear immediately under in the module. If some new item appears
539 // in some nested item in the module, we'll be re-executed due to reads
540 // in the expect_* calls the loops below
543 let node_id = self.hir_to_node_id[&hir_id];
545 let module = &self.forest.krate.modules[&node_id];
547 for id in &module.items {
548 visitor.visit_item(self.expect_item(*id));
551 for id in &module.trait_items {
552 visitor.visit_trait_item(self.expect_trait_item(id.hir_id));
555 for id in &module.impl_items {
556 visitor.visit_impl_item(self.expect_impl_item(id.hir_id));
560 /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found.
561 pub fn get(&self, id: HirId) -> Node<'hir> {
562 // read recorded by `find`
563 self.find(id).unwrap_or_else(||
564 bug!("couldn't find hir id {} in the HIR map", id))
567 pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
568 self.as_local_hir_id(id).map(|id| self.get(id)) // read recorded by `get`
571 pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics> {
572 self.get_if_local(id).and_then(|node| {
574 Node::ImplItem(ref impl_item) => Some(&impl_item.generics),
575 Node::TraitItem(ref trait_item) => Some(&trait_item.generics),
576 Node::Item(ref item) => {
578 ItemKind::Fn(_, _, ref generics, _) |
579 ItemKind::Ty(_, ref generics) |
580 ItemKind::Enum(_, ref generics) |
581 ItemKind::Struct(_, ref generics) |
582 ItemKind::Union(_, ref generics) |
583 ItemKind::Trait(_, _, ref generics, ..) |
584 ItemKind::TraitAlias(ref generics, _) |
585 ItemKind::Impl(_, _, _, ref generics, ..) => Some(generics),
594 /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
595 pub fn find(&self, hir_id: HirId) -> Option<Node<'hir>> {
596 let result = self.find_entry(hir_id).and_then(|entry| {
597 if let Node::Crate = entry.node {
603 if result.is_some() {
609 /// Similar to `get_parent`; returns the parent HIR Id, or just `hir_id` if there
610 /// is no parent. Note that the parent may be `CRATE_HIR_ID`, which is not itself
611 /// present in the map, so passing the return value of `get_parent_node` to
612 /// `get` may in fact panic.
613 /// This function returns the immediate parent in the HIR, whereas `get_parent`
614 /// returns the enclosing item. Note that this might not be the actual parent
615 /// node in the HIR -- some kinds of nodes are not in the map and these will
616 /// never appear as the parent node. Thus, you can always walk the parent nodes
617 /// from a node to the root of the HIR (unless you get back the same ID here,
618 /// which can happen if the ID is not in the map itself or is just weird).
619 pub fn get_parent_node(&self, hir_id: HirId) -> HirId {
620 if self.dep_graph.is_fully_enabled() {
621 let hir_id_owner = hir_id.owner;
622 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
623 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
626 self.find_entry(hir_id)
627 .and_then(|x| x.parent_node())
631 /// Check if the node is an argument. An argument is a local variable whose
632 /// immediate parent is an item or a closure.
633 pub fn is_argument(&self, id: HirId) -> bool {
634 match self.find(id) {
635 Some(Node::Binding(_)) => (),
638 match self.find(self.get_parent_node(id)) {
639 Some(Node::Item(_)) |
640 Some(Node::TraitItem(_)) |
641 Some(Node::ImplItem(_)) => true,
642 Some(Node::Expr(e)) => {
644 ExprKind::Closure(..) => true,
652 pub fn is_const_scope(&self, hir_id: HirId) -> bool {
653 self.walk_parent_nodes(hir_id, |node| match *node {
654 Node::Item(Item { node: ItemKind::Const(_, _), .. }) => true,
655 Node::Item(Item { node: ItemKind::Fn(_, header, _, _), .. }) => header.is_const(),
657 }, |_| false).map(|id| id != CRATE_HIR_ID).unwrap_or(false)
660 /// If there is some error when walking the parents (e.g., a node does not
661 /// have a parent in the map or a node can't be found), then we return the
662 /// last good `HirId` we found. Note that reaching the crate root (`id == 0`),
663 /// is not an error, since items in the crate module have the crate root as
665 fn walk_parent_nodes<F, F2>(&self,
669 -> Result<HirId, HirId>
670 where F: Fn(&Node<'hir>) -> bool, F2: Fn(&Node<'hir>) -> bool
672 let mut id = start_id;
674 let parent_id = self.get_parent_node(id);
675 if parent_id == CRATE_HIR_ID {
676 return Ok(CRATE_HIR_ID);
682 if let Some(entry) = self.find_entry(parent_id) {
683 if let Node::Crate = entry.node {
686 if found(&entry.node) {
687 return Ok(parent_id);
688 } else if bail_early(&entry.node) {
689 return Err(parent_id);
698 /// Retrieves the `HirId` for `id`'s enclosing method, unless there's a
699 /// `while` or `loop` before reaching it, as block tail returns are not
700 /// available in them.
703 /// fn foo(x: usize) -> bool {
705 /// true // `get_return_block` gets passed the `id` corresponding
706 /// } else { // to this, it will return `foo`'s `HirId`.
713 /// fn foo(x: usize) -> bool {
715 /// true // `get_return_block` gets passed the `id` corresponding
716 /// } // to this, it will return `None`.
720 pub fn get_return_block(&self, id: HirId) -> Option<HirId> {
721 let match_fn = |node: &Node<'_>| {
724 Node::ForeignItem(_) |
726 Node::Expr(Expr { node: ExprKind::Closure(..), ..}) |
727 Node::ImplItem(_) => true,
731 let match_non_returning_block = |node: &Node<'_>| {
733 Node::Expr(ref expr) => {
735 ExprKind::Loop(..) | ExprKind::Ret(..) => true,
743 self.walk_parent_nodes(id, match_fn, match_non_returning_block).ok()
746 /// Retrieves the `HirId` for `id`'s parent item, or `id` itself if no
747 /// parent item is in this map. The "parent item" is the closest parent node
748 /// in the HIR which is recorded by the map and is an item, either an item
749 /// in a module, trait, or impl.
750 pub fn get_parent_item(&self, hir_id: HirId) -> HirId {
751 match self.walk_parent_nodes(hir_id, |node| match *node {
753 Node::ForeignItem(_) |
755 Node::ImplItem(_) => true,
763 /// Returns the `DefId` of `id`'s nearest module parent, or `id` itself if no
764 /// module parent is in this map.
765 pub fn get_module_parent(&self, id: HirId) -> DefId {
766 self.local_def_id(self.get_module_parent_node(id))
769 /// Returns the `HirId` of `id`'s nearest module parent, or `id` itself if no
770 /// module parent is in this map.
771 pub fn get_module_parent_node(&self, hir_id: HirId) -> HirId {
772 match self.walk_parent_nodes(hir_id, |node| match *node {
773 Node::Item(&Item { node: ItemKind::Mod(_), .. }) => true,
781 /// Returns the nearest enclosing scope. A scope is roughly an item or block.
782 pub fn get_enclosing_scope(&self, hir_id: HirId) -> Option<HirId> {
783 self.walk_parent_nodes(hir_id, |node| match *node {
789 | ItemKind::Struct(..)
790 | ItemKind::Union(..)
791 | ItemKind::Trait(..)
792 | ItemKind::Impl(..) => true,
796 Node::ForeignItem(fi) => {
798 ForeignItemKind::Fn(..) => true,
802 Node::TraitItem(ti) => {
804 TraitItemKind::Method(..) => true,
808 Node::ImplItem(ii) => {
810 ImplItemKind::Method(..) => true,
814 Node::Block(_) => true,
819 /// Returns the defining scope for an existential type definition.
820 pub fn get_defining_scope(&self, id: HirId) -> Option<HirId> {
823 scope = self.get_enclosing_scope(scope)?;
824 if scope == CRATE_HIR_ID {
825 return Some(CRATE_HIR_ID);
827 match self.get(scope) {
830 ItemKind::Existential(ExistTy { impl_trait_fn: None, .. }) => {}
841 pub fn get_parent_did(&self, id: HirId) -> DefId {
842 self.local_def_id(self.get_parent_item(id))
845 pub fn get_foreign_abi(&self, hir_id: HirId) -> Abi {
846 let parent = self.get_parent_item(hir_id);
847 if let Some(entry) = self.find_entry(parent) {
849 node: Node::Item(Item { node: ItemKind::ForeignMod(ref nm), .. }), .. } = entry
851 self.read(hir_id); // reveals some of the content of a node
855 bug!("expected foreign mod or inlined parent, found {}", self.node_to_string(parent))
858 pub fn expect_item(&self, id: HirId) -> &'hir Item {
859 match self.find(id) { // read recorded by `find`
860 Some(Node::Item(item)) => item,
861 _ => bug!("expected item, found {}", self.node_to_string(id))
865 pub fn expect_impl_item(&self, id: HirId) -> &'hir ImplItem {
866 match self.find(id) {
867 Some(Node::ImplItem(item)) => item,
868 _ => bug!("expected impl item, found {}", self.node_to_string(id))
872 pub fn expect_trait_item(&self, id: HirId) -> &'hir TraitItem {
873 match self.find(id) {
874 Some(Node::TraitItem(item)) => item,
875 _ => bug!("expected trait item, found {}", self.node_to_string(id))
879 pub fn expect_variant_data(&self, id: HirId) -> &'hir VariantData {
880 match self.find(id) {
881 Some(Node::Item(i)) => {
883 ItemKind::Struct(ref struct_def, _) |
884 ItemKind::Union(ref struct_def, _) => struct_def,
885 _ => bug!("struct ID bound to non-struct {}", self.node_to_string(id))
888 Some(Node::Variant(variant)) => &variant.node.data,
889 Some(Node::Ctor(data)) => data,
890 _ => bug!("expected struct or variant, found {}", self.node_to_string(id))
894 pub fn expect_variant(&self, id: HirId) -> &'hir Variant {
895 match self.find(id) {
896 Some(Node::Variant(variant)) => variant,
897 _ => bug!("expected variant, found {}", self.node_to_string(id)),
901 pub fn expect_foreign_item(&self, id: HirId) -> &'hir ForeignItem {
902 match self.find(id) {
903 Some(Node::ForeignItem(item)) => item,
904 _ => bug!("expected foreign item, found {}", self.node_to_string(id))
908 pub fn expect_expr(&self, id: HirId) -> &'hir Expr {
909 match self.find(id) { // read recorded by find
910 Some(Node::Expr(expr)) => expr,
911 _ => bug!("expected expr, found {}", self.node_to_string(id))
915 pub fn name(&self, id: HirId) -> Name {
917 Node::Item(i) => i.ident.name,
918 Node::ForeignItem(fi) => fi.ident.name,
919 Node::ImplItem(ii) => ii.ident.name,
920 Node::TraitItem(ti) => ti.ident.name,
921 Node::Variant(v) => v.node.ident.name,
922 Node::Field(f) => f.ident.name,
923 Node::Lifetime(lt) => lt.name.ident().name,
924 Node::GenericParam(param) => param.name.ident().name,
925 Node::Binding(&Pat { node: PatKind::Binding(_, _, l, _), .. }) => l.name,
926 Node::Ctor(..) => self.name(self.get_parent_item(id)),
927 _ => bug!("no name for {}", self.node_to_string(id))
931 /// Given a node ID, gets a list of attributes associated with the AST
932 /// corresponding to the node-ID.
933 pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] {
934 self.read(id); // reveals attributes on the node
935 let attrs = match self.find_entry(id).map(|entry| entry.node) {
936 Some(Node::Arg(a)) => Some(&a.attrs[..]),
937 Some(Node::Local(l)) => Some(&l.attrs[..]),
938 Some(Node::Item(i)) => Some(&i.attrs[..]),
939 Some(Node::ForeignItem(fi)) => Some(&fi.attrs[..]),
940 Some(Node::TraitItem(ref ti)) => Some(&ti.attrs[..]),
941 Some(Node::ImplItem(ref ii)) => Some(&ii.attrs[..]),
942 Some(Node::Variant(ref v)) => Some(&v.node.attrs[..]),
943 Some(Node::Field(ref f)) => Some(&f.attrs[..]),
944 Some(Node::Expr(ref e)) => Some(&*e.attrs),
945 Some(Node::Stmt(ref s)) => Some(s.node.attrs()),
946 Some(Node::Arm(ref a)) => Some(&*a.attrs),
947 Some(Node::GenericParam(param)) => Some(¶m.attrs[..]),
948 // Unit/tuple structs/variants take the attributes straight from
949 // the struct/variant definition.
950 Some(Node::Ctor(..)) => return self.attrs(self.get_parent_item(id)),
951 Some(Node::Crate) => Some(&self.forest.krate.attrs[..]),
957 /// Returns an iterator that yields all the hir ids in the map.
958 fn all_ids<'a>(&'a self) -> impl Iterator<Item = HirId> + 'a {
959 // This code is a bit awkward because the map is implemented as 2 levels of arrays,
960 // see the comment on `HirEntryMap`.
961 // Iterate over all the indices and return a reference to
962 // local maps and their index given that they exist.
963 self.map.iter().enumerate().filter_map(|(i, local_map)| {
964 local_map.as_ref().map(|m| (i, m))
965 }).flat_map(move |(array_index, local_map)| {
966 // Iterate over each valid entry in the local map
967 local_map.iter_enumerated().filter_map(move |(i, entry)| entry.map(move |_| {
968 // Reconstruct the HirId based on the 3 indices we used to find it
970 owner: DefIndex::from(array_index),
977 /// Returns an iterator that yields the node id's with paths that
978 /// match `parts`. (Requires `parts` is non-empty.)
980 /// For example, if given `parts` equal to `["bar", "quux"]`, then
981 /// the iterator will produce node id's for items with paths
982 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
983 /// any other such items it can find in the map.
984 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
985 -> impl Iterator<Item = NodeId> + 'a {
986 let nodes = NodesMatchingSuffix {
988 item_name: parts.last().unwrap(),
989 in_which: &parts[..parts.len() - 1],
992 self.all_ids().filter(move |hir| nodes.matches_suffix(*hir)).map(move |hir| {
993 self.hir_to_node_id(hir)
997 pub fn span(&self, hir_id: HirId) -> Span {
998 self.read(hir_id); // reveals span from node
999 match self.find_entry(hir_id).map(|entry| entry.node) {
1000 Some(Node::Arg(arg)) => arg.span,
1001 Some(Node::Item(item)) => item.span,
1002 Some(Node::ForeignItem(foreign_item)) => foreign_item.span,
1003 Some(Node::TraitItem(trait_method)) => trait_method.span,
1004 Some(Node::ImplItem(impl_item)) => impl_item.span,
1005 Some(Node::Variant(variant)) => variant.span,
1006 Some(Node::Field(field)) => field.span,
1007 Some(Node::AnonConst(constant)) => self.body(constant.body).value.span,
1008 Some(Node::Expr(expr)) => expr.span,
1009 Some(Node::Stmt(stmt)) => stmt.span,
1010 Some(Node::PathSegment(seg)) => seg.ident.span,
1011 Some(Node::Ty(ty)) => ty.span,
1012 Some(Node::TraitRef(tr)) => tr.path.span,
1013 Some(Node::Binding(pat)) => pat.span,
1014 Some(Node::Pat(pat)) => pat.span,
1015 Some(Node::Arm(arm)) => arm.span,
1016 Some(Node::Block(block)) => block.span,
1017 Some(Node::Ctor(..)) => match self.find(
1018 self.get_parent_node(hir_id))
1020 Some(Node::Item(item)) => item.span,
1021 Some(Node::Variant(variant)) => variant.span,
1022 _ => unreachable!(),
1024 Some(Node::Lifetime(lifetime)) => lifetime.span,
1025 Some(Node::GenericParam(param)) => param.span,
1026 Some(Node::Visibility(&Spanned {
1027 node: VisibilityKind::Restricted { ref path, .. }, ..
1029 Some(Node::Visibility(v)) => bug!("unexpected Visibility {:?}", v),
1030 Some(Node::Local(local)) => local.span,
1031 Some(Node::MacroDef(macro_def)) => macro_def.span,
1032 Some(Node::Crate) => self.forest.krate.span,
1033 None => bug!("hir::map::Map::span: id not in map: {:?}", hir_id),
1037 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
1038 self.as_local_hir_id(id).map(|id| self.span(id))
1041 pub fn node_to_string(&self, id: HirId) -> String {
1042 hir_id_to_string(self, id, true)
1045 pub fn hir_to_user_string(&self, id: HirId) -> String {
1046 hir_id_to_string(self, id, false)
1049 pub fn hir_to_pretty_string(&self, id: HirId) -> String {
1050 print::to_string(self, |s| s.print_node(self.get(id)))
1054 pub struct NodesMatchingSuffix<'a> {
1056 item_name: &'a String,
1057 in_which: &'a [String],
1060 impl<'a> NodesMatchingSuffix<'a> {
1061 /// Returns `true` only if some suffix of the module path for parent
1062 /// matches `self.in_which`.
1064 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
1065 /// returns true if parent's path ends with the suffix
1066 /// `x_0::x_1::...::x_k`.
1067 fn suffix_matches(&self, parent: HirId) -> bool {
1068 let mut cursor = parent;
1069 for part in self.in_which.iter().rev() {
1070 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
1071 None => return false,
1072 Some((node_id, name)) => (node_id, name),
1074 if mod_name.as_str() != *part {
1077 cursor = self.map.get_parent_item(mod_id);
1081 // Finds the first mod in parent chain for `id`, along with
1084 // If `id` itself is a mod named `m` with parent `p`, then
1085 // returns `Some(id, m, p)`. If `id` has no mod in its parent
1086 // chain, then returns `None`.
1087 fn find_first_mod_parent(map: &Map<'_>, mut id: HirId) -> Option<(HirId, Name)> {
1089 if let Node::Item(item) = map.find(id)? {
1090 if item_is_mod(&item) {
1091 return Some((id, item.ident.name))
1094 let parent = map.get_parent_item(id);
1095 if parent == id { return None }
1099 fn item_is_mod(item: &Item) -> bool {
1101 ItemKind::Mod(_) => true,
1108 // We are looking at some node `n` with a given name and parent
1109 // id; do their names match what I am seeking?
1110 fn matches_names(&self, parent_of_n: HirId, name: Name) -> bool {
1111 name.as_str() == *self.item_name && self.suffix_matches(parent_of_n)
1114 fn matches_suffix(&self, hir: HirId) -> bool {
1115 let name = match self.map.find_entry(hir).map(|entry| entry.node) {
1116 Some(Node::Item(n)) => n.name(),
1117 Some(Node::ForeignItem(n)) => n.name(),
1118 Some(Node::TraitItem(n)) => n.name(),
1119 Some(Node::ImplItem(n)) => n.name(),
1120 Some(Node::Variant(n)) => n.name(),
1121 Some(Node::Field(n)) => n.name(),
1124 self.matches_names(self.map.get_parent_item(hir), name)
1129 fn name(&self) -> Name;
1132 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
1134 impl Named for Item { fn name(&self) -> Name { self.ident.name } }
1135 impl Named for ForeignItem { fn name(&self) -> Name { self.ident.name } }
1136 impl Named for VariantKind { fn name(&self) -> Name { self.ident.name } }
1137 impl Named for StructField { fn name(&self) -> Name { self.ident.name } }
1138 impl Named for TraitItem { fn name(&self) -> Name { self.ident.name } }
1139 impl Named for ImplItem { fn name(&self) -> Name { self.ident.name } }
1141 pub fn map_crate<'hir>(sess: &crate::session::Session,
1142 cstore: &CrateStoreDyn,
1143 forest: &'hir Forest,
1144 definitions: &'hir Definitions)
1146 // Build the reverse mapping of `node_to_hir_id`.
1147 let hir_to_node_id = definitions.node_to_hir_id.iter_enumerated()
1148 .map(|(node_id, &hir_id)| (hir_id, node_id)).collect();
1150 let (map, crate_hash) = {
1151 let hcx = crate::ich::StableHashingContext::new(sess, &forest.krate, definitions, cstore);
1153 let mut collector = NodeCollector::root(sess,
1159 intravisit::walk_crate(&mut collector, &forest.krate);
1161 let crate_disambiguator = sess.local_crate_disambiguator();
1162 let cmdline_args = sess.opts.dep_tracking_hash();
1163 collector.finalize_and_compute_crate_hash(
1164 crate_disambiguator,
1172 dep_graph: forest.dep_graph.clone(),
1179 time(sess, "validate hir map", || {
1180 hir_id_validator::check_crate(&map);
1186 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1187 /// except it avoids creating a dependency on the whole crate.
1188 impl<'hir> print::PpAnn for Map<'hir> {
1189 fn nested(&self, state: &mut print::State<'_>, nested: print::Nested) {
1191 Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1192 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1193 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1194 Nested::Body(id) => state.print_expr(&self.body(id).value),
1195 Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
1200 impl<'a> print::State<'a> {
1201 pub fn print_node(&mut self, node: Node<'_>) {
1203 Node::Arg(a) => self.print_arg(&a),
1204 Node::Item(a) => self.print_item(&a),
1205 Node::ForeignItem(a) => self.print_foreign_item(&a),
1206 Node::TraitItem(a) => self.print_trait_item(a),
1207 Node::ImplItem(a) => self.print_impl_item(a),
1208 Node::Variant(a) => self.print_variant(&a),
1209 Node::AnonConst(a) => self.print_anon_const(&a),
1210 Node::Expr(a) => self.print_expr(&a),
1211 Node::Stmt(a) => self.print_stmt(&a),
1212 Node::PathSegment(a) => self.print_path_segment(&a),
1213 Node::Ty(a) => self.print_type(&a),
1214 Node::TraitRef(a) => self.print_trait_ref(&a),
1216 Node::Pat(a) => self.print_pat(&a),
1217 Node::Arm(a) => self.print_arm(&a),
1219 // containing cbox, will be closed by print-block at }
1220 self.cbox(print::INDENT_UNIT);
1221 // head-ibox, will be closed by print-block after {
1223 self.print_block(&a)
1225 Node::Lifetime(a) => self.print_lifetime(&a),
1226 Node::Visibility(a) => self.print_visibility(&a),
1227 Node::GenericParam(_) => bug!("cannot print Node::GenericParam"),
1228 Node::Field(_) => bug!("cannot print StructField"),
1229 // these cases do not carry enough information in the
1230 // hir_map to reconstruct their full structure for pretty
1232 Node::Ctor(..) => bug!("cannot print isolated Ctor"),
1233 Node::Local(a) => self.print_local_decl(&a),
1234 Node::MacroDef(_) => bug!("cannot print MacroDef"),
1235 Node::Crate => bug!("cannot print Crate"),
1240 fn hir_id_to_string(map: &Map<'_>, id: HirId, include_id: bool) -> String {
1241 let id_str = format!(" (hir_id={})", id);
1242 let id_str = if include_id { &id_str[..] } else { "" };
1245 // This functionality is used for debugging, try to use TyCtxt to get
1246 // the user-friendly path, otherwise fall back to stringifying DefPath.
1247 crate::ty::tls::with_opt(|tcx| {
1248 if let Some(tcx) = tcx {
1249 let def_id = map.local_def_id(id);
1250 tcx.def_path_str(def_id)
1251 } else if let Some(path) = map.def_path_from_hir_id(id) {
1252 path.data.into_iter().map(|elem| {
1253 elem.data.to_string()
1254 }).collect::<Vec<_>>().join("::")
1256 String::from("<missing path>")
1261 match map.find(id) {
1262 Some(Node::Item(item)) => {
1263 let item_str = match item.node {
1264 ItemKind::ExternCrate(..) => "extern crate",
1265 ItemKind::Use(..) => "use",
1266 ItemKind::Static(..) => "static",
1267 ItemKind::Const(..) => "const",
1268 ItemKind::Fn(..) => "fn",
1269 ItemKind::Mod(..) => "mod",
1270 ItemKind::ForeignMod(..) => "foreign mod",
1271 ItemKind::GlobalAsm(..) => "global asm",
1272 ItemKind::Ty(..) => "ty",
1273 ItemKind::Existential(..) => "existential type",
1274 ItemKind::Enum(..) => "enum",
1275 ItemKind::Struct(..) => "struct",
1276 ItemKind::Union(..) => "union",
1277 ItemKind::Trait(..) => "trait",
1278 ItemKind::TraitAlias(..) => "trait alias",
1279 ItemKind::Impl(..) => "impl",
1281 format!("{} {}{}", item_str, path_str(), id_str)
1283 Some(Node::ForeignItem(_)) => {
1284 format!("foreign item {}{}", path_str(), id_str)
1286 Some(Node::ImplItem(ii)) => {
1288 ImplItemKind::Const(..) => {
1289 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1291 ImplItemKind::Method(..) => {
1292 format!("method {} in {}{}", ii.ident, path_str(), id_str)
1294 ImplItemKind::Type(_) => {
1295 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1297 ImplItemKind::Existential(_) => {
1298 format!("assoc existential type {} in {}{}", ii.ident, path_str(), id_str)
1302 Some(Node::TraitItem(ti)) => {
1303 let kind = match ti.node {
1304 TraitItemKind::Const(..) => "assoc constant",
1305 TraitItemKind::Method(..) => "trait method",
1306 TraitItemKind::Type(..) => "assoc type",
1309 format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1311 Some(Node::Variant(ref variant)) => {
1312 format!("variant {} in {}{}",
1316 Some(Node::Field(ref field)) => {
1317 format!("field {} in {}{}",
1321 Some(Node::AnonConst(_)) => {
1322 format!("const {}{}", map.hir_to_pretty_string(id), id_str)
1324 Some(Node::Expr(_)) => {
1325 format!("expr {}{}", map.hir_to_pretty_string(id), id_str)
1327 Some(Node::Stmt(_)) => {
1328 format!("stmt {}{}", map.hir_to_pretty_string(id), id_str)
1330 Some(Node::PathSegment(_)) => {
1331 format!("path segment {}{}", map.hir_to_pretty_string(id), id_str)
1333 Some(Node::Ty(_)) => {
1334 format!("type {}{}", map.hir_to_pretty_string(id), id_str)
1336 Some(Node::TraitRef(_)) => {
1337 format!("trait_ref {}{}", map.hir_to_pretty_string(id), id_str)
1339 Some(Node::Binding(_)) => {
1340 format!("local {}{}", map.hir_to_pretty_string(id), id_str)
1342 Some(Node::Pat(_)) => {
1343 format!("pat {}{}", map.hir_to_pretty_string(id), id_str)
1345 Some(Node::Arg(_)) => {
1346 format!("arg {}{}", map.hir_to_pretty_string(id), id_str)
1348 Some(Node::Arm(_)) => {
1349 format!("arm {}{}", map.hir_to_pretty_string(id), id_str)
1351 Some(Node::Block(_)) => {
1352 format!("block {}{}", map.hir_to_pretty_string(id), id_str)
1354 Some(Node::Local(_)) => {
1355 format!("local {}{}", map.hir_to_pretty_string(id), id_str)
1357 Some(Node::Ctor(..)) => {
1358 format!("ctor {}{}", path_str(), id_str)
1360 Some(Node::Lifetime(_)) => {
1361 format!("lifetime {}{}", map.hir_to_pretty_string(id), id_str)
1363 Some(Node::GenericParam(ref param)) => {
1364 format!("generic_param {:?}{}", param, id_str)
1366 Some(Node::Visibility(ref vis)) => {
1367 format!("visibility {:?}{}", vis, id_str)
1369 Some(Node::MacroDef(_)) => {
1370 format!("macro {}{}", path_str(), id_str)
1372 Some(Node::Crate) => String::from("root_crate"),
1373 None => format!("unknown node{}", id_str),
1377 pub fn provide(providers: &mut Providers<'_>) {
1378 providers.def_kind = |tcx, def_id| {
1379 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
1380 tcx.hir().def_kind(hir_id)
1382 bug!("calling local def_kind query provider for upstream DefId: {:?}",