1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::Node::*;
12 use self::MapEntry::*;
13 use self::collector::NodeCollector;
14 pub use self::def_collector::{DefCollector, MacroInvocationData};
15 pub use self::definitions::{Definitions, DefKey, DefPath, DefPathData,
16 DisambiguatedDefPathData, DefPathHash};
18 use dep_graph::{DepGraph, DepNode, DepKind, DepNodeIndex};
20 use hir::def_id::{CRATE_DEF_INDEX, DefId, LocalDefId, DefIndexAddressSpace};
22 use middle::cstore::CrateStore;
24 use rustc_target::spec::abi::Abi;
25 use syntax::ast::{self, Name, NodeId, CRATE_NODE_ID};
26 use syntax::codemap::Spanned;
27 use syntax::ext::base::MacroKind;
28 use syntax_pos::{Span, DUMMY_SP};
31 use hir::print::Nested;
33 use util::nodemap::FxHashMap;
45 pub const ITEM_LIKE_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::Low;
46 pub const REGULAR_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::High;
48 #[derive(Copy, Clone, Debug)]
51 NodeForeignItem(&'hir ForeignItem),
52 NodeTraitItem(&'hir TraitItem),
53 NodeImplItem(&'hir ImplItem),
54 NodeVariant(&'hir Variant),
55 NodeField(&'hir StructField),
56 NodeAnonConst(&'hir AnonConst),
60 NodeTraitRef(&'hir TraitRef),
61 NodeBinding(&'hir Pat),
63 NodeBlock(&'hir Block),
64 NodeLocal(&'hir Local),
65 NodeMacroDef(&'hir MacroDef),
67 /// NodeStructCtor represents a tuple struct.
68 NodeStructCtor(&'hir VariantData),
70 NodeLifetime(&'hir Lifetime),
71 NodeGenericParam(&'hir GenericParam),
72 NodeVisibility(&'hir Visibility),
75 /// Represents an entry and its parent NodeID.
76 /// The odd layout is to bring down the total size.
77 #[derive(Copy, Debug)]
79 /// Placeholder for holes in the map.
82 /// All the node types, with a parent ID.
83 EntryItem(NodeId, DepNodeIndex, &'hir Item),
84 EntryForeignItem(NodeId, DepNodeIndex, &'hir ForeignItem),
85 EntryTraitItem(NodeId, DepNodeIndex, &'hir TraitItem),
86 EntryImplItem(NodeId, DepNodeIndex, &'hir ImplItem),
87 EntryVariant(NodeId, DepNodeIndex, &'hir Variant),
88 EntryField(NodeId, DepNodeIndex, &'hir StructField),
89 EntryAnonConst(NodeId, DepNodeIndex, &'hir AnonConst),
90 EntryExpr(NodeId, DepNodeIndex, &'hir Expr),
91 EntryStmt(NodeId, DepNodeIndex, &'hir Stmt),
92 EntryTy(NodeId, DepNodeIndex, &'hir Ty),
93 EntryTraitRef(NodeId, DepNodeIndex, &'hir TraitRef),
94 EntryBinding(NodeId, DepNodeIndex, &'hir Pat),
95 EntryPat(NodeId, DepNodeIndex, &'hir Pat),
96 EntryBlock(NodeId, DepNodeIndex, &'hir Block),
97 EntryStructCtor(NodeId, DepNodeIndex, &'hir VariantData),
98 EntryLifetime(NodeId, DepNodeIndex, &'hir Lifetime),
99 EntryGenericParam(NodeId, DepNodeIndex, &'hir GenericParam),
100 EntryVisibility(NodeId, DepNodeIndex, &'hir Visibility),
101 EntryLocal(NodeId, DepNodeIndex, &'hir Local),
103 EntryMacroDef(DepNodeIndex, &'hir MacroDef),
105 /// Roots for node trees. The DepNodeIndex is the dependency node of the
106 /// crate's root module.
107 RootCrate(DepNodeIndex),
110 impl<'hir> Clone for MapEntry<'hir> {
111 fn clone(&self) -> MapEntry<'hir> {
116 impl<'hir> MapEntry<'hir> {
117 fn parent_node(self) -> Option<NodeId> {
119 EntryItem(id, _, _) => id,
120 EntryForeignItem(id, _, _) => id,
121 EntryTraitItem(id, _, _) => id,
122 EntryImplItem(id, _, _) => id,
123 EntryVariant(id, _, _) => id,
124 EntryField(id, _, _) => id,
125 EntryAnonConst(id, _, _) => id,
126 EntryExpr(id, _, _) => id,
127 EntryStmt(id, _, _) => id,
128 EntryTy(id, _, _) => id,
129 EntryTraitRef(id, _, _) => id,
130 EntryBinding(id, _, _) => id,
131 EntryPat(id, _, _) => id,
132 EntryBlock(id, _, _) => id,
133 EntryStructCtor(id, _, _) => id,
134 EntryLifetime(id, _, _) => id,
135 EntryGenericParam(id, _, _) => id,
136 EntryVisibility(id, _, _) => id,
137 EntryLocal(id, _, _) => id,
141 RootCrate(_) => return None,
145 fn to_node(self) -> Option<Node<'hir>> {
147 EntryItem(_, _, n) => NodeItem(n),
148 EntryForeignItem(_, _, n) => NodeForeignItem(n),
149 EntryTraitItem(_, _, n) => NodeTraitItem(n),
150 EntryImplItem(_, _, n) => NodeImplItem(n),
151 EntryVariant(_, _, n) => NodeVariant(n),
152 EntryField(_, _, n) => NodeField(n),
153 EntryAnonConst(_, _, n) => NodeAnonConst(n),
154 EntryExpr(_, _, n) => NodeExpr(n),
155 EntryStmt(_, _, n) => NodeStmt(n),
156 EntryTy(_, _, n) => NodeTy(n),
157 EntryTraitRef(_, _, n) => NodeTraitRef(n),
158 EntryBinding(_, _, n) => NodeBinding(n),
159 EntryPat(_, _, n) => NodePat(n),
160 EntryBlock(_, _, n) => NodeBlock(n),
161 EntryStructCtor(_, _, n) => NodeStructCtor(n),
162 EntryLifetime(_, _, n) => NodeLifetime(n),
163 EntryGenericParam(_, _, n) => NodeGenericParam(n),
164 EntryVisibility(_, _, n) => NodeVisibility(n),
165 EntryLocal(_, _, n) => NodeLocal(n),
166 EntryMacroDef(_, n) => NodeMacroDef(n),
169 RootCrate(_) => return None
173 fn fn_decl(&self) -> Option<&FnDecl> {
175 EntryItem(_, _, ref item) => {
177 ItemFn(ref fn_decl, _, _, _) => Some(&fn_decl),
182 EntryTraitItem(_, _, ref item) => {
184 TraitItemKind::Method(ref method_sig, _) => Some(&method_sig.decl),
189 EntryImplItem(_, _, ref item) => {
191 ImplItemKind::Method(ref method_sig, _) => Some(&method_sig.decl),
196 EntryExpr(_, _, ref expr) => {
198 ExprClosure(_, ref fn_decl, ..) => Some(&fn_decl),
207 fn associated_body(self) -> Option<BodyId> {
209 EntryItem(_, _, item) => {
212 ItemStatic(.., body) |
213 ItemFn(_, _, _, body) => Some(body),
218 EntryTraitItem(_, _, item) => {
220 TraitItemKind::Const(_, Some(body)) |
221 TraitItemKind::Method(_, TraitMethod::Provided(body)) => Some(body),
226 EntryImplItem(_, _, item) => {
228 ImplItemKind::Const(_, body) |
229 ImplItemKind::Method(_, body) => Some(body),
234 EntryAnonConst(_, _, constant) => Some(constant.body),
236 EntryExpr(_, _, expr) => {
238 ExprClosure(.., body, _, _) => Some(body),
247 fn is_body_owner(self, node_id: NodeId) -> bool {
248 match self.associated_body() {
249 Some(b) => b.node_id == node_id,
255 /// Stores a crate and any number of inlined items from other crates.
258 pub dep_graph: DepGraph,
262 pub fn new(krate: Crate, dep_graph: &DepGraph) -> Forest {
265 dep_graph: dep_graph.clone(),
269 pub fn krate<'hir>(&'hir self) -> &'hir Crate {
270 self.dep_graph.read(DepNode::new_no_params(DepKind::Krate));
275 /// Represents a mapping from Node IDs to AST elements and their parent
278 pub struct Map<'hir> {
279 /// The backing storage for all the AST nodes.
280 pub forest: &'hir Forest,
282 /// Same as the dep_graph in forest, just available with one fewer
283 /// deref. This is a gratuitous micro-optimization.
284 pub dep_graph: DepGraph,
286 /// The SVH of the local crate.
289 /// NodeIds are sequential integers from 0, so we can be
290 /// super-compact by storing them in a vector. Not everything with
291 /// a NodeId is in the map, but empirically the occupancy is about
292 /// 75-80%, so there's not too much overhead (certainly less than
293 /// a hashmap, since they (at the time of writing) have a maximum
294 /// of 75% occupancy).
296 /// Also, indexing is pretty quick when you've got a vector and
297 /// plain old integers.
298 map: Vec<MapEntry<'hir>>,
300 definitions: &'hir Definitions,
302 /// The reverse mapping of `node_to_hir_id`.
303 hir_to_node_id: FxHashMap<HirId, NodeId>,
306 impl<'hir> Map<'hir> {
307 /// Registers a read in the dependency graph of the AST node with
308 /// the given `id`. This needs to be called each time a public
309 /// function returns the HIR for a node -- in other words, when it
310 /// "reveals" the content of a node to the caller (who might not
311 /// otherwise have had access to those contents, and hence needs a
312 /// read recorded). If the function just returns a DefId or
313 /// NodeId, no actual content was returned, so no read is needed.
314 pub fn read(&self, id: NodeId) {
315 let entry = self.map[id.as_usize()];
317 EntryItem(_, dep_node_index, _) |
318 EntryTraitItem(_, dep_node_index, _) |
319 EntryImplItem(_, dep_node_index, _) |
320 EntryVariant(_, dep_node_index, _) |
321 EntryForeignItem(_, dep_node_index, _) |
322 EntryField(_, dep_node_index, _) |
323 EntryStmt(_, dep_node_index, _) |
324 EntryTy(_, dep_node_index, _) |
325 EntryTraitRef(_, dep_node_index, _) |
326 EntryBinding(_, dep_node_index, _) |
327 EntryPat(_, dep_node_index, _) |
328 EntryBlock(_, dep_node_index, _) |
329 EntryStructCtor(_, dep_node_index, _) |
330 EntryLifetime(_, dep_node_index, _) |
331 EntryGenericParam(_, dep_node_index, _) |
332 EntryVisibility(_, dep_node_index, _) |
333 EntryAnonConst(_, dep_node_index, _) |
334 EntryExpr(_, dep_node_index, _) |
335 EntryLocal(_, dep_node_index, _) |
336 EntryMacroDef(dep_node_index, _) |
337 RootCrate(dep_node_index) => {
338 self.dep_graph.read_index(dep_node_index);
341 bug!("called HirMap::read() with invalid NodeId")
347 pub fn definitions(&self) -> &'hir Definitions {
351 pub fn def_key(&self, def_id: DefId) -> DefKey {
352 assert!(def_id.is_local());
353 self.definitions.def_key(def_id.index)
356 pub fn def_path_from_id(&self, id: NodeId) -> Option<DefPath> {
357 self.opt_local_def_id(id).map(|def_id| {
358 self.def_path(def_id)
362 pub fn def_path(&self, def_id: DefId) -> DefPath {
363 assert!(def_id.is_local());
364 self.definitions.def_path(def_id.index)
368 pub fn local_def_id(&self, node: NodeId) -> DefId {
369 self.opt_local_def_id(node).unwrap_or_else(|| {
370 bug!("local_def_id: no entry for `{}`, which has a map of `{:?}`",
371 node, self.find_entry(node))
376 pub fn opt_local_def_id(&self, node: NodeId) -> Option<DefId> {
377 self.definitions.opt_local_def_id(node)
381 pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
382 self.definitions.as_local_node_id(def_id)
386 pub fn hir_to_node_id(&self, hir_id: HirId) -> NodeId {
387 self.hir_to_node_id[&hir_id]
391 pub fn node_to_hir_id(&self, node_id: NodeId) -> HirId {
392 self.definitions.node_to_hir_id(node_id)
396 pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> HirId {
397 self.definitions.def_index_to_hir_id(def_index)
401 pub fn def_index_to_node_id(&self, def_index: DefIndex) -> NodeId {
402 self.definitions.as_local_node_id(DefId::local(def_index)).unwrap()
406 pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
407 self.definitions.def_index_to_hir_id(def_id.to_def_id().index)
411 pub fn local_def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
412 self.definitions.as_local_node_id(def_id.to_def_id()).unwrap()
415 pub fn describe_def(&self, node_id: NodeId) -> Option<Def> {
416 let node = if let Some(node) = self.find(node_id) {
425 self.local_def_id(item.id)
429 ItemStatic(_, m, _) => Some(Def::Static(def_id(),
431 ItemConst(..) => Some(Def::Const(def_id())),
432 ItemFn(..) => Some(Def::Fn(def_id())),
433 ItemMod(..) => Some(Def::Mod(def_id())),
434 ItemGlobalAsm(..) => Some(Def::GlobalAsm(def_id())),
435 ItemExistential(..) => Some(Def::Existential(def_id())),
436 ItemTy(..) => Some(Def::TyAlias(def_id())),
437 ItemEnum(..) => Some(Def::Enum(def_id())),
438 ItemStruct(..) => Some(Def::Struct(def_id())),
439 ItemUnion(..) => Some(Def::Union(def_id())),
440 ItemTrait(..) => Some(Def::Trait(def_id())),
441 ItemTraitAlias(..) => {
442 bug!("trait aliases are not yet implemented (see issue #41517)")
447 ItemImpl(..) => None,
450 NodeForeignItem(item) => {
451 let def_id = self.local_def_id(item.id);
453 ForeignItemFn(..) => Some(Def::Fn(def_id)),
454 ForeignItemStatic(_, m) => Some(Def::Static(def_id, m)),
455 ForeignItemType => Some(Def::TyForeign(def_id)),
458 NodeTraitItem(item) => {
459 let def_id = self.local_def_id(item.id);
461 TraitItemKind::Const(..) => Some(Def::AssociatedConst(def_id)),
462 TraitItemKind::Method(..) => Some(Def::Method(def_id)),
463 TraitItemKind::Type(..) => Some(Def::AssociatedTy(def_id)),
466 NodeImplItem(item) => {
467 let def_id = self.local_def_id(item.id);
469 ImplItemKind::Const(..) => Some(Def::AssociatedConst(def_id)),
470 ImplItemKind::Method(..) => Some(Def::Method(def_id)),
471 ImplItemKind::Type(..) => Some(Def::AssociatedTy(def_id)),
474 NodeVariant(variant) => {
475 let def_id = self.local_def_id(variant.node.data.id());
476 Some(Def::Variant(def_id))
489 NodeBlock(_) => None,
490 NodeLocal(local) => {
491 Some(Def::Local(local.id))
493 NodeMacroDef(macro_def) => {
494 Some(Def::Macro(self.local_def_id(macro_def.id),
497 NodeGenericParam(param) => {
498 Some(match param.kind {
499 GenericParamKind::Lifetime { .. } => Def::Local(param.id),
500 GenericParamKind::Type { .. } => Def::TyParam(self.local_def_id(param.id)),
506 fn entry_count(&self) -> usize {
510 fn find_entry(&self, id: NodeId) -> Option<MapEntry<'hir>> {
511 self.map.get(id.as_usize()).cloned()
514 pub fn krate(&self) -> &'hir Crate {
518 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem {
519 self.read(id.node_id);
521 // NB: intentionally bypass `self.forest.krate()` so that we
522 // do not trigger a read of the whole krate here
523 self.forest.krate.trait_item(id)
526 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem {
527 self.read(id.node_id);
529 // NB: intentionally bypass `self.forest.krate()` so that we
530 // do not trigger a read of the whole krate here
531 self.forest.krate.impl_item(id)
534 pub fn body(&self, id: BodyId) -> &'hir Body {
535 self.read(id.node_id);
537 // NB: intentionally bypass `self.forest.krate()` so that we
538 // do not trigger a read of the whole krate here
539 self.forest.krate.body(id)
542 pub fn fn_decl(&self, node_id: ast::NodeId) -> Option<FnDecl> {
543 if let Some(entry) = self.find_entry(node_id) {
544 entry.fn_decl().map(|fd| fd.clone())
546 bug!("no entry for node_id `{}`", node_id)
550 /// Returns the `NodeId` that corresponds to the definition of
551 /// which this is the body of, i.e. a `fn`, `const` or `static`
552 /// item (possibly associated), a closure, or a `hir::AnonConst`.
553 pub fn body_owner(&self, BodyId { node_id }: BodyId) -> NodeId {
554 let parent = self.get_parent_node(node_id);
555 assert!(self.map[parent.as_usize()].is_body_owner(node_id));
559 pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
560 self.local_def_id(self.body_owner(id))
563 /// Given a node id, returns the `BodyId` associated with it,
564 /// if the node is a body owner, otherwise returns `None`.
565 pub fn maybe_body_owned_by(&self, id: NodeId) -> Option<BodyId> {
566 if let Some(entry) = self.find_entry(id) {
567 if self.dep_graph.is_fully_enabled() {
568 let hir_id_owner = self.node_to_hir_id(id).owner;
569 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
570 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
573 entry.associated_body()
575 bug!("no entry for id `{}`", id)
579 /// Given a body owner's id, returns the `BodyId` associated with it.
580 pub fn body_owned_by(&self, id: NodeId) -> BodyId {
581 self.maybe_body_owned_by(id).unwrap_or_else(|| {
582 span_bug!(self.span(id), "body_owned_by: {} has no associated body",
583 self.node_to_string(id));
587 pub fn body_owner_kind(&self, id: NodeId) -> BodyOwnerKind {
589 NodeItem(&Item { node: ItemConst(..), .. }) |
590 NodeTraitItem(&TraitItem { node: TraitItemKind::Const(..), .. }) |
591 NodeImplItem(&ImplItem { node: ImplItemKind::Const(..), .. }) |
592 NodeAnonConst(_) => {
595 NodeItem(&Item { node: ItemStatic(_, m, _), .. }) => {
596 BodyOwnerKind::Static(m)
598 // Default to function if it's not a constant or static.
599 _ => BodyOwnerKind::Fn
603 pub fn ty_param_owner(&self, id: NodeId) -> NodeId {
605 NodeItem(&Item { node: ItemTrait(..), .. }) => id,
606 NodeGenericParam(_) => self.get_parent_node(id),
608 bug!("ty_param_owner: {} not a type parameter",
609 self.node_to_string(id))
614 pub fn ty_param_name(&self, id: NodeId) -> Name {
616 NodeItem(&Item { node: ItemTrait(..), .. }) => {
617 keywords::SelfType.name()
619 NodeGenericParam(param) => param.name.ident().name,
620 _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
624 pub fn trait_impls(&self, trait_did: DefId) -> &'hir [NodeId] {
625 self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
627 // NB: intentionally bypass `self.forest.krate()` so that we
628 // do not trigger a read of the whole krate here
629 self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
632 pub fn trait_auto_impl(&self, trait_did: DefId) -> Option<NodeId> {
633 self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
635 // NB: intentionally bypass `self.forest.krate()` so that we
636 // do not trigger a read of the whole krate here
637 self.forest.krate.trait_auto_impl.get(&trait_did).cloned()
640 pub fn trait_is_auto(&self, trait_did: DefId) -> bool {
641 self.trait_auto_impl(trait_did).is_some()
644 /// Get the attributes on the krate. This is preferable to
645 /// invoking `krate.attrs` because it registers a tighter
646 /// dep-graph access.
647 pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
648 let def_path_hash = self.definitions.def_path_hash(CRATE_DEF_INDEX);
650 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::Hir));
651 &self.forest.krate.attrs
654 /// Retrieve the Node corresponding to `id`, panicking if it cannot
656 pub fn get(&self, id: NodeId) -> Node<'hir> {
657 match self.find(id) {
658 Some(node) => node, // read recorded by `find`
659 None => bug!("couldn't find node id {} in the AST map", id)
663 pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
664 self.as_local_node_id(id).map(|id| self.get(id)) // read recorded by `get`
667 pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics> {
668 self.get_if_local(id).and_then(|node| {
670 NodeImplItem(ref impl_item) => Some(&impl_item.generics),
671 NodeTraitItem(ref trait_item) => Some(&trait_item.generics),
672 NodeItem(ref item) => {
674 ItemFn(_, _, ref generics, _) |
675 ItemTy(_, ref generics) |
676 ItemEnum(_, ref generics) |
677 ItemStruct(_, ref generics) |
678 ItemUnion(_, ref generics) |
679 ItemTrait(_, _, ref generics, ..) |
680 ItemTraitAlias(ref generics, _) |
681 ItemImpl(_, _, _, ref generics, ..) => Some(generics),
690 pub fn get_generics_span(&self, id: DefId) -> Option<Span> {
691 self.get_generics(id).map(|generics| generics.span).filter(|sp| *sp != DUMMY_SP)
694 /// Retrieve the Node corresponding to `id`, returning None if
696 pub fn find(&self, id: NodeId) -> Option<Node<'hir>> {
697 let result = self.find_entry(id).and_then(|x| x.to_node());
698 if result.is_some() {
704 /// Similar to get_parent, returns the parent node id or id if there is no
705 /// parent. Note that the parent may be CRATE_NODE_ID, which is not itself
706 /// present in the map -- so passing the return value of get_parent_node to
707 /// get may actually panic.
708 /// This function returns the immediate parent in the AST, whereas get_parent
709 /// returns the enclosing item. Note that this might not be the actual parent
710 /// node in the AST - some kinds of nodes are not in the map and these will
711 /// never appear as the parent_node. So you can always walk the parent_nodes
712 /// from a node to the root of the ast (unless you get the same id back here
713 /// that can happen if the id is not in the map itself or is just weird).
714 pub fn get_parent_node(&self, id: NodeId) -> NodeId {
715 if self.dep_graph.is_fully_enabled() {
716 let hir_id_owner = self.node_to_hir_id(id).owner;
717 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
718 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
721 self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
724 /// Check if the node is an argument. An argument is a local variable whose
725 /// immediate parent is an item or a closure.
726 pub fn is_argument(&self, id: NodeId) -> bool {
727 match self.find(id) {
728 Some(NodeBinding(_)) => (),
731 match self.find(self.get_parent_node(id)) {
733 Some(NodeTraitItem(_)) |
734 Some(NodeImplItem(_)) => true,
735 Some(NodeExpr(e)) => {
737 ExprClosure(..) => true,
745 /// If there is some error when walking the parents (e.g., a node does not
746 /// have a parent in the map or a node can't be found), then we return the
747 /// last good node id we found. Note that reaching the crate root (id == 0),
748 /// is not an error, since items in the crate module have the crate root as
750 fn walk_parent_nodes<F, F2>(&self,
754 -> Result<NodeId, NodeId>
755 where F: Fn(&Node<'hir>) -> bool, F2: Fn(&Node<'hir>) -> bool
757 let mut id = start_id;
759 let parent_node = self.get_parent_node(id);
760 if parent_node == CRATE_NODE_ID {
761 return Ok(CRATE_NODE_ID);
763 if parent_node == id {
767 let node = self.find_entry(parent_node);
771 let node = node.unwrap().to_node();
775 return Ok(parent_node);
776 } else if bail_early(node) {
777 return Err(parent_node);
781 return Err(parent_node);
788 /// Retrieve the NodeId for `id`'s enclosing method, unless there's a
789 /// `while` or `loop` before reaching it, as block tail returns are not
790 /// available in them.
793 /// fn foo(x: usize) -> bool {
795 /// true // `get_return_block` gets passed the `id` corresponding
796 /// } else { // to this, it will return `foo`'s `NodeId`.
803 /// fn foo(x: usize) -> bool {
805 /// true // `get_return_block` gets passed the `id` corresponding
806 /// } // to this, it will return `None`.
810 pub fn get_return_block(&self, id: NodeId) -> Option<NodeId> {
811 let match_fn = |node: &Node| {
816 NodeImplItem(_) => true,
820 let match_non_returning_block = |node: &Node| {
822 NodeExpr(ref expr) => {
824 ExprWhile(..) | ExprLoop(..) => true,
832 match self.walk_parent_nodes(id, match_fn, match_non_returning_block) {
838 /// Retrieve the NodeId for `id`'s parent item, or `id` itself if no
839 /// parent item is in this map. The "parent item" is the closest parent node
840 /// in the HIR which is recorded by the map and is an item, either an item
841 /// in a module, trait, or impl.
842 pub fn get_parent(&self, id: NodeId) -> NodeId {
843 match self.walk_parent_nodes(id, |node| match *node {
847 NodeImplItem(_) => true,
855 /// Returns the NodeId of `id`'s nearest module parent, or `id` itself if no
856 /// module parent is in this map.
857 pub fn get_module_parent(&self, id: NodeId) -> DefId {
858 let id = match self.walk_parent_nodes(id, |node| match *node {
859 NodeItem(&Item { node: Item_::ItemMod(_), .. }) => true,
865 self.local_def_id(id)
868 /// Returns the nearest enclosing scope. A scope is an item or block.
869 /// FIXME it is not clear to me that all items qualify as scopes - statics
870 /// and associated types probably shouldn't, for example. Behavior in this
871 /// regard should be expected to be highly unstable.
872 pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
873 match self.walk_parent_nodes(id, |node| match *node {
878 NodeBlock(_) => true,
886 pub fn get_parent_did(&self, id: NodeId) -> DefId {
887 self.local_def_id(self.get_parent(id))
890 pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
891 let parent = self.get_parent(id);
892 let abi = match self.find_entry(parent) {
893 Some(EntryItem(_, _, i)) => {
895 ItemForeignMod(ref nm) => Some(nm.abi),
903 self.read(id); // reveals some of the content of a node
906 None => bug!("expected foreign mod or inlined parent, found {}",
907 self.node_to_string(parent))
911 pub fn expect_item(&self, id: NodeId) -> &'hir Item {
912 match self.find(id) { // read recorded by `find`
913 Some(NodeItem(item)) => item,
914 _ => bug!("expected item, found {}", self.node_to_string(id))
918 pub fn expect_impl_item(&self, id: NodeId) -> &'hir ImplItem {
919 match self.find(id) {
920 Some(NodeImplItem(item)) => item,
921 _ => bug!("expected impl item, found {}", self.node_to_string(id))
925 pub fn expect_trait_item(&self, id: NodeId) -> &'hir TraitItem {
926 match self.find(id) {
927 Some(NodeTraitItem(item)) => item,
928 _ => bug!("expected trait item, found {}", self.node_to_string(id))
932 pub fn expect_variant_data(&self, id: NodeId) -> &'hir VariantData {
933 match self.find(id) {
934 Some(NodeItem(i)) => {
936 ItemStruct(ref struct_def, _) |
937 ItemUnion(ref struct_def, _) => struct_def,
939 bug!("struct ID bound to non-struct {}",
940 self.node_to_string(id));
944 Some(NodeStructCtor(data)) => data,
945 Some(NodeVariant(variant)) => &variant.node.data,
947 bug!("expected struct or variant, found {}",
948 self.node_to_string(id));
953 pub fn expect_variant(&self, id: NodeId) -> &'hir Variant {
954 match self.find(id) {
955 Some(NodeVariant(variant)) => variant,
956 _ => bug!("expected variant, found {}", self.node_to_string(id)),
960 pub fn expect_foreign_item(&self, id: NodeId) -> &'hir ForeignItem {
961 match self.find(id) {
962 Some(NodeForeignItem(item)) => item,
963 _ => bug!("expected foreign item, found {}", self.node_to_string(id))
967 pub fn expect_expr(&self, id: NodeId) -> &'hir Expr {
968 match self.find(id) { // read recorded by find
969 Some(NodeExpr(expr)) => expr,
970 _ => bug!("expected expr, found {}", self.node_to_string(id))
974 /// Returns the name associated with the given NodeId's AST.
975 pub fn name(&self, id: NodeId) -> Name {
977 NodeItem(i) => i.name,
978 NodeForeignItem(i) => i.name,
979 NodeImplItem(ii) => ii.ident.name,
980 NodeTraitItem(ti) => ti.ident.name,
981 NodeVariant(v) => v.node.name,
982 NodeField(f) => f.ident.name,
983 NodeLifetime(lt) => lt.name.ident().name,
984 NodeGenericParam(param) => param.name.ident().name,
985 NodeBinding(&Pat { node: PatKind::Binding(_,_,l,_), .. }) => l.name,
986 NodeStructCtor(_) => self.name(self.get_parent(id)),
987 _ => bug!("no name for {}", self.node_to_string(id))
991 /// Given a node ID, get a list of attributes associated with the AST
992 /// corresponding to the Node ID
993 pub fn attrs(&self, id: NodeId) -> &'hir [ast::Attribute] {
994 self.read(id); // reveals attributes on the node
995 let attrs = match self.find(id) {
996 Some(NodeItem(i)) => Some(&i.attrs[..]),
997 Some(NodeForeignItem(fi)) => Some(&fi.attrs[..]),
998 Some(NodeTraitItem(ref ti)) => Some(&ti.attrs[..]),
999 Some(NodeImplItem(ref ii)) => Some(&ii.attrs[..]),
1000 Some(NodeVariant(ref v)) => Some(&v.node.attrs[..]),
1001 Some(NodeField(ref f)) => Some(&f.attrs[..]),
1002 Some(NodeExpr(ref e)) => Some(&*e.attrs),
1003 Some(NodeStmt(ref s)) => Some(s.node.attrs()),
1004 Some(NodeGenericParam(param)) => Some(¶m.attrs[..]),
1005 // unit/tuple structs take the attributes straight from
1006 // the struct definition.
1007 Some(NodeStructCtor(_)) => {
1008 return self.attrs(self.get_parent(id));
1012 attrs.unwrap_or(&[])
1015 /// Returns an iterator that yields the node id's with paths that
1016 /// match `parts`. (Requires `parts` is non-empty.)
1018 /// For example, if given `parts` equal to `["bar", "quux"]`, then
1019 /// the iterator will produce node id's for items with paths
1020 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
1021 /// any other such items it can find in the map.
1022 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
1023 -> NodesMatchingSuffix<'a, 'hir> {
1024 NodesMatchingSuffix {
1026 item_name: parts.last().unwrap(),
1027 in_which: &parts[..parts.len() - 1],
1032 pub fn span(&self, id: NodeId) -> Span {
1033 self.read(id); // reveals span from node
1034 match self.find_entry(id) {
1035 Some(EntryItem(_, _, item)) => item.span,
1036 Some(EntryForeignItem(_, _, foreign_item)) => foreign_item.span,
1037 Some(EntryTraitItem(_, _, trait_method)) => trait_method.span,
1038 Some(EntryImplItem(_, _, impl_item)) => impl_item.span,
1039 Some(EntryVariant(_, _, variant)) => variant.span,
1040 Some(EntryField(_, _, field)) => field.span,
1041 Some(EntryAnonConst(_, _, constant)) => self.body(constant.body).value.span,
1042 Some(EntryExpr(_, _, expr)) => expr.span,
1043 Some(EntryStmt(_, _, stmt)) => stmt.span,
1044 Some(EntryTy(_, _, ty)) => ty.span,
1045 Some(EntryTraitRef(_, _, tr)) => tr.path.span,
1046 Some(EntryBinding(_, _, pat)) => pat.span,
1047 Some(EntryPat(_, _, pat)) => pat.span,
1048 Some(EntryBlock(_, _, block)) => block.span,
1049 Some(EntryStructCtor(_, _, _)) => self.expect_item(self.get_parent(id)).span,
1050 Some(EntryLifetime(_, _, lifetime)) => lifetime.span,
1051 Some(EntryGenericParam(_, _, param)) => param.span,
1052 Some(EntryVisibility(_, _, &Visibility::Restricted { ref path, .. })) => path.span,
1053 Some(EntryVisibility(_, _, v)) => bug!("unexpected Visibility {:?}", v),
1054 Some(EntryLocal(_, _, local)) => local.span,
1055 Some(EntryMacroDef(_, macro_def)) => macro_def.span,
1057 Some(RootCrate(_)) => self.forest.krate.span,
1058 Some(NotPresent) | None => {
1059 bug!("hir::map::Map::span: id not in map: {:?}", id)
1064 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
1065 self.as_local_node_id(id).map(|id| self.span(id))
1068 pub fn node_to_string(&self, id: NodeId) -> String {
1069 node_id_to_string(self, id, true)
1072 pub fn node_to_user_string(&self, id: NodeId) -> String {
1073 node_id_to_string(self, id, false)
1076 pub fn node_to_pretty_string(&self, id: NodeId) -> String {
1077 print::to_string(self, |s| s.print_node(self.get(id)))
1081 pub struct NodesMatchingSuffix<'a, 'hir:'a> {
1083 item_name: &'a String,
1084 in_which: &'a [String],
1088 impl<'a, 'hir> NodesMatchingSuffix<'a, 'hir> {
1089 /// Returns true only if some suffix of the module path for parent
1090 /// matches `self.in_which`.
1092 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
1093 /// returns true if parent's path ends with the suffix
1094 /// `x_0::x_1::...::x_k`.
1095 fn suffix_matches(&self, parent: NodeId) -> bool {
1096 let mut cursor = parent;
1097 for part in self.in_which.iter().rev() {
1098 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
1099 None => return false,
1100 Some((node_id, name)) => (node_id, name),
1102 if mod_name != &**part {
1105 cursor = self.map.get_parent(mod_id);
1109 // Finds the first mod in parent chain for `id`, along with
1112 // If `id` itself is a mod named `m` with parent `p`, then
1113 // returns `Some(id, m, p)`. If `id` has no mod in its parent
1114 // chain, then returns `None`.
1115 fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
1117 match map.find(id)? {
1118 NodeItem(item) if item_is_mod(&item) =>
1119 return Some((id, item.name)),
1122 let parent = map.get_parent(id);
1123 if parent == id { return None }
1127 fn item_is_mod(item: &Item) -> bool {
1136 // We are looking at some node `n` with a given name and parent
1137 // id; do their names match what I am seeking?
1138 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
1139 name == &**self.item_name && self.suffix_matches(parent_of_n)
1143 impl<'a, 'hir> Iterator for NodesMatchingSuffix<'a, 'hir> {
1146 fn next(&mut self) -> Option<NodeId> {
1149 if idx.as_usize() >= self.map.entry_count() {
1152 self.idx = NodeId::from_u32(self.idx.as_u32() + 1);
1153 let name = match self.map.find_entry(idx) {
1154 Some(EntryItem(_, _, n)) => n.name(),
1155 Some(EntryForeignItem(_, _, n))=> n.name(),
1156 Some(EntryTraitItem(_, _, n)) => n.name(),
1157 Some(EntryImplItem(_, _, n)) => n.name(),
1158 Some(EntryVariant(_, _, n)) => n.name(),
1159 Some(EntryField(_, _, n)) => n.name(),
1162 if self.matches_names(self.map.get_parent(idx), name) {
1170 fn name(&self) -> Name;
1173 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
1175 impl Named for Item { fn name(&self) -> Name { self.name } }
1176 impl Named for ForeignItem { fn name(&self) -> Name { self.name } }
1177 impl Named for Variant_ { fn name(&self) -> Name { self.name } }
1178 impl Named for StructField { fn name(&self) -> Name { self.ident.name } }
1179 impl Named for TraitItem { fn name(&self) -> Name { self.ident.name } }
1180 impl Named for ImplItem { fn name(&self) -> Name { self.ident.name } }
1183 pub fn map_crate<'hir>(sess: &::session::Session,
1184 cstore: &dyn CrateStore,
1185 forest: &'hir mut Forest,
1186 definitions: &'hir Definitions)
1188 let (map, crate_hash) = {
1189 let hcx = ::ich::StableHashingContext::new(sess, &forest.krate, definitions, cstore);
1191 let mut collector = NodeCollector::root(&forest.krate,
1195 intravisit::walk_crate(&mut collector, &forest.krate);
1197 let crate_disambiguator = sess.local_crate_disambiguator();
1198 let cmdline_args = sess.opts.dep_tracking_hash();
1199 collector.finalize_and_compute_crate_hash(crate_disambiguator,
1205 if log_enabled!(::log::Level::Debug) {
1206 // This only makes sense for ordered stores; note the
1207 // enumerate to count the number of entries.
1208 let (entries_less_1, _) = map.iter().filter(|&x| {
1210 NotPresent => false,
1213 }).enumerate().last().expect("AST map was empty after folding?");
1215 let entries = entries_less_1 + 1;
1216 let vector_length = map.len();
1217 debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
1218 entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
1221 // Build the reverse mapping of `node_to_hir_id`.
1222 let hir_to_node_id = definitions.node_to_hir_id.iter_enumerated()
1223 .map(|(node_id, &hir_id)| (hir_id, node_id)).collect();
1227 dep_graph: forest.dep_graph.clone(),
1234 hir_id_validator::check_crate(&map);
1239 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1240 /// except it avoids creating a dependency on the whole crate.
1241 impl<'hir> print::PpAnn for Map<'hir> {
1242 fn nested(&self, state: &mut print::State, nested: print::Nested) -> io::Result<()> {
1244 Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1245 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1246 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1247 Nested::Body(id) => state.print_expr(&self.body(id).value),
1248 Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
1253 impl<'a> print::State<'a> {
1254 pub fn print_node(&mut self, node: Node) -> io::Result<()> {
1256 NodeItem(a) => self.print_item(&a),
1257 NodeForeignItem(a) => self.print_foreign_item(&a),
1258 NodeTraitItem(a) => self.print_trait_item(a),
1259 NodeImplItem(a) => self.print_impl_item(a),
1260 NodeVariant(a) => self.print_variant(&a),
1261 NodeAnonConst(a) => self.print_anon_const(&a),
1262 NodeExpr(a) => self.print_expr(&a),
1263 NodeStmt(a) => self.print_stmt(&a),
1264 NodeTy(a) => self.print_type(&a),
1265 NodeTraitRef(a) => self.print_trait_ref(&a),
1267 NodePat(a) => self.print_pat(&a),
1269 use syntax::print::pprust::PrintState;
1271 // containing cbox, will be closed by print-block at }
1272 self.cbox(print::indent_unit)?;
1273 // head-ibox, will be closed by print-block after {
1275 self.print_block(&a)
1277 NodeLifetime(a) => self.print_lifetime(&a),
1278 NodeVisibility(a) => self.print_visibility(&a),
1279 NodeGenericParam(_) => bug!("cannot print NodeGenericParam"),
1280 NodeField(_) => bug!("cannot print StructField"),
1281 // these cases do not carry enough information in the
1282 // hir_map to reconstruct their full structure for pretty
1284 NodeStructCtor(_) => bug!("cannot print isolated StructCtor"),
1285 NodeLocal(a) => self.print_local_decl(&a),
1286 NodeMacroDef(_) => bug!("cannot print MacroDef"),
1291 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
1292 let id_str = format!(" (id={})", id);
1293 let id_str = if include_id { &id_str[..] } else { "" };
1296 // This functionality is used for debugging, try to use TyCtxt to get
1297 // the user-friendly path, otherwise fall back to stringifying DefPath.
1298 ::ty::tls::with_opt(|tcx| {
1299 if let Some(tcx) = tcx {
1300 tcx.node_path_str(id)
1301 } else if let Some(path) = map.def_path_from_id(id) {
1302 path.data.into_iter().map(|elem| {
1303 elem.data.to_string()
1304 }).collect::<Vec<_>>().join("::")
1306 String::from("<missing path>")
1311 match map.find(id) {
1312 Some(NodeItem(item)) => {
1313 let item_str = match item.node {
1314 ItemExternCrate(..) => "extern crate",
1315 ItemUse(..) => "use",
1316 ItemStatic(..) => "static",
1317 ItemConst(..) => "const",
1319 ItemMod(..) => "mod",
1320 ItemForeignMod(..) => "foreign mod",
1321 ItemGlobalAsm(..) => "global asm",
1323 ItemExistential(..) => "existential",
1324 ItemEnum(..) => "enum",
1325 ItemStruct(..) => "struct",
1326 ItemUnion(..) => "union",
1327 ItemTrait(..) => "trait",
1328 ItemTraitAlias(..) => "trait alias",
1329 ItemImpl(..) => "impl",
1331 format!("{} {}{}", item_str, path_str(), id_str)
1333 Some(NodeForeignItem(_)) => {
1334 format!("foreign item {}{}", path_str(), id_str)
1336 Some(NodeImplItem(ii)) => {
1338 ImplItemKind::Const(..) => {
1339 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1341 ImplItemKind::Method(..) => {
1342 format!("method {} in {}{}", ii.ident, path_str(), id_str)
1344 ImplItemKind::Type(_) => {
1345 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1349 Some(NodeTraitItem(ti)) => {
1350 let kind = match ti.node {
1351 TraitItemKind::Const(..) => "assoc constant",
1352 TraitItemKind::Method(..) => "trait method",
1353 TraitItemKind::Type(..) => "assoc type",
1356 format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1358 Some(NodeVariant(ref variant)) => {
1359 format!("variant {} in {}{}",
1363 Some(NodeField(ref field)) => {
1364 format!("field {} in {}{}",
1368 Some(NodeAnonConst(_)) => {
1369 format!("const {}{}", map.node_to_pretty_string(id), id_str)
1371 Some(NodeExpr(_)) => {
1372 format!("expr {}{}", map.node_to_pretty_string(id), id_str)
1374 Some(NodeStmt(_)) => {
1375 format!("stmt {}{}", map.node_to_pretty_string(id), id_str)
1377 Some(NodeTy(_)) => {
1378 format!("type {}{}", map.node_to_pretty_string(id), id_str)
1380 Some(NodeTraitRef(_)) => {
1381 format!("trait_ref {}{}", map.node_to_pretty_string(id), id_str)
1383 Some(NodeBinding(_)) => {
1384 format!("local {}{}", map.node_to_pretty_string(id), id_str)
1386 Some(NodePat(_)) => {
1387 format!("pat {}{}", map.node_to_pretty_string(id), id_str)
1389 Some(NodeBlock(_)) => {
1390 format!("block {}{}", map.node_to_pretty_string(id), id_str)
1392 Some(NodeLocal(_)) => {
1393 format!("local {}{}", map.node_to_pretty_string(id), id_str)
1395 Some(NodeStructCtor(_)) => {
1396 format!("struct_ctor {}{}", path_str(), id_str)
1398 Some(NodeLifetime(_)) => {
1399 format!("lifetime {}{}", map.node_to_pretty_string(id), id_str)
1401 Some(NodeGenericParam(ref param)) => {
1402 format!("generic_param {:?}{}", param, id_str)
1404 Some(NodeVisibility(ref vis)) => {
1405 format!("visibility {:?}{}", vis, id_str)
1407 Some(NodeMacroDef(_)) => {
1408 format!("macro {}{}", path_str(), id_str)
1411 format!("unknown node{}", id_str)
1416 pub fn describe_def(tcx: TyCtxt, def_id: DefId) -> Option<Def> {
1417 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1418 tcx.hir.describe_def(node_id)
1420 bug!("Calling local describe_def query provider for upstream DefId: {:?}",