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};
23 use syntax::ast::{self, Name, NodeId, CRATE_NODE_ID};
24 use syntax::codemap::Spanned;
25 use syntax::ext::base::MacroKind;
29 use hir::print::Nested;
31 use util::nodemap::{DefIdMap, FxHashMap};
33 use arena::TypedArena;
34 use std::cell::RefCell;
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),
59 NodeTraitRef(&'hir TraitRef),
60 NodeBinding(&'hir Pat),
62 NodeBlock(&'hir Block),
63 NodeLocal(&'hir Local),
64 NodeMacroDef(&'hir MacroDef),
66 /// NodeStructCtor represents a tuple struct.
67 NodeStructCtor(&'hir VariantData),
69 NodeLifetime(&'hir Lifetime),
70 NodeTyParam(&'hir TyParam),
71 NodeVisibility(&'hir Visibility),
74 /// Represents an entry and its parent NodeID.
75 /// The odd layout is to bring down the total size.
76 #[derive(Copy, Debug)]
78 /// Placeholder for holes in the map.
81 /// All the node types, with a parent ID.
82 EntryItem(NodeId, DepNodeIndex, &'hir Item),
83 EntryForeignItem(NodeId, DepNodeIndex, &'hir ForeignItem),
84 EntryTraitItem(NodeId, DepNodeIndex, &'hir TraitItem),
85 EntryImplItem(NodeId, DepNodeIndex, &'hir ImplItem),
86 EntryVariant(NodeId, DepNodeIndex, &'hir Variant),
87 EntryField(NodeId, DepNodeIndex, &'hir StructField),
88 EntryExpr(NodeId, DepNodeIndex, &'hir Expr),
89 EntryStmt(NodeId, DepNodeIndex, &'hir Stmt),
90 EntryTy(NodeId, DepNodeIndex, &'hir Ty),
91 EntryTraitRef(NodeId, DepNodeIndex, &'hir TraitRef),
92 EntryBinding(NodeId, DepNodeIndex, &'hir Pat),
93 EntryPat(NodeId, DepNodeIndex, &'hir Pat),
94 EntryBlock(NodeId, DepNodeIndex, &'hir Block),
95 EntryStructCtor(NodeId, DepNodeIndex, &'hir VariantData),
96 EntryLifetime(NodeId, DepNodeIndex, &'hir Lifetime),
97 EntryTyParam(NodeId, DepNodeIndex, &'hir TyParam),
98 EntryVisibility(NodeId, DepNodeIndex, &'hir Visibility),
99 EntryLocal(NodeId, DepNodeIndex, &'hir Local),
101 EntryMacroDef(DepNodeIndex, &'hir MacroDef),
103 /// Roots for node trees. The DepNodeIndex is the dependency node of the
104 /// crate's root module.
105 RootCrate(DepNodeIndex),
108 impl<'hir> Clone for MapEntry<'hir> {
109 fn clone(&self) -> MapEntry<'hir> {
114 impl<'hir> MapEntry<'hir> {
115 fn parent_node(self) -> Option<NodeId> {
117 EntryItem(id, _, _) => id,
118 EntryForeignItem(id, _, _) => id,
119 EntryTraitItem(id, _, _) => id,
120 EntryImplItem(id, _, _) => id,
121 EntryVariant(id, _, _) => id,
122 EntryField(id, _, _) => id,
123 EntryExpr(id, _, _) => id,
124 EntryStmt(id, _, _) => id,
125 EntryTy(id, _, _) => id,
126 EntryTraitRef(id, _, _) => id,
127 EntryBinding(id, _, _) => id,
128 EntryPat(id, _, _) => id,
129 EntryBlock(id, _, _) => id,
130 EntryStructCtor(id, _, _) => id,
131 EntryLifetime(id, _, _) => id,
132 EntryTyParam(id, _, _) => id,
133 EntryVisibility(id, _, _) => id,
134 EntryLocal(id, _, _) => id,
138 RootCrate(_) => return None,
142 fn to_node(self) -> Option<Node<'hir>> {
144 EntryItem(_, _, n) => NodeItem(n),
145 EntryForeignItem(_, _, n) => NodeForeignItem(n),
146 EntryTraitItem(_, _, n) => NodeTraitItem(n),
147 EntryImplItem(_, _, n) => NodeImplItem(n),
148 EntryVariant(_, _, n) => NodeVariant(n),
149 EntryField(_, _, n) => NodeField(n),
150 EntryExpr(_, _, n) => NodeExpr(n),
151 EntryStmt(_, _, n) => NodeStmt(n),
152 EntryTy(_, _, n) => NodeTy(n),
153 EntryTraitRef(_, _, n) => NodeTraitRef(n),
154 EntryBinding(_, _, n) => NodeBinding(n),
155 EntryPat(_, _, n) => NodePat(n),
156 EntryBlock(_, _, n) => NodeBlock(n),
157 EntryStructCtor(_, _, n) => NodeStructCtor(n),
158 EntryLifetime(_, _, n) => NodeLifetime(n),
159 EntryTyParam(_, _, n) => NodeTyParam(n),
160 EntryVisibility(_, _, n) => NodeVisibility(n),
161 EntryLocal(_, _, n) => NodeLocal(n),
162 EntryMacroDef(_, n) => NodeMacroDef(n),
165 RootCrate(_) => return None
169 fn associated_body(self) -> Option<BodyId> {
171 EntryItem(_, _, item) => {
174 ItemStatic(.., body) |
175 ItemFn(_, _, _, _, _, body) => Some(body),
180 EntryTraitItem(_, _, item) => {
182 TraitItemKind::Const(_, Some(body)) |
183 TraitItemKind::Method(_, TraitMethod::Provided(body)) => Some(body),
188 EntryImplItem(_, _, item) => {
190 ImplItemKind::Const(_, body) |
191 ImplItemKind::Method(_, body) => Some(body),
196 EntryExpr(_, _, expr) => {
198 ExprClosure(.., body, _, _) => Some(body),
207 fn is_body_owner(self, node_id: NodeId) -> bool {
208 match self.associated_body() {
209 Some(b) => b.node_id == node_id,
215 /// Stores a crate and any number of inlined items from other crates.
218 pub dep_graph: DepGraph,
219 inlined_bodies: TypedArena<Body>
223 pub fn new(krate: Crate, dep_graph: &DepGraph) -> Forest {
226 dep_graph: dep_graph.clone(),
227 inlined_bodies: TypedArena::new()
231 pub fn krate<'hir>(&'hir self) -> &'hir Crate {
232 self.dep_graph.read(DepNode::new_no_params(DepKind::Krate));
237 /// Represents a mapping from Node IDs to AST elements and their parent
240 pub struct Map<'hir> {
241 /// The backing storage for all the AST nodes.
242 pub forest: &'hir Forest,
244 /// Same as the dep_graph in forest, just available with one fewer
245 /// deref. This is a gratuitous micro-optimization.
246 pub dep_graph: DepGraph,
248 /// The SVH of the local crate.
251 /// NodeIds are sequential integers from 0, so we can be
252 /// super-compact by storing them in a vector. Not everything with
253 /// a NodeId is in the map, but empirically the occupancy is about
254 /// 75-80%, so there's not too much overhead (certainly less than
255 /// a hashmap, since they (at the time of writing) have a maximum
256 /// of 75% occupancy).
258 /// Also, indexing is pretty quick when you've got a vector and
259 /// plain old integers.
260 map: Vec<MapEntry<'hir>>,
262 definitions: &'hir Definitions,
264 /// Bodies inlined from other crates are cached here.
265 inlined_bodies: RefCell<DefIdMap<&'hir Body>>,
267 /// The reverse mapping of `node_to_hir_id`.
268 hir_to_node_id: FxHashMap<HirId, NodeId>,
271 impl<'hir> Map<'hir> {
272 /// Registers a read in the dependency graph of the AST node with
273 /// the given `id`. This needs to be called each time a public
274 /// function returns the HIR for a node -- in other words, when it
275 /// "reveals" the content of a node to the caller (who might not
276 /// otherwise have had access to those contents, and hence needs a
277 /// read recorded). If the function just returns a DefId or
278 /// NodeId, no actual content was returned, so no read is needed.
279 pub fn read(&self, id: NodeId) {
280 let entry = self.map[id.as_usize()];
282 EntryItem(_, dep_node_index, _) |
283 EntryTraitItem(_, dep_node_index, _) |
284 EntryImplItem(_, dep_node_index, _) |
285 EntryVariant(_, dep_node_index, _) |
286 EntryForeignItem(_, dep_node_index, _) |
287 EntryField(_, dep_node_index, _) |
288 EntryStmt(_, dep_node_index, _) |
289 EntryTy(_, dep_node_index, _) |
290 EntryTraitRef(_, dep_node_index, _) |
291 EntryBinding(_, dep_node_index, _) |
292 EntryPat(_, dep_node_index, _) |
293 EntryBlock(_, dep_node_index, _) |
294 EntryStructCtor(_, dep_node_index, _) |
295 EntryLifetime(_, dep_node_index, _) |
296 EntryTyParam(_, dep_node_index, _) |
297 EntryVisibility(_, dep_node_index, _) |
298 EntryExpr(_, dep_node_index, _) |
299 EntryLocal(_, dep_node_index, _) |
300 EntryMacroDef(dep_node_index, _) |
301 RootCrate(dep_node_index) => {
302 self.dep_graph.read_index(dep_node_index);
305 bug!("called HirMap::read() with invalid NodeId")
311 pub fn definitions(&self) -> &'hir Definitions {
315 pub fn def_key(&self, def_id: DefId) -> DefKey {
316 assert!(def_id.is_local());
317 self.definitions.def_key(def_id.index)
320 pub fn def_path_from_id(&self, id: NodeId) -> Option<DefPath> {
321 self.opt_local_def_id(id).map(|def_id| {
322 self.def_path(def_id)
326 pub fn def_path(&self, def_id: DefId) -> DefPath {
327 assert!(def_id.is_local());
328 self.definitions.def_path(def_id.index)
332 pub fn local_def_id(&self, node: NodeId) -> DefId {
333 self.opt_local_def_id(node).unwrap_or_else(|| {
334 bug!("local_def_id: no entry for `{}`, which has a map of `{:?}`",
335 node, self.find_entry(node))
340 pub fn opt_local_def_id(&self, node: NodeId) -> Option<DefId> {
341 self.definitions.opt_local_def_id(node)
345 pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
346 self.definitions.as_local_node_id(def_id)
350 pub fn hir_to_node_id(&self, hir_id: HirId) -> NodeId {
351 self.hir_to_node_id[&hir_id]
355 pub fn node_to_hir_id(&self, node_id: NodeId) -> HirId {
356 self.definitions.node_to_hir_id(node_id)
360 pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> HirId {
361 self.definitions.def_index_to_hir_id(def_index)
365 pub fn def_index_to_node_id(&self, def_index: DefIndex) -> NodeId {
366 self.definitions.as_local_node_id(DefId::local(def_index)).unwrap()
370 pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
371 self.definitions.def_index_to_hir_id(def_id.to_def_id().index)
375 pub fn local_def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
376 self.definitions.as_local_node_id(def_id.to_def_id()).unwrap()
379 pub fn describe_def(&self, node_id: NodeId) -> Option<Def> {
380 let node = if let Some(node) = self.find(node_id) {
389 self.local_def_id(item.id)
393 ItemStatic(_, m, _) => Some(Def::Static(def_id(),
395 ItemConst(..) => Some(Def::Const(def_id())),
396 ItemFn(..) => Some(Def::Fn(def_id())),
397 ItemMod(..) => Some(Def::Mod(def_id())),
398 ItemGlobalAsm(..) => Some(Def::GlobalAsm(def_id())),
399 ItemTy(..) => Some(Def::TyAlias(def_id())),
400 ItemEnum(..) => Some(Def::Enum(def_id())),
401 ItemStruct(..) => Some(Def::Struct(def_id())),
402 ItemUnion(..) => Some(Def::Union(def_id())),
403 ItemTrait(..) => Some(Def::Trait(def_id())),
404 ItemTraitAlias(..) => {
405 bug!("trait aliases are not yet implemented (see issue #41517)")
410 ItemImpl(..) => None,
413 NodeForeignItem(item) => {
414 let def_id = self.local_def_id(item.id);
416 ForeignItemFn(..) => Some(Def::Fn(def_id)),
417 ForeignItemStatic(_, m) => Some(Def::Static(def_id, m)),
418 ForeignItemType => Some(Def::TyForeign(def_id)),
421 NodeTraitItem(item) => {
422 let def_id = self.local_def_id(item.id);
424 TraitItemKind::Const(..) => Some(Def::AssociatedConst(def_id)),
425 TraitItemKind::Method(..) => Some(Def::Method(def_id)),
426 TraitItemKind::Type(..) => Some(Def::AssociatedTy(def_id)),
429 NodeImplItem(item) => {
430 let def_id = self.local_def_id(item.id);
432 ImplItemKind::Const(..) => Some(Def::AssociatedConst(def_id)),
433 ImplItemKind::Method(..) => Some(Def::Method(def_id)),
434 ImplItemKind::Type(..) => Some(Def::AssociatedTy(def_id)),
437 NodeVariant(variant) => {
438 let def_id = self.local_def_id(variant.node.data.id());
439 Some(Def::Variant(def_id))
451 NodeBlock(_) => None,
452 NodeLocal(local) => {
453 Some(Def::Local(local.id))
455 NodeMacroDef(macro_def) => {
456 Some(Def::Macro(self.local_def_id(macro_def.id),
459 NodeTyParam(param) => {
460 Some(Def::TyParam(self.local_def_id(param.id)))
465 fn entry_count(&self) -> usize {
469 fn find_entry(&self, id: NodeId) -> Option<MapEntry<'hir>> {
470 self.map.get(id.as_usize()).cloned()
473 pub fn krate(&self) -> &'hir Crate {
477 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem {
478 self.read(id.node_id);
480 // NB: intentionally bypass `self.forest.krate()` so that we
481 // do not trigger a read of the whole krate here
482 self.forest.krate.trait_item(id)
485 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem {
486 self.read(id.node_id);
488 // NB: intentionally bypass `self.forest.krate()` so that we
489 // do not trigger a read of the whole krate here
490 self.forest.krate.impl_item(id)
493 pub fn body(&self, id: BodyId) -> &'hir Body {
494 self.read(id.node_id);
496 // NB: intentionally bypass `self.forest.krate()` so that we
497 // do not trigger a read of the whole krate here
498 self.forest.krate.body(id)
501 /// Returns the `NodeId` that corresponds to the definition of
502 /// which this is the body of, i.e. a `fn`, `const` or `static`
503 /// item (possibly associated), or a closure, or the body itself
504 /// for embedded constant expressions (e.g. `N` in `[T; N]`).
505 pub fn body_owner(&self, BodyId { node_id }: BodyId) -> NodeId {
506 let parent = self.get_parent_node(node_id);
507 if self.map[parent.as_usize()].is_body_owner(node_id) {
514 pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
515 self.local_def_id(self.body_owner(id))
518 /// Given a node id, returns the `BodyId` associated with it,
519 /// if the node is a body owner, otherwise returns `None`.
520 pub fn maybe_body_owned_by(&self, id: NodeId) -> Option<BodyId> {
521 if let Some(entry) = self.find_entry(id) {
522 if self.dep_graph.is_fully_enabled() {
523 let hir_id_owner = self.node_to_hir_id(id).owner;
524 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
525 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
528 if let Some(body_id) = entry.associated_body() {
529 // For item-like things and closures, the associated
530 // body has its own distinct id, and that is returned
531 // by `associated_body`.
534 // For some expressions, the expression is its own body.
535 if let EntryExpr(_, _, expr) = entry {
536 Some(BodyId { node_id: expr.id })
542 bug!("no entry for id `{}`", id)
546 /// Given a body owner's id, returns the `BodyId` associated with it.
547 pub fn body_owned_by(&self, id: NodeId) -> BodyId {
548 self.maybe_body_owned_by(id).unwrap_or_else(|| {
549 span_bug!(self.span(id), "body_owned_by: {} has no associated body",
550 self.node_to_string(id));
554 pub fn body_owner_kind(&self, id: NodeId) -> BodyOwnerKind {
555 // Handle constants in enum discriminants, types, and repeat expressions.
556 let def_id = self.local_def_id(id);
557 let def_key = self.def_key(def_id);
558 if def_key.disambiguated_data.data == DefPathData::Initializer {
559 return BodyOwnerKind::Const;
563 NodeItem(&Item { node: ItemConst(..), .. }) |
564 NodeTraitItem(&TraitItem { node: TraitItemKind::Const(..), .. }) |
565 NodeImplItem(&ImplItem { node: ImplItemKind::Const(..), .. }) => {
568 NodeItem(&Item { node: ItemStatic(_, m, _), .. }) => {
569 BodyOwnerKind::Static(m)
571 // Default to function if it's not a constant or static.
572 _ => BodyOwnerKind::Fn
576 pub fn ty_param_owner(&self, id: NodeId) -> NodeId {
578 NodeItem(&Item { node: ItemTrait(..), .. }) => id,
579 NodeTyParam(_) => self.get_parent_node(id),
581 bug!("ty_param_owner: {} not a type parameter",
582 self.node_to_string(id))
587 pub fn ty_param_name(&self, id: NodeId) -> Name {
589 NodeItem(&Item { node: ItemTrait(..), .. }) => {
590 keywords::SelfType.name()
592 NodeTyParam(tp) => tp.name,
594 bug!("ty_param_name: {} not a type parameter",
595 self.node_to_string(id))
600 pub fn trait_impls(&self, trait_did: DefId) -> &'hir [NodeId] {
601 self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
603 // NB: intentionally bypass `self.forest.krate()` so that we
604 // do not trigger a read of the whole krate here
605 self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
608 pub fn trait_auto_impl(&self, trait_did: DefId) -> Option<NodeId> {
609 self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
611 // NB: intentionally bypass `self.forest.krate()` so that we
612 // do not trigger a read of the whole krate here
613 self.forest.krate.trait_auto_impl.get(&trait_did).cloned()
616 pub fn trait_is_auto(&self, trait_did: DefId) -> bool {
617 self.trait_auto_impl(trait_did).is_some()
620 /// Get the attributes on the krate. This is preferable to
621 /// invoking `krate.attrs` because it registers a tighter
622 /// dep-graph access.
623 pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
624 let def_path_hash = self.definitions.def_path_hash(CRATE_DEF_INDEX);
626 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::Hir));
627 &self.forest.krate.attrs
630 /// Retrieve the Node corresponding to `id`, panicking if it cannot
632 pub fn get(&self, id: NodeId) -> Node<'hir> {
633 match self.find(id) {
634 Some(node) => node, // read recorded by `find`
635 None => bug!("couldn't find node id {} in the AST map", id)
639 pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
640 self.as_local_node_id(id).map(|id| self.get(id)) // read recorded by `get`
643 /// Retrieve the Node corresponding to `id`, returning None if
645 pub fn find(&self, id: NodeId) -> Option<Node<'hir>> {
646 let result = self.find_entry(id).and_then(|x| x.to_node());
647 if result.is_some() {
653 /// Similar to get_parent, returns the parent node id or id if there is no
654 /// parent. Note that the parent may be CRATE_NODE_ID, which is not itself
655 /// present in the map -- so passing the return value of get_parent_node to
656 /// get may actually panic.
657 /// This function returns the immediate parent in the AST, whereas get_parent
658 /// returns the enclosing item. Note that this might not be the actual parent
659 /// node in the AST - some kinds of nodes are not in the map and these will
660 /// never appear as the parent_node. So you can always walk the parent_nodes
661 /// from a node to the root of the ast (unless you get the same id back here
662 /// that can happen if the id is not in the map itself or is just weird).
663 pub fn get_parent_node(&self, id: NodeId) -> NodeId {
664 if self.dep_graph.is_fully_enabled() {
665 let hir_id_owner = self.node_to_hir_id(id).owner;
666 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
667 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
670 self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
673 /// Check if the node is an argument. An argument is a local variable whose
674 /// immediate parent is an item or a closure.
675 pub fn is_argument(&self, id: NodeId) -> bool {
676 match self.find(id) {
677 Some(NodeBinding(_)) => (),
680 match self.find(self.get_parent_node(id)) {
682 Some(NodeTraitItem(_)) |
683 Some(NodeImplItem(_)) => true,
684 Some(NodeExpr(e)) => {
686 ExprClosure(..) => true,
694 /// If there is some error when walking the parents (e.g., a node does not
695 /// have a parent in the map or a node can't be found), then we return the
696 /// last good node id we found. Note that reaching the crate root (id == 0),
697 /// is not an error, since items in the crate module have the crate root as
699 fn walk_parent_nodes<F, F2>(&self,
703 -> Result<NodeId, NodeId>
704 where F: Fn(&Node<'hir>) -> bool, F2: Fn(&Node<'hir>) -> bool
706 let mut id = start_id;
708 let parent_node = self.get_parent_node(id);
709 if parent_node == CRATE_NODE_ID {
710 return Ok(CRATE_NODE_ID);
712 if parent_node == id {
716 let node = self.find_entry(parent_node);
720 let node = node.unwrap().to_node();
724 return Ok(parent_node);
725 } else if bail_early(node) {
726 return Err(parent_node);
730 return Err(parent_node);
737 /// Retrieve the NodeId for `id`'s enclosing method, unless there's a
738 /// `while` or `loop` before reaching it, as block tail returns are not
739 /// available in them.
742 /// fn foo(x: usize) -> bool {
744 /// true // `get_return_block` gets passed the `id` corresponding
745 /// } else { // to this, it will return `foo`'s `NodeId`.
752 /// fn foo(x: usize) -> bool {
754 /// true // `get_return_block` gets passed the `id` corresponding
755 /// } // to this, it will return `None`.
759 pub fn get_return_block(&self, id: NodeId) -> Option<NodeId> {
760 let match_fn = |node: &Node| {
765 NodeImplItem(_) => true,
769 let match_non_returning_block = |node: &Node| {
771 NodeExpr(ref expr) => {
773 ExprWhile(..) | ExprLoop(..) => true,
781 match self.walk_parent_nodes(id, match_fn, match_non_returning_block) {
787 /// Retrieve the NodeId for `id`'s parent item, or `id` itself if no
788 /// parent item is in this map. The "parent item" is the closest parent node
789 /// in the AST which is recorded by the map and is an item, either an item
790 /// in a module, trait, or impl.
791 pub fn get_parent(&self, id: NodeId) -> NodeId {
792 match self.walk_parent_nodes(id, |node| match *node {
796 NodeImplItem(_) => true,
804 /// Returns the NodeId of `id`'s nearest module parent, or `id` itself if no
805 /// module parent is in this map.
806 pub fn get_module_parent(&self, id: NodeId) -> DefId {
807 let id = match self.walk_parent_nodes(id, |node| match *node {
808 NodeItem(&Item { node: Item_::ItemMod(_), .. }) => true,
814 self.local_def_id(id)
817 /// Returns the nearest enclosing scope. A scope is an item or block.
818 /// FIXME it is not clear to me that all items qualify as scopes - statics
819 /// and associated types probably shouldn't, for example. Behavior in this
820 /// regard should be expected to be highly unstable.
821 pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
822 match self.walk_parent_nodes(id, |node| match *node {
827 NodeBlock(_) => true,
835 pub fn get_parent_did(&self, id: NodeId) -> DefId {
836 self.local_def_id(self.get_parent(id))
839 pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
840 let parent = self.get_parent(id);
841 let abi = match self.find_entry(parent) {
842 Some(EntryItem(_, _, i)) => {
844 ItemForeignMod(ref nm) => Some(nm.abi),
852 self.read(id); // reveals some of the content of a node
855 None => bug!("expected foreign mod or inlined parent, found {}",
856 self.node_to_string(parent))
860 pub fn expect_item(&self, id: NodeId) -> &'hir Item {
861 match self.find(id) { // read recorded by `find`
862 Some(NodeItem(item)) => item,
863 _ => bug!("expected item, found {}", self.node_to_string(id))
867 pub fn expect_impl_item(&self, id: NodeId) -> &'hir ImplItem {
868 match self.find(id) {
869 Some(NodeImplItem(item)) => item,
870 _ => bug!("expected impl item, found {}", self.node_to_string(id))
874 pub fn expect_trait_item(&self, id: NodeId) -> &'hir TraitItem {
875 match self.find(id) {
876 Some(NodeTraitItem(item)) => item,
877 _ => bug!("expected trait item, found {}", self.node_to_string(id))
881 pub fn expect_variant_data(&self, id: NodeId) -> &'hir VariantData {
882 match self.find(id) {
883 Some(NodeItem(i)) => {
885 ItemStruct(ref struct_def, _) |
886 ItemUnion(ref struct_def, _) => struct_def,
888 bug!("struct ID bound to non-struct {}",
889 self.node_to_string(id));
893 Some(NodeStructCtor(data)) => data,
894 Some(NodeVariant(variant)) => &variant.node.data,
896 bug!("expected struct or variant, found {}",
897 self.node_to_string(id));
902 pub fn expect_variant(&self, id: NodeId) -> &'hir Variant {
903 match self.find(id) {
904 Some(NodeVariant(variant)) => variant,
905 _ => bug!("expected variant, found {}", self.node_to_string(id)),
909 pub fn expect_foreign_item(&self, id: NodeId) -> &'hir ForeignItem {
910 match self.find(id) {
911 Some(NodeForeignItem(item)) => item,
912 _ => bug!("expected foreign item, found {}", self.node_to_string(id))
916 pub fn expect_expr(&self, id: NodeId) -> &'hir Expr {
917 match self.find(id) { // read recorded by find
918 Some(NodeExpr(expr)) => expr,
919 _ => bug!("expected expr, found {}", self.node_to_string(id))
923 pub fn get_inlined_body_untracked(&self, def_id: DefId) -> Option<&'hir Body> {
924 self.inlined_bodies.borrow().get(&def_id).cloned()
927 pub fn intern_inlined_body(&self, def_id: DefId, body: Body) -> &'hir Body {
928 let body = self.forest.inlined_bodies.alloc(body);
929 self.inlined_bodies.borrow_mut().insert(def_id, body);
933 /// Returns the name associated with the given NodeId's AST.
934 pub fn name(&self, id: NodeId) -> Name {
936 NodeItem(i) => i.name,
937 NodeForeignItem(i) => i.name,
938 NodeImplItem(ii) => ii.name,
939 NodeTraitItem(ti) => ti.name,
940 NodeVariant(v) => v.node.name,
941 NodeField(f) => f.name,
942 NodeLifetime(lt) => lt.name.name(),
943 NodeTyParam(tp) => tp.name,
944 NodeBinding(&Pat { node: PatKind::Binding(_,_,l,_), .. }) => l.node,
945 NodeStructCtor(_) => self.name(self.get_parent(id)),
946 _ => bug!("no name for {}", self.node_to_string(id))
950 /// Given a node ID, get a list of attributes associated with the AST
951 /// corresponding to the Node ID
952 pub fn attrs(&self, id: NodeId) -> &'hir [ast::Attribute] {
953 self.read(id); // reveals attributes on the node
954 let attrs = match self.find(id) {
955 Some(NodeItem(i)) => Some(&i.attrs[..]),
956 Some(NodeForeignItem(fi)) => Some(&fi.attrs[..]),
957 Some(NodeTraitItem(ref ti)) => Some(&ti.attrs[..]),
958 Some(NodeImplItem(ref ii)) => Some(&ii.attrs[..]),
959 Some(NodeVariant(ref v)) => Some(&v.node.attrs[..]),
960 Some(NodeField(ref f)) => Some(&f.attrs[..]),
961 Some(NodeExpr(ref e)) => Some(&*e.attrs),
962 Some(NodeStmt(ref s)) => Some(s.node.attrs()),
963 // unit/tuple structs take the attributes straight from
964 // the struct definition.
965 Some(NodeStructCtor(_)) => {
966 return self.attrs(self.get_parent(id));
973 /// Returns an iterator that yields the node id's with paths that
974 /// match `parts`. (Requires `parts` is non-empty.)
976 /// For example, if given `parts` equal to `["bar", "quux"]`, then
977 /// the iterator will produce node id's for items with paths
978 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
979 /// any other such items it can find in the map.
980 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
981 -> NodesMatchingSuffix<'a, 'hir> {
982 NodesMatchingSuffix {
984 item_name: parts.last().unwrap(),
985 in_which: &parts[..parts.len() - 1],
990 pub fn span(&self, id: NodeId) -> Span {
991 self.read(id); // reveals span from node
992 match self.find_entry(id) {
993 Some(EntryItem(_, _, item)) => item.span,
994 Some(EntryForeignItem(_, _, foreign_item)) => foreign_item.span,
995 Some(EntryTraitItem(_, _, trait_method)) => trait_method.span,
996 Some(EntryImplItem(_, _, impl_item)) => impl_item.span,
997 Some(EntryVariant(_, _, variant)) => variant.span,
998 Some(EntryField(_, _, field)) => field.span,
999 Some(EntryExpr(_, _, expr)) => expr.span,
1000 Some(EntryStmt(_, _, stmt)) => stmt.span,
1001 Some(EntryTy(_, _, ty)) => ty.span,
1002 Some(EntryTraitRef(_, _, tr)) => tr.path.span,
1003 Some(EntryBinding(_, _, pat)) => pat.span,
1004 Some(EntryPat(_, _, pat)) => pat.span,
1005 Some(EntryBlock(_, _, block)) => block.span,
1006 Some(EntryStructCtor(_, _, _)) => self.expect_item(self.get_parent(id)).span,
1007 Some(EntryLifetime(_, _, lifetime)) => lifetime.span,
1008 Some(EntryTyParam(_, _, ty_param)) => ty_param.span,
1009 Some(EntryVisibility(_, _, &Visibility::Restricted { ref path, .. })) => path.span,
1010 Some(EntryVisibility(_, _, v)) => bug!("unexpected Visibility {:?}", v),
1011 Some(EntryLocal(_, _, local)) => local.span,
1012 Some(EntryMacroDef(_, macro_def)) => macro_def.span,
1014 Some(RootCrate(_)) => self.forest.krate.span,
1015 Some(NotPresent) | None => {
1016 bug!("hir::map::Map::span: id not in map: {:?}", id)
1021 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
1022 self.as_local_node_id(id).map(|id| self.span(id))
1025 pub fn node_to_string(&self, id: NodeId) -> String {
1026 node_id_to_string(self, id, true)
1029 pub fn node_to_user_string(&self, id: NodeId) -> String {
1030 node_id_to_string(self, id, false)
1033 pub fn node_to_pretty_string(&self, id: NodeId) -> String {
1034 print::to_string(self, |s| s.print_node(self.get(id)))
1038 pub struct NodesMatchingSuffix<'a, 'hir:'a> {
1040 item_name: &'a String,
1041 in_which: &'a [String],
1045 impl<'a, 'hir> NodesMatchingSuffix<'a, 'hir> {
1046 /// Returns true only if some suffix of the module path for parent
1047 /// matches `self.in_which`.
1049 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
1050 /// returns true if parent's path ends with the suffix
1051 /// `x_0::x_1::...::x_k`.
1052 fn suffix_matches(&self, parent: NodeId) -> bool {
1053 let mut cursor = parent;
1054 for part in self.in_which.iter().rev() {
1055 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
1056 None => return false,
1057 Some((node_id, name)) => (node_id, name),
1059 if mod_name != &**part {
1062 cursor = self.map.get_parent(mod_id);
1066 // Finds the first mod in parent chain for `id`, along with
1069 // If `id` itself is a mod named `m` with parent `p`, then
1070 // returns `Some(id, m, p)`. If `id` has no mod in its parent
1071 // chain, then returns `None`.
1072 fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
1074 match map.find(id)? {
1075 NodeItem(item) if item_is_mod(&item) =>
1076 return Some((id, item.name)),
1079 let parent = map.get_parent(id);
1080 if parent == id { return None }
1084 fn item_is_mod(item: &Item) -> bool {
1093 // We are looking at some node `n` with a given name and parent
1094 // id; do their names match what I am seeking?
1095 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
1096 name == &**self.item_name && self.suffix_matches(parent_of_n)
1100 impl<'a, 'hir> Iterator for NodesMatchingSuffix<'a, 'hir> {
1103 fn next(&mut self) -> Option<NodeId> {
1106 if idx.as_usize() >= self.map.entry_count() {
1109 self.idx = NodeId::from_u32(self.idx.as_u32() + 1);
1110 let name = match self.map.find_entry(idx) {
1111 Some(EntryItem(_, _, n)) => n.name(),
1112 Some(EntryForeignItem(_, _, n))=> n.name(),
1113 Some(EntryTraitItem(_, _, n)) => n.name(),
1114 Some(EntryImplItem(_, _, n)) => n.name(),
1115 Some(EntryVariant(_, _, n)) => n.name(),
1116 Some(EntryField(_, _, n)) => n.name(),
1119 if self.matches_names(self.map.get_parent(idx), name) {
1127 fn name(&self) -> Name;
1130 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
1132 impl Named for Item { fn name(&self) -> Name { self.name } }
1133 impl Named for ForeignItem { fn name(&self) -> Name { self.name } }
1134 impl Named for Variant_ { fn name(&self) -> Name { self.name } }
1135 impl Named for StructField { fn name(&self) -> Name { self.name } }
1136 impl Named for TraitItem { fn name(&self) -> Name { self.name } }
1137 impl Named for ImplItem { fn name(&self) -> Name { self.name } }
1139 pub fn map_crate<'hir>(sess: &::session::Session,
1140 cstore: &dyn ::middle::cstore::CrateStore,
1141 forest: &'hir mut Forest,
1142 definitions: &'hir Definitions)
1144 let (map, crate_hash) = {
1145 let hcx = ::ich::StableHashingContext::new(sess, &forest.krate, definitions, cstore);
1147 let mut collector = NodeCollector::root(&forest.krate,
1151 intravisit::walk_crate(&mut collector, &forest.krate);
1153 let crate_disambiguator = sess.local_crate_disambiguator();
1154 let cmdline_args = sess.opts.dep_tracking_hash();
1155 collector.finalize_and_compute_crate_hash(crate_disambiguator,
1161 if log_enabled!(::log::Level::Debug) {
1162 // This only makes sense for ordered stores; note the
1163 // enumerate to count the number of entries.
1164 let (entries_less_1, _) = map.iter().filter(|&x| {
1166 NotPresent => false,
1169 }).enumerate().last().expect("AST map was empty after folding?");
1171 let entries = entries_less_1 + 1;
1172 let vector_length = map.len();
1173 debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
1174 entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
1177 // Build the reverse mapping of `node_to_hir_id`.
1178 let hir_to_node_id = definitions.node_to_hir_id.iter_enumerated()
1179 .map(|(node_id, &hir_id)| (hir_id, node_id)).collect();
1183 dep_graph: forest.dep_graph.clone(),
1188 inlined_bodies: RefCell::new(DefIdMap()),
1191 hir_id_validator::check_crate(&map);
1196 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1197 /// except it avoids creating a dependency on the whole crate.
1198 impl<'hir> print::PpAnn for Map<'hir> {
1199 fn nested(&self, state: &mut print::State, nested: print::Nested) -> io::Result<()> {
1201 Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1202 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1203 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1204 Nested::Body(id) => state.print_expr(&self.body(id).value),
1205 Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
1210 impl<'a> print::State<'a> {
1211 pub fn print_node(&mut self, node: Node) -> io::Result<()> {
1213 NodeItem(a) => self.print_item(&a),
1214 NodeForeignItem(a) => self.print_foreign_item(&a),
1215 NodeTraitItem(a) => self.print_trait_item(a),
1216 NodeImplItem(a) => self.print_impl_item(a),
1217 NodeVariant(a) => self.print_variant(&a),
1218 NodeExpr(a) => self.print_expr(&a),
1219 NodeStmt(a) => self.print_stmt(&a),
1220 NodeTy(a) => self.print_type(&a),
1221 NodeTraitRef(a) => self.print_trait_ref(&a),
1223 NodePat(a) => self.print_pat(&a),
1225 use syntax::print::pprust::PrintState;
1227 // containing cbox, will be closed by print-block at }
1228 self.cbox(print::indent_unit)?;
1229 // head-ibox, will be closed by print-block after {
1231 self.print_block(&a)
1233 NodeLifetime(a) => self.print_lifetime(&a),
1234 NodeVisibility(a) => self.print_visibility(&a),
1235 NodeTyParam(_) => bug!("cannot print TyParam"),
1236 NodeField(_) => bug!("cannot print StructField"),
1237 // these cases do not carry enough information in the
1238 // hir_map to reconstruct their full structure for pretty
1240 NodeStructCtor(_) => bug!("cannot print isolated StructCtor"),
1241 NodeLocal(a) => self.print_local_decl(&a),
1242 NodeMacroDef(_) => bug!("cannot print MacroDef"),
1247 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
1248 let id_str = format!(" (id={})", id);
1249 let id_str = if include_id { &id_str[..] } else { "" };
1252 // This functionality is used for debugging, try to use TyCtxt to get
1253 // the user-friendly path, otherwise fall back to stringifying DefPath.
1254 ::ty::tls::with_opt(|tcx| {
1255 if let Some(tcx) = tcx {
1256 tcx.node_path_str(id)
1257 } else if let Some(path) = map.def_path_from_id(id) {
1258 path.data.into_iter().map(|elem| {
1259 elem.data.to_string()
1260 }).collect::<Vec<_>>().join("::")
1262 String::from("<missing path>")
1267 match map.find(id) {
1268 Some(NodeItem(item)) => {
1269 let item_str = match item.node {
1270 ItemExternCrate(..) => "extern crate",
1271 ItemUse(..) => "use",
1272 ItemStatic(..) => "static",
1273 ItemConst(..) => "const",
1275 ItemMod(..) => "mod",
1276 ItemForeignMod(..) => "foreign mod",
1277 ItemGlobalAsm(..) => "global asm",
1279 ItemEnum(..) => "enum",
1280 ItemStruct(..) => "struct",
1281 ItemUnion(..) => "union",
1282 ItemTrait(..) => "trait",
1283 ItemTraitAlias(..) => "trait alias",
1284 ItemImpl(..) => "impl",
1286 format!("{} {}{}", item_str, path_str(), id_str)
1288 Some(NodeForeignItem(_)) => {
1289 format!("foreign item {}{}", path_str(), id_str)
1291 Some(NodeImplItem(ii)) => {
1293 ImplItemKind::Const(..) => {
1294 format!("assoc const {} in {}{}", ii.name, path_str(), id_str)
1296 ImplItemKind::Method(..) => {
1297 format!("method {} in {}{}", ii.name, path_str(), id_str)
1299 ImplItemKind::Type(_) => {
1300 format!("assoc type {} in {}{}", ii.name, path_str(), id_str)
1304 Some(NodeTraitItem(ti)) => {
1305 let kind = match ti.node {
1306 TraitItemKind::Const(..) => "assoc constant",
1307 TraitItemKind::Method(..) => "trait method",
1308 TraitItemKind::Type(..) => "assoc type",
1311 format!("{} {} in {}{}", kind, ti.name, path_str(), id_str)
1313 Some(NodeVariant(ref variant)) => {
1314 format!("variant {} in {}{}",
1318 Some(NodeField(ref field)) => {
1319 format!("field {} in {}{}",
1323 Some(NodeExpr(_)) => {
1324 format!("expr {}{}", map.node_to_pretty_string(id), id_str)
1326 Some(NodeStmt(_)) => {
1327 format!("stmt {}{}", map.node_to_pretty_string(id), id_str)
1329 Some(NodeTy(_)) => {
1330 format!("type {}{}", map.node_to_pretty_string(id), id_str)
1332 Some(NodeTraitRef(_)) => {
1333 format!("trait_ref {}{}", map.node_to_pretty_string(id), id_str)
1335 Some(NodeBinding(_)) => {
1336 format!("local {}{}", map.node_to_pretty_string(id), id_str)
1338 Some(NodePat(_)) => {
1339 format!("pat {}{}", map.node_to_pretty_string(id), id_str)
1341 Some(NodeBlock(_)) => {
1342 format!("block {}{}", map.node_to_pretty_string(id), id_str)
1344 Some(NodeLocal(_)) => {
1345 format!("local {}{}", map.node_to_pretty_string(id), id_str)
1347 Some(NodeStructCtor(_)) => {
1348 format!("struct_ctor {}{}", path_str(), id_str)
1350 Some(NodeLifetime(_)) => {
1351 format!("lifetime {}{}", map.node_to_pretty_string(id), id_str)
1353 Some(NodeTyParam(ref ty_param)) => {
1354 format!("typaram {:?}{}", ty_param, id_str)
1356 Some(NodeVisibility(ref vis)) => {
1357 format!("visibility {:?}{}", vis, id_str)
1359 Some(NodeMacroDef(_)) => {
1360 format!("macro {}{}", path_str(), id_str)
1363 format!("unknown node{}", id_str)
1368 pub fn describe_def(tcx: TyCtxt, def_id: DefId) -> Option<Def> {
1369 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1370 tcx.hir.describe_def(node_id)
1372 bug!("Calling local describe_def query provider for upstream DefId: {:?}",