1 use self::collector::NodeCollector;
2 pub use self::definitions::{
3 Definitions, DefKey, DefPath, DefPathData, DisambiguatedDefPathData, DefPathHash
6 use crate::dep_graph::{DepGraph, DepNode, DepKind, DepNodeIndex};
8 use crate::hir::DefKind;
9 use crate::hir::def_id::{CRATE_DEF_INDEX, DefId, LocalDefId};
10 use crate::hir::itemlikevisit::ItemLikeVisitor;
11 use crate::hir::print::Nested;
12 use crate::middle::cstore::CrateStoreDyn;
13 use crate::ty::query::Providers;
14 use crate::util::nodemap::FxHashMap;
15 use crate::util::common::time;
17 use rustc_target::spec::abi::Abi;
18 use rustc_data_structures::svh::Svh;
19 use rustc_index::vec::IndexVec;
20 use syntax::ast::{self, Name, NodeId};
21 use syntax::source_map::Spanned;
22 use syntax_pos::hygiene::MacroKind;
23 use syntax_pos::{Span, DUMMY_SP};
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> {
48 Node::Item(ref item) => {
50 ItemKind::Fn(ref sig, _, _) => Some(&sig.decl),
55 Node::TraitItem(ref item) => {
57 TraitItemKind::Method(ref sig, _) => Some(&sig.decl),
62 Node::ImplItem(ref item) => {
64 ImplItemKind::Method(ref sig, _) => Some(&sig.decl),
69 Node::Expr(ref expr) => {
71 ExprKind::Closure(_, ref fn_decl, ..) => Some(fn_decl),
80 fn fn_sig(&self) -> Option<&'hir FnSig> {
84 ItemKind::Fn(sig, _, _) => Some(sig),
89 Node::TraitItem(item) => {
91 TraitItemKind::Method(sig, _) => Some(sig),
96 Node::ImplItem(item) => {
98 ImplItemKind::Method(sig, _) => Some(sig),
107 fn associated_body(self) -> Option<BodyId> {
109 Node::Item(item) => {
111 ItemKind::Const(_, body) |
112 ItemKind::Static(.., body) |
113 ItemKind::Fn(.., body) => Some(body),
118 Node::TraitItem(item) => {
120 TraitItemKind::Const(_, Some(body)) |
121 TraitItemKind::Method(_, TraitMethod::Provided(body)) => Some(body),
126 Node::ImplItem(item) => {
128 ImplItemKind::Const(_, body) |
129 ImplItemKind::Method(_, body) => Some(body),
134 Node::AnonConst(constant) => Some(constant.body),
136 Node::Expr(expr) => {
138 ExprKind::Closure(.., body, _, _) => Some(body),
147 fn is_body_owner(self, hir_id: HirId) -> bool {
148 match self.associated_body() {
149 Some(b) => b.hir_id == hir_id,
155 /// Stores a crate and any number of inlined items from other crates.
156 pub struct Forest<'hir> {
158 pub dep_graph: DepGraph,
162 pub fn new(krate: Crate<'hir>, dep_graph: &DepGraph) -> Forest<'hir> {
165 dep_graph: dep_graph.clone(),
169 pub fn krate(&self) -> &Crate<'hir> {
170 self.dep_graph.read(DepNode::new_no_params(DepKind::Krate));
174 /// This is used internally in the dependency tracking system.
175 /// Use the `krate` method to ensure your dependency on the
176 /// crate is tracked.
177 pub fn untracked_krate(&self) -> &Crate<'hir> {
182 /// This type is effectively a `HashMap<HirId, Entry<'hir>>`,
183 /// but it is implemented as 2 layers of arrays.
184 /// - first we have `A = IndexVec<DefIndex, B>` mapping `DefIndex`s to an inner value
185 /// - which is `B = IndexVec<ItemLocalId, Option<Entry<'hir>>` which gives you the `Entry`.
186 pub(super) type HirEntryMap<'hir> = IndexVec<DefIndex, IndexVec<ItemLocalId, Option<Entry<'hir>>>>;
188 /// Represents a mapping from `NodeId`s to AST elements and their parent `NodeId`s.
190 pub struct Map<'hir> {
191 /// The backing storage for all the AST nodes.
192 pub forest: &'hir Forest<'hir>,
194 /// Same as the dep_graph in forest, just available with one fewer
195 /// deref. This is a gratuitous micro-optimization.
196 pub dep_graph: DepGraph,
198 /// The SVH of the local crate.
201 map: HirEntryMap<'hir>,
203 definitions: Definitions,
205 /// The reverse mapping of `node_to_hir_id`.
206 hir_to_node_id: FxHashMap<HirId, NodeId>,
209 struct ParentHirIterator<'map> {
211 map: &'map Map<'map>,
214 impl<'map> ParentHirIterator<'map> {
215 fn new(current_id: HirId, map: &'map Map<'map>) -> ParentHirIterator<'map> {
223 impl<'map> Iterator for ParentHirIterator<'map> {
224 type Item = (HirId, Node<'map>);
226 fn next(&mut self) -> Option<Self::Item> {
227 if self.current_id == CRATE_HIR_ID {
230 loop { // There are nodes that do not have entries, so we need to skip them.
231 let parent_id = self.map.get_parent_node(self.current_id);
233 if parent_id == self.current_id {
234 self.current_id = CRATE_HIR_ID;
238 self.current_id = parent_id;
239 if let Some(entry) = self.map.find_entry(parent_id) {
240 return Some((parent_id, entry.node));
242 // If this `HirId` doesn't have an `Entry`, skip it and look for its `parent_id`.
247 impl<'hir> Map<'hir> {
249 fn lookup(&self, id: HirId) -> Option<&Entry<'hir>> {
250 let local_map = self.map.get(id.owner)?;
251 local_map.get(id.local_id)?.as_ref()
254 /// Registers a read in the dependency graph of the AST node with
255 /// the given `id`. This needs to be called each time a public
256 /// function returns the HIR for a node -- in other words, when it
257 /// "reveals" the content of a node to the caller (who might not
258 /// otherwise have had access to those contents, and hence needs a
259 /// read recorded). If the function just returns a DefId or
260 /// HirId, no actual content was returned, so no read is needed.
261 pub fn read(&self, hir_id: HirId) {
262 if let Some(entry) = self.lookup(hir_id) {
263 self.dep_graph.read_index(entry.dep_node);
265 bug!("called `HirMap::read()` with invalid `HirId`: {:?}", hir_id)
270 pub fn definitions(&self) -> &Definitions {
274 pub fn def_key(&self, def_id: DefId) -> DefKey {
275 assert!(def_id.is_local());
276 self.definitions.def_key(def_id.index)
279 pub fn def_path_from_hir_id(&self, id: HirId) -> Option<DefPath> {
280 self.opt_local_def_id(id).map(|def_id| {
281 self.def_path(def_id)
285 pub fn def_path(&self, def_id: DefId) -> DefPath {
286 assert!(def_id.is_local());
287 self.definitions.def_path(def_id.index)
291 pub fn local_def_id_from_node_id(&self, node: NodeId) -> DefId {
292 self.opt_local_def_id_from_node_id(node).unwrap_or_else(|| {
293 let hir_id = self.node_to_hir_id(node);
294 bug!("local_def_id_from_node_id: no entry for `{}`, which has a map of `{:?}`",
295 node, self.find_entry(hir_id))
300 pub fn local_def_id(&self, hir_id: HirId) -> DefId {
301 self.opt_local_def_id(hir_id).unwrap_or_else(|| {
302 bug!("local_def_id: no entry for `{:?}`, which has a map of `{:?}`",
303 hir_id, self.find_entry(hir_id))
308 pub fn opt_local_def_id(&self, hir_id: HirId) -> Option<DefId> {
309 let node_id = self.hir_to_node_id(hir_id);
310 self.definitions.opt_local_def_id(node_id)
314 pub fn opt_local_def_id_from_node_id(&self, node: NodeId) -> Option<DefId> {
315 self.definitions.opt_local_def_id(node)
319 pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
320 self.definitions.as_local_node_id(def_id)
324 pub fn as_local_hir_id(&self, def_id: DefId) -> Option<HirId> {
325 self.definitions.as_local_hir_id(def_id)
329 pub fn hir_to_node_id(&self, hir_id: HirId) -> NodeId {
330 self.hir_to_node_id[&hir_id]
334 pub fn node_to_hir_id(&self, node_id: NodeId) -> HirId {
335 self.definitions.node_to_hir_id(node_id)
339 pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> HirId {
340 self.definitions.def_index_to_hir_id(def_index)
344 pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
345 self.definitions.def_index_to_hir_id(def_id.to_def_id().index)
348 pub fn def_kind(&self, hir_id: HirId) -> Option<DefKind> {
349 let node = if let Some(node) = self.find(hir_id) {
356 Node::Item(item) => {
358 ItemKind::Static(..) => DefKind::Static,
359 ItemKind::Const(..) => DefKind::Const,
360 ItemKind::Fn(..) => DefKind::Fn,
361 ItemKind::Mod(..) => DefKind::Mod,
362 ItemKind::OpaqueTy(..) => DefKind::OpaqueTy,
363 ItemKind::TyAlias(..) => DefKind::TyAlias,
364 ItemKind::Enum(..) => DefKind::Enum,
365 ItemKind::Struct(..) => DefKind::Struct,
366 ItemKind::Union(..) => DefKind::Union,
367 ItemKind::Trait(..) => DefKind::Trait,
368 ItemKind::TraitAlias(..) => DefKind::TraitAlias,
369 ItemKind::ExternCrate(_) |
371 ItemKind::ForeignMod(..) |
372 ItemKind::GlobalAsm(..) |
373 ItemKind::Impl(..) => return None,
376 Node::ForeignItem(item) => {
378 ForeignItemKind::Fn(..) => DefKind::Fn,
379 ForeignItemKind::Static(..) => DefKind::Static,
380 ForeignItemKind::Type => DefKind::ForeignTy,
383 Node::TraitItem(item) => {
385 TraitItemKind::Const(..) => DefKind::AssocConst,
386 TraitItemKind::Method(..) => DefKind::Method,
387 TraitItemKind::Type(..) => DefKind::AssocTy,
390 Node::ImplItem(item) => {
392 ImplItemKind::Const(..) => DefKind::AssocConst,
393 ImplItemKind::Method(..) => DefKind::Method,
394 ImplItemKind::TyAlias(..) => DefKind::AssocTy,
395 ImplItemKind::OpaqueTy(..) => DefKind::AssocOpaqueTy,
398 Node::Variant(_) => DefKind::Variant,
399 Node::Ctor(variant_data) => {
400 // FIXME(eddyb) is this even possible, if we have a `Node::Ctor`?
401 if variant_data.ctor_hir_id().is_none() {
404 let ctor_of = match self.find(self.get_parent_node(hir_id)) {
405 Some(Node::Item(..)) => def::CtorOf::Struct,
406 Some(Node::Variant(..)) => def::CtorOf::Variant,
409 DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data))
415 Node::PathSegment(_) |
424 Node::Visibility(_) |
426 Node::Crate => return None,
427 Node::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
428 Node::GenericParam(param) => {
430 GenericParamKind::Lifetime { .. } => return None,
431 GenericParamKind::Type { .. } => DefKind::TyParam,
432 GenericParamKind::Const { .. } => DefKind::ConstParam,
438 fn find_entry(&self, id: HirId) -> Option<Entry<'hir>> {
439 self.lookup(id).cloned()
442 pub fn krate(&self) -> &'hir Crate<'hir> {
446 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
447 self.read(id.hir_id);
449 // N.B., intentionally bypass `self.forest.krate()` so that we
450 // do not trigger a read of the whole krate here
451 self.forest.krate.trait_item(id)
454 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
455 self.read(id.hir_id);
457 // N.B., intentionally bypass `self.forest.krate()` so that we
458 // do not trigger a read of the whole krate here
459 self.forest.krate.impl_item(id)
462 pub fn body(&self, id: BodyId) -> &'hir Body {
463 self.read(id.hir_id);
465 // N.B., intentionally bypass `self.forest.krate()` so that we
466 // do not trigger a read of the whole krate here
467 self.forest.krate.body(id)
470 pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnDecl> {
471 if let Some(entry) = self.find_entry(hir_id) {
474 bug!("no entry for hir_id `{}`", hir_id)
478 pub fn fn_sig_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnSig> {
479 if let Some(entry) = self.find_entry(hir_id) {
482 bug!("no entry for hir_id `{}`", hir_id)
486 /// Returns the `HirId` that corresponds to the definition of
487 /// which this is the body of, i.e., a `fn`, `const` or `static`
488 /// item (possibly associated), a closure, or a `hir::AnonConst`.
489 pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> HirId {
490 let parent = self.get_parent_node(hir_id);
491 assert!(self.lookup(parent).map_or(false, |e| e.is_body_owner(hir_id)));
495 pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
496 self.local_def_id(self.body_owner(id))
499 /// Given a `HirId`, returns the `BodyId` associated with it,
500 /// if the node is a body owner, otherwise returns `None`.
501 pub fn maybe_body_owned_by(&self, hir_id: HirId) -> Option<BodyId> {
502 if let Some(entry) = self.find_entry(hir_id) {
503 if self.dep_graph.is_fully_enabled() {
504 let hir_id_owner = hir_id.owner;
505 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
506 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
509 entry.associated_body()
511 bug!("no entry for id `{}`", hir_id)
515 /// Given a body owner's id, returns the `BodyId` associated with it.
516 pub fn body_owned_by(&self, id: HirId) -> BodyId {
517 self.maybe_body_owned_by(id).unwrap_or_else(|| {
518 span_bug!(self.span(id), "body_owned_by: {} has no associated body",
519 self.node_to_string(id));
523 pub fn body_owner_kind(&self, id: HirId) -> BodyOwnerKind {
525 Node::Item(&Item { kind: ItemKind::Const(..), .. }) |
526 Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. }) |
527 Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. }) |
528 Node::AnonConst(_) => {
532 Node::Item(&Item { kind: ItemKind::Fn(..), .. }) |
533 Node::TraitItem(&TraitItem { kind: TraitItemKind::Method(..), .. }) |
534 Node::ImplItem(&ImplItem { kind: ImplItemKind::Method(..), .. }) => {
537 Node::Item(&Item { kind: ItemKind::Static(_, m, _), .. }) => {
538 BodyOwnerKind::Static(m)
540 Node::Expr(&Expr { kind: ExprKind::Closure(..), .. }) => {
541 BodyOwnerKind::Closure
543 node => bug!("{:#?} is not a body node", node),
547 pub fn ty_param_owner(&self, id: HirId) -> HirId {
549 Node::Item(&Item { kind: ItemKind::Trait(..), .. }) |
550 Node::Item(&Item { kind: ItemKind::TraitAlias(..), .. }) => id,
551 Node::GenericParam(_) => self.get_parent_node(id),
552 _ => bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id))
556 pub fn ty_param_name(&self, id: HirId) -> Name {
558 Node::Item(&Item { kind: ItemKind::Trait(..), .. }) |
559 Node::Item(&Item { kind: ItemKind::TraitAlias(..), .. }) => kw::SelfUpper,
560 Node::GenericParam(param) => param.name.ident().name,
561 _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
565 pub fn trait_impls(&self, trait_did: DefId) -> &'hir [HirId] {
566 self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
568 // N.B., intentionally bypass `self.forest.krate()` so that we
569 // do not trigger a read of the whole krate here
570 self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
573 /// Gets the attributes on the crate. This is preferable to
574 /// invoking `krate.attrs` because it registers a tighter
575 /// dep-graph access.
576 pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
577 let def_path_hash = self.definitions.def_path_hash(CRATE_DEF_INDEX);
579 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::Hir));
580 &self.forest.krate.attrs
583 pub fn get_module(&self, module: DefId) -> (&'hir Mod, Span, HirId) {
584 let hir_id = self.as_local_hir_id(module).unwrap();
586 match self.find_entry(hir_id).unwrap().node {
589 kind: ItemKind::Mod(ref m),
591 }) => (m, span, hir_id),
592 Node::Crate => (&self.forest.krate.module, self.forest.krate.span, hir_id),
593 node => panic!("not a module: {:?}", node),
597 pub fn visit_item_likes_in_module<V>(&self, module: DefId, visitor: &mut V)
598 where V: ItemLikeVisitor<'hir>
600 let hir_id = self.as_local_hir_id(module).unwrap();
602 // Read the module so we'll be re-executed if new items
603 // appear immediately under in the module. If some new item appears
604 // in some nested item in the module, we'll be re-executed due to reads
605 // in the expect_* calls the loops below
608 let module = &self.forest.krate.modules[&hir_id];
610 for id in &module.items {
611 visitor.visit_item(self.expect_item(*id));
614 for id in &module.trait_items {
615 visitor.visit_trait_item(self.expect_trait_item(id.hir_id));
618 for id in &module.impl_items {
619 visitor.visit_impl_item(self.expect_impl_item(id.hir_id));
623 /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found.
624 pub fn get(&self, id: HirId) -> Node<'hir> {
625 // read recorded by `find`
626 self.find(id).unwrap_or_else(||
627 bug!("couldn't find hir id {} in the HIR map", id))
630 pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
631 self.as_local_hir_id(id).map(|id| self.get(id)) // read recorded by `get`
634 pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics> {
635 self.get_if_local(id).and_then(|node| {
637 Node::ImplItem(ref impl_item) => Some(&impl_item.generics),
638 Node::TraitItem(ref trait_item) => Some(&trait_item.generics),
639 Node::Item(ref item) => {
641 ItemKind::Fn(_, ref generics, _) |
642 ItemKind::TyAlias(_, ref generics) |
643 ItemKind::Enum(_, ref generics) |
644 ItemKind::Struct(_, ref generics) |
645 ItemKind::Union(_, ref generics) |
646 ItemKind::Trait(_, _, ref generics, ..) |
647 ItemKind::TraitAlias(ref generics, _) |
648 ItemKind::Impl(_, _, _, ref generics, ..) => Some(generics),
657 /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
658 pub fn find(&self, hir_id: HirId) -> Option<Node<'hir>> {
659 let result = self.find_entry(hir_id).and_then(|entry| {
660 if let Node::Crate = entry.node {
666 if result.is_some() {
672 /// Similar to `get_parent`; returns the parent HIR Id, or just `hir_id` if there
673 /// is no parent. Note that the parent may be `CRATE_HIR_ID`, which is not itself
674 /// present in the map, so passing the return value of `get_parent_node` to
675 /// `get` may in fact panic.
676 /// This function returns the immediate parent in the HIR, whereas `get_parent`
677 /// returns the enclosing item. Note that this might not be the actual parent
678 /// node in the HIR -- some kinds of nodes are not in the map and these will
679 /// never appear as the parent node. Thus, you can always walk the parent nodes
680 /// from a node to the root of the HIR (unless you get back the same ID here,
681 /// which can happen if the ID is not in the map itself or is just weird).
682 pub fn get_parent_node(&self, hir_id: HirId) -> HirId {
683 if self.dep_graph.is_fully_enabled() {
684 let hir_id_owner = hir_id.owner;
685 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
686 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
689 self.find_entry(hir_id)
690 .and_then(|x| x.parent_node())
694 /// Checks if the node is an argument. An argument is a local variable whose
695 /// immediate parent is an item or a closure.
696 pub fn is_argument(&self, id: HirId) -> bool {
697 match self.find(id) {
698 Some(Node::Binding(_)) => (),
701 match self.find(self.get_parent_node(id)) {
702 Some(Node::Item(_)) |
703 Some(Node::TraitItem(_)) |
704 Some(Node::ImplItem(_)) => true,
705 Some(Node::Expr(e)) => {
707 ExprKind::Closure(..) => true,
715 /// Whether the expression pointed at by `hir_id` belongs to a `const` evaluation context.
716 /// Used exclusively for diagnostics, to avoid suggestion function calls.
717 pub fn is_const_context(&self, hir_id: HirId) -> bool {
718 let parent_id = self.get_parent_item(hir_id);
719 match self.get(parent_id) {
721 kind: ItemKind::Const(..),
724 | Node::TraitItem(&TraitItem {
725 kind: TraitItemKind::Const(..),
728 | Node::ImplItem(&ImplItem {
729 kind: ImplItemKind::Const(..),
734 kind: ItemKind::Static(..),
738 kind: ItemKind::Fn(ref sig, ..),
740 }) => sig.header.constness == Constness::Const,
745 /// Wether `hir_id` corresponds to a `mod` or a crate.
746 pub fn is_hir_id_module(&self, hir_id: HirId) -> bool {
747 match self.lookup(hir_id) {
748 Some(Entry { node: Node::Item(Item { kind: ItemKind::Mod(_), .. }), .. }) |
749 Some(Entry { node: Node::Crate, .. }) => true,
754 /// Retrieves the `HirId` for `id`'s enclosing method, unless there's a
755 /// `while` or `loop` before reaching it, as block tail returns are not
756 /// available in them.
759 /// fn foo(x: usize) -> bool {
761 /// true // If `get_return_block` gets passed the `id` corresponding
762 /// } else { // to this, it will return `foo`'s `HirId`.
769 /// fn foo(x: usize) -> bool {
771 /// true // If `get_return_block` gets passed the `id` corresponding
772 /// } // to this, it will return `None`.
776 pub fn get_return_block(&self, id: HirId) -> Option<HirId> {
777 let mut iter = ParentHirIterator::new(id, &self).peekable();
778 let mut ignore_tail = false;
779 if let Some(entry) = self.find_entry(id) {
780 if let Node::Expr(Expr { kind: ExprKind::Ret(_), .. }) = entry.node {
781 // When dealing with `return` statements, we don't care about climbing only tail
786 while let Some((hir_id, node)) = iter.next() {
787 if let (Some((_, next_node)), false) = (iter.peek(), ignore_tail) {
789 Node::Block(Block { expr: None, .. }) => return None,
790 Node::Block(Block { expr: Some(expr), .. }) => {
791 if hir_id != expr.hir_id {
792 // The current node is not the tail expression of its parent.
801 Node::ForeignItem(_) |
803 Node::Expr(Expr { kind: ExprKind::Closure(..), ..}) |
804 Node::ImplItem(_) => return Some(hir_id),
805 Node::Expr(ref expr) => {
807 // Ignore `return`s on the first iteration
808 ExprKind::Loop(..) | ExprKind::Ret(..) => return None,
812 Node::Local(_) => return None,
819 /// Retrieves the `HirId` for `id`'s parent item, or `id` itself if no
820 /// parent item is in this map. The "parent item" is the closest parent node
821 /// in the HIR which is recorded by the map and is an item, either an item
822 /// in a module, trait, or impl.
823 pub fn get_parent_item(&self, hir_id: HirId) -> HirId {
824 for (hir_id, node) in ParentHirIterator::new(hir_id, &self) {
828 Node::ForeignItem(_) |
830 Node::ImplItem(_) => return hir_id,
837 /// Returns the `DefId` of `id`'s nearest module parent, or `id` itself if no
838 /// module parent is in this map.
839 pub fn get_module_parent(&self, id: HirId) -> DefId {
840 self.local_def_id(self.get_module_parent_node(id))
843 /// Returns the `HirId` of `id`'s nearest module parent, or `id` itself if no
844 /// module parent is in this map.
845 pub fn get_module_parent_node(&self, hir_id: HirId) -> HirId {
846 for (hir_id, node) in ParentHirIterator::new(hir_id, &self) {
847 if let Node::Item(&Item { kind: ItemKind::Mod(_), .. }) = node {
854 /// When on a match arm tail expression or on a match arm, give back the enclosing `match`
857 /// Used by error reporting when there's a type error in a match arm caused by the `match`
858 /// expression needing to be unit.
859 pub fn get_match_if_cause(&self, hir_id: HirId) -> Option<&Expr> {
860 for (_, node) in ParentHirIterator::new(hir_id, &self) {
863 Node::ForeignItem(_) |
865 Node::ImplItem(_) => break,
866 Node::Expr(expr) => match expr.kind {
867 ExprKind::Match(_, _, _) => return Some(expr),
870 Node::Stmt(stmt) => match stmt.kind {
871 StmtKind::Local(_) => break,
880 /// Returns the nearest enclosing scope. A scope is roughly an item or block.
881 pub fn get_enclosing_scope(&self, hir_id: HirId) -> Option<HirId> {
882 for (hir_id, node) in ParentHirIterator::new(hir_id, &self) {
889 | ItemKind::Struct(..)
890 | ItemKind::Union(..)
891 | ItemKind::Trait(..)
892 | ItemKind::Impl(..) => true,
896 Node::ForeignItem(fi) => {
898 ForeignItemKind::Fn(..) => true,
902 Node::TraitItem(ti) => {
904 TraitItemKind::Method(..) => true,
908 Node::ImplItem(ii) => {
910 ImplItemKind::Method(..) => true,
914 Node::Block(_) => true,
923 /// Returns the defining scope for an opaque type definition.
924 pub fn get_defining_scope(&self, id: HirId) -> HirId {
927 scope = self.get_enclosing_scope(scope).unwrap_or(CRATE_HIR_ID);
928 if scope == CRATE_HIR_ID {
931 match self.get(scope) {
934 ItemKind::OpaqueTy(OpaqueTy { impl_trait_fn: None, .. }) => {}
945 pub fn get_parent_did(&self, id: HirId) -> DefId {
946 self.local_def_id(self.get_parent_item(id))
949 pub fn get_foreign_abi(&self, hir_id: HirId) -> Abi {
950 let parent = self.get_parent_item(hir_id);
951 if let Some(entry) = self.find_entry(parent) {
953 node: Node::Item(Item { kind: ItemKind::ForeignMod(ref nm), .. }), .. } = entry
955 self.read(hir_id); // reveals some of the content of a node
959 bug!("expected foreign mod or inlined parent, found {}", self.node_to_string(parent))
962 pub fn expect_item(&self, id: HirId) -> &'hir Item<'hir> {
963 match self.find(id) { // read recorded by `find`
964 Some(Node::Item(item)) => item,
965 _ => bug!("expected item, found {}", self.node_to_string(id))
969 pub fn expect_impl_item(&self, id: HirId) -> &'hir ImplItem<'hir> {
970 match self.find(id) {
971 Some(Node::ImplItem(item)) => item,
972 _ => bug!("expected impl item, found {}", self.node_to_string(id))
976 pub fn expect_trait_item(&self, id: HirId) -> &'hir TraitItem<'hir> {
977 match self.find(id) {
978 Some(Node::TraitItem(item)) => item,
979 _ => bug!("expected trait item, found {}", self.node_to_string(id))
983 pub fn expect_variant_data(&self, id: HirId) -> &'hir VariantData<'hir> {
984 match self.find(id) {
985 Some(Node::Item(i)) => {
987 ItemKind::Struct(ref struct_def, _) |
988 ItemKind::Union(ref struct_def, _) => struct_def,
989 _ => bug!("struct ID bound to non-struct {}", self.node_to_string(id))
992 Some(Node::Variant(variant)) => &variant.data,
993 Some(Node::Ctor(data)) => data,
994 _ => bug!("expected struct or variant, found {}", self.node_to_string(id))
998 pub fn expect_variant(&self, id: HirId) -> &'hir Variant<'hir> {
999 match self.find(id) {
1000 Some(Node::Variant(variant)) => variant,
1001 _ => bug!("expected variant, found {}", self.node_to_string(id)),
1005 pub fn expect_foreign_item(&self, id: HirId) -> &'hir ForeignItem<'hir> {
1006 match self.find(id) {
1007 Some(Node::ForeignItem(item)) => item,
1008 _ => bug!("expected foreign item, found {}", self.node_to_string(id))
1012 pub fn expect_expr(&self, id: HirId) -> &'hir Expr {
1013 match self.find(id) { // read recorded by find
1014 Some(Node::Expr(expr)) => expr,
1015 _ => bug!("expected expr, found {}", self.node_to_string(id))
1019 pub fn opt_name(&self, id: HirId) -> Option<Name> {
1020 Some(match self.get(id) {
1021 Node::Item(i) => i.ident.name,
1022 Node::ForeignItem(fi) => fi.ident.name,
1023 Node::ImplItem(ii) => ii.ident.name,
1024 Node::TraitItem(ti) => ti.ident.name,
1025 Node::Variant(v) => v.ident.name,
1026 Node::Field(f) => f.ident.name,
1027 Node::Lifetime(lt) => lt.name.ident().name,
1028 Node::GenericParam(param) => param.name.ident().name,
1029 Node::Binding(&Pat { kind: PatKind::Binding(_, _, l, _), .. }) => l.name,
1030 Node::Ctor(..) => self.name(self.get_parent_item(id)),
1035 pub fn name(&self, id: HirId) -> Name {
1036 match self.opt_name(id) {
1038 None => bug!("no name for {}", self.node_to_string(id)),
1042 /// Given a node ID, gets a list of attributes associated with the AST
1043 /// corresponding to the node-ID.
1044 pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] {
1045 self.read(id); // reveals attributes on the node
1046 let attrs = match self.find_entry(id).map(|entry| entry.node) {
1047 Some(Node::Param(a)) => Some(&a.attrs[..]),
1048 Some(Node::Local(l)) => Some(&l.attrs[..]),
1049 Some(Node::Item(i)) => Some(&i.attrs[..]),
1050 Some(Node::ForeignItem(fi)) => Some(&fi.attrs[..]),
1051 Some(Node::TraitItem(ref ti)) => Some(&ti.attrs[..]),
1052 Some(Node::ImplItem(ref ii)) => Some(&ii.attrs[..]),
1053 Some(Node::Variant(ref v)) => Some(&v.attrs[..]),
1054 Some(Node::Field(ref f)) => Some(&f.attrs[..]),
1055 Some(Node::Expr(ref e)) => Some(&*e.attrs),
1056 Some(Node::Stmt(ref s)) => Some(s.kind.attrs()),
1057 Some(Node::Arm(ref a)) => Some(&*a.attrs),
1058 Some(Node::GenericParam(param)) => Some(¶m.attrs[..]),
1059 // Unit/tuple structs/variants take the attributes straight from
1060 // the struct/variant definition.
1061 Some(Node::Ctor(..)) => return self.attrs(self.get_parent_item(id)),
1062 Some(Node::Crate) => Some(&self.forest.krate.attrs[..]),
1065 attrs.unwrap_or(&[])
1068 /// Returns an iterator that yields all the hir ids in the map.
1069 fn all_ids<'a>(&'a self) -> impl Iterator<Item = HirId> + 'a {
1070 // This code is a bit awkward because the map is implemented as 2 levels of arrays,
1071 // see the comment on `HirEntryMap`.
1072 // Iterate over all the indices and return a reference to
1073 // local maps and their index given that they exist.
1074 self.map.iter_enumerated().flat_map(move |(owner, local_map)| {
1075 // Iterate over each valid entry in the local map.
1076 local_map.iter_enumerated().filter_map(move |(i, entry)| entry.map(move |_| {
1077 // Reconstruct the `HirId` based on the 3 indices we used to find it.
1086 /// Returns an iterator that yields the node id's with paths that
1087 /// match `parts`. (Requires `parts` is non-empty.)
1089 /// For example, if given `parts` equal to `["bar", "quux"]`, then
1090 /// the iterator will produce node id's for items with paths
1091 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
1092 /// any other such items it can find in the map.
1093 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
1094 -> impl Iterator<Item = NodeId> + 'a {
1095 let nodes = NodesMatchingSuffix {
1097 item_name: parts.last().unwrap(),
1098 in_which: &parts[..parts.len() - 1],
1101 self.all_ids().filter(move |hir| nodes.matches_suffix(*hir)).map(move |hir| {
1102 self.hir_to_node_id(hir)
1106 pub fn span(&self, hir_id: HirId) -> Span {
1107 self.read(hir_id); // reveals span from node
1108 match self.find_entry(hir_id).map(|entry| entry.node) {
1109 Some(Node::Param(param)) => param.span,
1110 Some(Node::Item(item)) => item.span,
1111 Some(Node::ForeignItem(foreign_item)) => foreign_item.span,
1112 Some(Node::TraitItem(trait_method)) => trait_method.span,
1113 Some(Node::ImplItem(impl_item)) => impl_item.span,
1114 Some(Node::Variant(variant)) => variant.span,
1115 Some(Node::Field(field)) => field.span,
1116 Some(Node::AnonConst(constant)) => self.body(constant.body).value.span,
1117 Some(Node::Expr(expr)) => expr.span,
1118 Some(Node::Stmt(stmt)) => stmt.span,
1119 Some(Node::PathSegment(seg)) => seg.ident.span,
1120 Some(Node::Ty(ty)) => ty.span,
1121 Some(Node::TraitRef(tr)) => tr.path.span,
1122 Some(Node::Binding(pat)) => pat.span,
1123 Some(Node::Pat(pat)) => pat.span,
1124 Some(Node::Arm(arm)) => arm.span,
1125 Some(Node::Block(block)) => block.span,
1126 Some(Node::Ctor(..)) => match self.find(
1127 self.get_parent_node(hir_id))
1129 Some(Node::Item(item)) => item.span,
1130 Some(Node::Variant(variant)) => variant.span,
1131 _ => unreachable!(),
1133 Some(Node::Lifetime(lifetime)) => lifetime.span,
1134 Some(Node::GenericParam(param)) => param.span,
1135 Some(Node::Visibility(&Spanned {
1136 node: VisibilityKind::Restricted { ref path, .. }, ..
1138 Some(Node::Visibility(v)) => bug!("unexpected Visibility {:?}", v),
1139 Some(Node::Local(local)) => local.span,
1140 Some(Node::MacroDef(macro_def)) => macro_def.span,
1141 Some(Node::Crate) => self.forest.krate.span,
1142 None => bug!("hir::map::Map::span: id not in map: {:?}", hir_id),
1146 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
1147 self.as_local_hir_id(id).map(|id| self.span(id))
1150 pub fn res_span(&self, res: Res) -> Option<Span> {
1153 Res::Local(id) => Some(self.span(id)),
1154 res => self.span_if_local(res.opt_def_id()?),
1158 pub fn node_to_string(&self, id: HirId) -> String {
1159 hir_id_to_string(self, id, true)
1162 pub fn hir_to_user_string(&self, id: HirId) -> String {
1163 hir_id_to_string(self, id, false)
1166 pub fn hir_to_pretty_string(&self, id: HirId) -> String {
1167 print::to_string(self, |s| s.print_node(self.get(id)))
1171 pub struct NodesMatchingSuffix<'a> {
1173 item_name: &'a String,
1174 in_which: &'a [String],
1177 impl<'a> NodesMatchingSuffix<'a> {
1178 /// Returns `true` only if some suffix of the module path for parent
1179 /// matches `self.in_which`.
1181 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
1182 /// returns true if parent's path ends with the suffix
1183 /// `x_0::x_1::...::x_k`.
1184 fn suffix_matches(&self, parent: HirId) -> bool {
1185 let mut cursor = parent;
1186 for part in self.in_which.iter().rev() {
1187 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
1188 None => return false,
1189 Some((node_id, name)) => (node_id, name),
1191 if mod_name.as_str() != *part {
1194 cursor = self.map.get_parent_item(mod_id);
1198 // Finds the first mod in parent chain for `id`, along with
1201 // If `id` itself is a mod named `m` with parent `p`, then
1202 // returns `Some(id, m, p)`. If `id` has no mod in its parent
1203 // chain, then returns `None`.
1204 fn find_first_mod_parent(map: &Map<'_>, mut id: HirId) -> Option<(HirId, Name)> {
1206 if let Node::Item(item) = map.find(id)? {
1207 if item_is_mod(&item) {
1208 return Some((id, item.ident.name))
1211 let parent = map.get_parent_item(id);
1212 if parent == id { return None }
1216 fn item_is_mod(item: &Item<'_>) -> bool {
1218 ItemKind::Mod(_) => true,
1225 // We are looking at some node `n` with a given name and parent
1226 // id; do their names match what I am seeking?
1227 fn matches_names(&self, parent_of_n: HirId, name: Name) -> bool {
1228 name.as_str() == *self.item_name && self.suffix_matches(parent_of_n)
1231 fn matches_suffix(&self, hir: HirId) -> bool {
1232 let name = match self.map.find_entry(hir).map(|entry| entry.node) {
1233 Some(Node::Item(n)) => n.name(),
1234 Some(Node::ForeignItem(n)) => n.name(),
1235 Some(Node::TraitItem(n)) => n.name(),
1236 Some(Node::ImplItem(n)) => n.name(),
1237 Some(Node::Variant(n)) => n.name(),
1238 Some(Node::Field(n)) => n.name(),
1241 self.matches_names(self.map.get_parent_item(hir), name)
1246 fn name(&self) -> Name;
1249 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
1251 impl Named for Item<'_> { fn name(&self) -> Name { self.ident.name } }
1252 impl Named for ForeignItem<'_> { fn name(&self) -> Name { self.ident.name } }
1253 impl Named for Variant<'_> { fn name(&self) -> Name { self.ident.name } }
1254 impl Named for StructField { fn name(&self) -> Name { self.ident.name } }
1255 impl Named for TraitItem<'_> { fn name(&self) -> Name { self.ident.name } }
1256 impl Named for ImplItem<'_> { fn name(&self) -> Name { self.ident.name } }
1258 pub fn map_crate<'hir>(sess: &crate::session::Session,
1259 cstore: &CrateStoreDyn,
1260 forest: &'hir Forest<'hir>,
1261 definitions: Definitions)
1263 let _prof_timer = sess.prof.generic_activity("build_hir_map");
1265 // Build the reverse mapping of `node_to_hir_id`.
1266 let hir_to_node_id = definitions.node_to_hir_id.iter_enumerated()
1267 .map(|(node_id, &hir_id)| (hir_id, node_id)).collect();
1269 let (map, crate_hash) = {
1270 let hcx = crate::ich::StableHashingContext::new(sess, &forest.krate, &definitions, cstore);
1272 let mut collector = NodeCollector::root(sess,
1278 intravisit::walk_crate(&mut collector, &forest.krate);
1280 let crate_disambiguator = sess.local_crate_disambiguator();
1281 let cmdline_args = sess.opts.dep_tracking_hash();
1282 collector.finalize_and_compute_crate_hash(
1283 crate_disambiguator,
1291 dep_graph: forest.dep_graph.clone(),
1298 time(sess, "validate HIR map", || {
1299 hir_id_validator::check_crate(&map);
1305 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1306 /// except it avoids creating a dependency on the whole crate.
1307 impl<'hir> print::PpAnn for Map<'hir> {
1308 fn nested(&self, state: &mut print::State<'_>, nested: print::Nested) {
1310 Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1311 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1312 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1313 Nested::Body(id) => state.print_expr(&self.body(id).value),
1314 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat)
1319 impl<'a> print::State<'a> {
1320 pub fn print_node(&mut self, node: Node<'_>) {
1322 Node::Param(a) => self.print_param(&a),
1323 Node::Item(a) => self.print_item(&a),
1324 Node::ForeignItem(a) => self.print_foreign_item(&a),
1325 Node::TraitItem(a) => self.print_trait_item(a),
1326 Node::ImplItem(a) => self.print_impl_item(a),
1327 Node::Variant(a) => self.print_variant(&a),
1328 Node::AnonConst(a) => self.print_anon_const(&a),
1329 Node::Expr(a) => self.print_expr(&a),
1330 Node::Stmt(a) => self.print_stmt(&a),
1331 Node::PathSegment(a) => self.print_path_segment(&a),
1332 Node::Ty(a) => self.print_type(&a),
1333 Node::TraitRef(a) => self.print_trait_ref(&a),
1335 Node::Pat(a) => self.print_pat(&a),
1336 Node::Arm(a) => self.print_arm(&a),
1338 // Containing cbox, will be closed by print-block at `}`.
1339 self.cbox(print::INDENT_UNIT);
1340 // Head-ibox, will be closed by print-block after `{`.
1342 self.print_block(&a)
1344 Node::Lifetime(a) => self.print_lifetime(&a),
1345 Node::Visibility(a) => self.print_visibility(&a),
1346 Node::GenericParam(_) => bug!("cannot print Node::GenericParam"),
1347 Node::Field(_) => bug!("cannot print StructField"),
1348 // These cases do not carry enough information in the
1349 // `hir_map` to reconstruct their full structure for pretty
1351 Node::Ctor(..) => bug!("cannot print isolated Ctor"),
1352 Node::Local(a) => self.print_local_decl(&a),
1353 Node::MacroDef(_) => bug!("cannot print MacroDef"),
1354 Node::Crate => bug!("cannot print Crate"),
1359 fn hir_id_to_string(map: &Map<'_>, id: HirId, include_id: bool) -> String {
1360 let id_str = format!(" (hir_id={})", id);
1361 let id_str = if include_id { &id_str[..] } else { "" };
1364 // This functionality is used for debugging, try to use `TyCtxt` to get
1365 // the user-friendly path, otherwise fall back to stringifying `DefPath`.
1366 crate::ty::tls::with_opt(|tcx| {
1367 if let Some(tcx) = tcx {
1368 let def_id = map.local_def_id(id);
1369 tcx.def_path_str(def_id)
1370 } else if let Some(path) = map.def_path_from_hir_id(id) {
1371 path.data.into_iter().map(|elem| {
1372 elem.data.to_string()
1373 }).collect::<Vec<_>>().join("::")
1375 String::from("<missing path>")
1380 match map.find(id) {
1381 Some(Node::Item(item)) => {
1382 let item_str = match item.kind {
1383 ItemKind::ExternCrate(..) => "extern crate",
1384 ItemKind::Use(..) => "use",
1385 ItemKind::Static(..) => "static",
1386 ItemKind::Const(..) => "const",
1387 ItemKind::Fn(..) => "fn",
1388 ItemKind::Mod(..) => "mod",
1389 ItemKind::ForeignMod(..) => "foreign mod",
1390 ItemKind::GlobalAsm(..) => "global asm",
1391 ItemKind::TyAlias(..) => "ty",
1392 ItemKind::OpaqueTy(..) => "opaque type",
1393 ItemKind::Enum(..) => "enum",
1394 ItemKind::Struct(..) => "struct",
1395 ItemKind::Union(..) => "union",
1396 ItemKind::Trait(..) => "trait",
1397 ItemKind::TraitAlias(..) => "trait alias",
1398 ItemKind::Impl(..) => "impl",
1400 format!("{} {}{}", item_str, path_str(), id_str)
1402 Some(Node::ForeignItem(_)) => {
1403 format!("foreign item {}{}", path_str(), id_str)
1405 Some(Node::ImplItem(ii)) => {
1407 ImplItemKind::Const(..) => {
1408 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1410 ImplItemKind::Method(..) => {
1411 format!("method {} in {}{}", ii.ident, path_str(), id_str)
1413 ImplItemKind::TyAlias(_) => {
1414 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1416 ImplItemKind::OpaqueTy(_) => {
1417 format!("assoc opaque type {} in {}{}", ii.ident, path_str(), id_str)
1421 Some(Node::TraitItem(ti)) => {
1422 let kind = match ti.kind {
1423 TraitItemKind::Const(..) => "assoc constant",
1424 TraitItemKind::Method(..) => "trait method",
1425 TraitItemKind::Type(..) => "assoc type",
1428 format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1430 Some(Node::Variant(ref variant)) => {
1431 format!("variant {} in {}{}",
1435 Some(Node::Field(ref field)) => {
1436 format!("field {} in {}{}",
1440 Some(Node::AnonConst(_)) => {
1441 format!("const {}{}", map.hir_to_pretty_string(id), id_str)
1443 Some(Node::Expr(_)) => {
1444 format!("expr {}{}", map.hir_to_pretty_string(id), id_str)
1446 Some(Node::Stmt(_)) => {
1447 format!("stmt {}{}", map.hir_to_pretty_string(id), id_str)
1449 Some(Node::PathSegment(_)) => {
1450 format!("path segment {}{}", map.hir_to_pretty_string(id), id_str)
1452 Some(Node::Ty(_)) => {
1453 format!("type {}{}", map.hir_to_pretty_string(id), id_str)
1455 Some(Node::TraitRef(_)) => {
1456 format!("trait_ref {}{}", map.hir_to_pretty_string(id), id_str)
1458 Some(Node::Binding(_)) => {
1459 format!("local {}{}", map.hir_to_pretty_string(id), id_str)
1461 Some(Node::Pat(_)) => {
1462 format!("pat {}{}", map.hir_to_pretty_string(id), id_str)
1464 Some(Node::Param(_)) => {
1465 format!("param {}{}", map.hir_to_pretty_string(id), id_str)
1467 Some(Node::Arm(_)) => {
1468 format!("arm {}{}", map.hir_to_pretty_string(id), id_str)
1470 Some(Node::Block(_)) => {
1471 format!("block {}{}", map.hir_to_pretty_string(id), id_str)
1473 Some(Node::Local(_)) => {
1474 format!("local {}{}", map.hir_to_pretty_string(id), id_str)
1476 Some(Node::Ctor(..)) => {
1477 format!("ctor {}{}", path_str(), id_str)
1479 Some(Node::Lifetime(_)) => {
1480 format!("lifetime {}{}", map.hir_to_pretty_string(id), id_str)
1482 Some(Node::GenericParam(ref param)) => {
1483 format!("generic_param {:?}{}", param, id_str)
1485 Some(Node::Visibility(ref vis)) => {
1486 format!("visibility {:?}{}", vis, id_str)
1488 Some(Node::MacroDef(_)) => {
1489 format!("macro {}{}", path_str(), id_str)
1491 Some(Node::Crate) => String::from("root_crate"),
1492 None => format!("unknown node{}", id_str),
1496 pub fn provide(providers: &mut Providers<'_>) {
1497 providers.def_kind = |tcx, def_id| {
1498 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
1499 tcx.hir().def_kind(hir_id)
1501 bug!("calling local def_kind query provider for upstream DefId: {:?}",