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;
25 use syntax::ast::{self, Name, NodeId, CRATE_NODE_ID};
26 use syntax::codemap::Spanned;
27 use syntax::ext::base::MacroKind;
31 use hir::print::Nested;
33 use util::nodemap::{DefIdMap, FxHashMap};
35 use arena::TypedArena;
36 use std::cell::RefCell;
47 pub const ITEM_LIKE_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::Low;
48 pub const REGULAR_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::High;
50 #[derive(Copy, Clone, Debug)]
53 NodeForeignItem(&'hir ForeignItem),
54 NodeTraitItem(&'hir TraitItem),
55 NodeImplItem(&'hir ImplItem),
56 NodeVariant(&'hir Variant),
57 NodeField(&'hir StructField),
61 NodeTraitRef(&'hir TraitRef),
62 NodeBinding(&'hir Pat),
64 NodeBlock(&'hir Block),
65 NodeLocal(&'hir Local),
66 NodeMacroDef(&'hir MacroDef),
68 /// NodeStructCtor represents a tuple struct.
69 NodeStructCtor(&'hir VariantData),
71 NodeLifetime(&'hir Lifetime),
72 NodeTyParam(&'hir TyParam),
73 NodeVisibility(&'hir Visibility),
76 /// Represents an entry and its parent NodeID.
77 /// The odd layout is to bring down the total size.
78 #[derive(Copy, Debug)]
80 /// Placeholder for holes in the map.
83 /// All the node types, with a parent ID.
84 EntryItem(NodeId, DepNodeIndex, &'hir Item),
85 EntryForeignItem(NodeId, DepNodeIndex, &'hir ForeignItem),
86 EntryTraitItem(NodeId, DepNodeIndex, &'hir TraitItem),
87 EntryImplItem(NodeId, DepNodeIndex, &'hir ImplItem),
88 EntryVariant(NodeId, DepNodeIndex, &'hir Variant),
89 EntryField(NodeId, DepNodeIndex, &'hir StructField),
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 EntryTyParam(NodeId, DepNodeIndex, &'hir TyParam),
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 EntryExpr(id, _, _) => id,
126 EntryStmt(id, _, _) => id,
127 EntryTy(id, _, _) => id,
128 EntryTraitRef(id, _, _) => id,
129 EntryBinding(id, _, _) => id,
130 EntryPat(id, _, _) => id,
131 EntryBlock(id, _, _) => id,
132 EntryStructCtor(id, _, _) => id,
133 EntryLifetime(id, _, _) => id,
134 EntryTyParam(id, _, _) => id,
135 EntryVisibility(id, _, _) => id,
136 EntryLocal(id, _, _) => id,
140 RootCrate(_) => return None,
144 fn to_node(self) -> Option<Node<'hir>> {
146 EntryItem(_, _, n) => NodeItem(n),
147 EntryForeignItem(_, _, n) => NodeForeignItem(n),
148 EntryTraitItem(_, _, n) => NodeTraitItem(n),
149 EntryImplItem(_, _, n) => NodeImplItem(n),
150 EntryVariant(_, _, n) => NodeVariant(n),
151 EntryField(_, _, n) => NodeField(n),
152 EntryExpr(_, _, n) => NodeExpr(n),
153 EntryStmt(_, _, n) => NodeStmt(n),
154 EntryTy(_, _, n) => NodeTy(n),
155 EntryTraitRef(_, _, n) => NodeTraitRef(n),
156 EntryBinding(_, _, n) => NodeBinding(n),
157 EntryPat(_, _, n) => NodePat(n),
158 EntryBlock(_, _, n) => NodeBlock(n),
159 EntryStructCtor(_, _, n) => NodeStructCtor(n),
160 EntryLifetime(_, _, n) => NodeLifetime(n),
161 EntryTyParam(_, _, n) => NodeTyParam(n),
162 EntryVisibility(_, _, n) => NodeVisibility(n),
163 EntryLocal(_, _, n) => NodeLocal(n),
164 EntryMacroDef(_, n) => NodeMacroDef(n),
167 RootCrate(_) => return None
171 fn associated_body(self) -> Option<BodyId> {
173 EntryItem(_, _, item) => {
176 ItemStatic(.., body) |
177 ItemFn(_, _, _, _, _, body) => Some(body),
182 EntryTraitItem(_, _, item) => {
184 TraitItemKind::Const(_, Some(body)) |
185 TraitItemKind::Method(_, TraitMethod::Provided(body)) => Some(body),
190 EntryImplItem(_, _, item) => {
192 ImplItemKind::Const(_, body) |
193 ImplItemKind::Method(_, body) => Some(body),
198 EntryExpr(_, _, expr) => {
200 ExprClosure(.., body, _, _) => Some(body),
209 fn is_body_owner(self, node_id: NodeId) -> bool {
210 match self.associated_body() {
211 Some(b) => b.node_id == node_id,
217 /// Stores a crate and any number of inlined items from other crates.
220 pub dep_graph: DepGraph,
221 inlined_bodies: TypedArena<Body>
225 pub fn new(krate: Crate, dep_graph: &DepGraph) -> Forest {
228 dep_graph: dep_graph.clone(),
229 inlined_bodies: TypedArena::new()
233 pub fn krate<'hir>(&'hir self) -> &'hir Crate {
234 self.dep_graph.read(DepNode::new_no_params(DepKind::Krate));
239 /// Represents a mapping from Node IDs to AST elements and their parent
242 pub struct Map<'hir> {
243 /// The backing storage for all the AST nodes.
244 pub forest: &'hir Forest,
246 /// Same as the dep_graph in forest, just available with one fewer
247 /// deref. This is a gratuitous micro-optimization.
248 pub dep_graph: DepGraph,
250 /// The SVH of the local crate.
253 /// NodeIds are sequential integers from 0, so we can be
254 /// super-compact by storing them in a vector. Not everything with
255 /// a NodeId is in the map, but empirically the occupancy is about
256 /// 75-80%, so there's not too much overhead (certainly less than
257 /// a hashmap, since they (at the time of writing) have a maximum
258 /// of 75% occupancy).
260 /// Also, indexing is pretty quick when you've got a vector and
261 /// plain old integers.
262 map: Vec<MapEntry<'hir>>,
264 definitions: &'hir Definitions,
266 /// Bodies inlined from other crates are cached here.
267 inlined_bodies: RefCell<DefIdMap<&'hir Body>>,
269 /// The reverse mapping of `node_to_hir_id`.
270 hir_to_node_id: FxHashMap<HirId, NodeId>,
273 impl<'hir> Map<'hir> {
274 /// Registers a read in the dependency graph of the AST node with
275 /// the given `id`. This needs to be called each time a public
276 /// function returns the HIR for a node -- in other words, when it
277 /// "reveals" the content of a node to the caller (who might not
278 /// otherwise have had access to those contents, and hence needs a
279 /// read recorded). If the function just returns a DefId or
280 /// NodeId, no actual content was returned, so no read is needed.
281 pub fn read(&self, id: NodeId) {
282 let entry = self.map[id.as_usize()];
284 EntryItem(_, dep_node_index, _) |
285 EntryTraitItem(_, dep_node_index, _) |
286 EntryImplItem(_, dep_node_index, _) |
287 EntryVariant(_, dep_node_index, _) |
288 EntryForeignItem(_, dep_node_index, _) |
289 EntryField(_, dep_node_index, _) |
290 EntryStmt(_, dep_node_index, _) |
291 EntryTy(_, dep_node_index, _) |
292 EntryTraitRef(_, dep_node_index, _) |
293 EntryBinding(_, dep_node_index, _) |
294 EntryPat(_, dep_node_index, _) |
295 EntryBlock(_, dep_node_index, _) |
296 EntryStructCtor(_, dep_node_index, _) |
297 EntryLifetime(_, dep_node_index, _) |
298 EntryTyParam(_, dep_node_index, _) |
299 EntryVisibility(_, dep_node_index, _) |
300 EntryExpr(_, dep_node_index, _) |
301 EntryLocal(_, dep_node_index, _) |
302 EntryMacroDef(dep_node_index, _) |
303 RootCrate(dep_node_index) => {
304 self.dep_graph.read_index(dep_node_index);
307 bug!("called HirMap::read() with invalid NodeId")
313 pub fn definitions(&self) -> &'hir Definitions {
317 pub fn def_key(&self, def_id: DefId) -> DefKey {
318 assert!(def_id.is_local());
319 self.definitions.def_key(def_id.index)
322 pub fn def_path_from_id(&self, id: NodeId) -> Option<DefPath> {
323 self.opt_local_def_id(id).map(|def_id| {
324 self.def_path(def_id)
328 pub fn def_path(&self, def_id: DefId) -> DefPath {
329 assert!(def_id.is_local());
330 self.definitions.def_path(def_id.index)
334 pub fn local_def_id(&self, node: NodeId) -> DefId {
335 self.opt_local_def_id(node).unwrap_or_else(|| {
336 bug!("local_def_id: no entry for `{}`, which has a map of `{:?}`",
337 node, self.find_entry(node))
342 pub fn opt_local_def_id(&self, node: NodeId) -> Option<DefId> {
343 self.definitions.opt_local_def_id(node)
347 pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
348 self.definitions.as_local_node_id(def_id)
352 pub fn hir_to_node_id(&self, hir_id: HirId) -> NodeId {
353 self.hir_to_node_id[&hir_id]
357 pub fn node_to_hir_id(&self, node_id: NodeId) -> HirId {
358 self.definitions.node_to_hir_id(node_id)
362 pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> HirId {
363 self.definitions.def_index_to_hir_id(def_index)
367 pub fn def_index_to_node_id(&self, def_index: DefIndex) -> NodeId {
368 self.definitions.as_local_node_id(DefId::local(def_index)).unwrap()
372 pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
373 self.definitions.def_index_to_hir_id(def_id.to_def_id().index)
377 pub fn local_def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
378 self.definitions.as_local_node_id(def_id.to_def_id()).unwrap()
381 pub fn describe_def(&self, node_id: NodeId) -> Option<Def> {
382 let node = if let Some(node) = self.find(node_id) {
391 self.local_def_id(item.id)
395 ItemStatic(_, m, _) => Some(Def::Static(def_id(),
397 ItemConst(..) => Some(Def::Const(def_id())),
398 ItemFn(..) => Some(Def::Fn(def_id())),
399 ItemMod(..) => Some(Def::Mod(def_id())),
400 ItemGlobalAsm(..) => Some(Def::GlobalAsm(def_id())),
401 ItemTy(..) => Some(Def::TyAlias(def_id())),
402 ItemEnum(..) => Some(Def::Enum(def_id())),
403 ItemStruct(..) => Some(Def::Struct(def_id())),
404 ItemUnion(..) => Some(Def::Union(def_id())),
405 ItemTrait(..) => Some(Def::Trait(def_id())),
406 ItemTraitAlias(..) => {
407 bug!("trait aliases are not yet implemented (see issue #41517)")
412 ItemImpl(..) => None,
415 NodeForeignItem(item) => {
416 let def_id = self.local_def_id(item.id);
418 ForeignItemFn(..) => Some(Def::Fn(def_id)),
419 ForeignItemStatic(_, m) => Some(Def::Static(def_id, m)),
420 ForeignItemType => Some(Def::TyForeign(def_id)),
423 NodeTraitItem(item) => {
424 let def_id = self.local_def_id(item.id);
426 TraitItemKind::Const(..) => Some(Def::AssociatedConst(def_id)),
427 TraitItemKind::Method(..) => Some(Def::Method(def_id)),
428 TraitItemKind::Type(..) => Some(Def::AssociatedTy(def_id)),
431 NodeImplItem(item) => {
432 let def_id = self.local_def_id(item.id);
434 ImplItemKind::Const(..) => Some(Def::AssociatedConst(def_id)),
435 ImplItemKind::Method(..) => Some(Def::Method(def_id)),
436 ImplItemKind::Type(..) => Some(Def::AssociatedTy(def_id)),
439 NodeVariant(variant) => {
440 let def_id = self.local_def_id(variant.node.data.id());
441 Some(Def::Variant(def_id))
453 NodeBlock(_) => None,
454 NodeLocal(local) => {
455 Some(Def::Local(local.id))
457 NodeMacroDef(macro_def) => {
458 Some(Def::Macro(self.local_def_id(macro_def.id),
461 NodeTyParam(param) => {
462 Some(Def::TyParam(self.local_def_id(param.id)))
467 fn entry_count(&self) -> usize {
471 fn find_entry(&self, id: NodeId) -> Option<MapEntry<'hir>> {
472 self.map.get(id.as_usize()).cloned()
475 pub fn krate(&self) -> &'hir Crate {
479 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem {
480 self.read(id.node_id);
482 // NB: intentionally bypass `self.forest.krate()` so that we
483 // do not trigger a read of the whole krate here
484 self.forest.krate.trait_item(id)
487 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem {
488 self.read(id.node_id);
490 // NB: intentionally bypass `self.forest.krate()` so that we
491 // do not trigger a read of the whole krate here
492 self.forest.krate.impl_item(id)
495 pub fn body(&self, id: BodyId) -> &'hir Body {
496 self.read(id.node_id);
498 // NB: intentionally bypass `self.forest.krate()` so that we
499 // do not trigger a read of the whole krate here
500 self.forest.krate.body(id)
503 /// Returns the `NodeId` that corresponds to the definition of
504 /// which this is the body of, i.e. a `fn`, `const` or `static`
505 /// item (possibly associated), or a closure, or the body itself
506 /// for embedded constant expressions (e.g. `N` in `[T; N]`).
507 pub fn body_owner(&self, BodyId { node_id }: BodyId) -> NodeId {
508 let parent = self.get_parent_node(node_id);
509 if self.map[parent.as_usize()].is_body_owner(node_id) {
516 pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
517 self.local_def_id(self.body_owner(id))
520 /// Given a node id, returns the `BodyId` associated with it,
521 /// if the node is a body owner, otherwise returns `None`.
522 pub fn maybe_body_owned_by(&self, id: NodeId) -> Option<BodyId> {
523 if let Some(entry) = self.find_entry(id) {
524 if self.dep_graph.is_fully_enabled() {
525 let hir_id_owner = self.node_to_hir_id(id).owner;
526 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
527 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
530 if let Some(body_id) = entry.associated_body() {
531 // For item-like things and closures, the associated
532 // body has its own distinct id, and that is returned
533 // by `associated_body`.
536 // For some expressions, the expression is its own body.
537 if let EntryExpr(_, _, expr) = entry {
538 Some(BodyId { node_id: expr.id })
544 bug!("no entry for id `{}`", id)
548 /// Given a body owner's id, returns the `BodyId` associated with it.
549 pub fn body_owned_by(&self, id: NodeId) -> BodyId {
550 self.maybe_body_owned_by(id).unwrap_or_else(|| {
551 span_bug!(self.span(id), "body_owned_by: {} has no associated body",
552 self.node_to_string(id));
556 pub fn body_owner_kind(&self, id: NodeId) -> BodyOwnerKind {
557 // Handle constants in enum discriminants, types, and repeat expressions.
558 let def_id = self.local_def_id(id);
559 let def_key = self.def_key(def_id);
560 if def_key.disambiguated_data.data == DefPathData::Initializer {
561 return BodyOwnerKind::Const;
565 NodeItem(&Item { node: ItemConst(..), .. }) |
566 NodeTraitItem(&TraitItem { node: TraitItemKind::Const(..), .. }) |
567 NodeImplItem(&ImplItem { node: ImplItemKind::Const(..), .. }) => {
570 NodeItem(&Item { node: ItemStatic(_, m, _), .. }) => {
571 BodyOwnerKind::Static(m)
573 // Default to function if it's not a constant or static.
574 _ => BodyOwnerKind::Fn
578 pub fn ty_param_owner(&self, id: NodeId) -> NodeId {
580 NodeItem(&Item { node: ItemTrait(..), .. }) => id,
581 NodeTyParam(_) => self.get_parent_node(id),
583 bug!("ty_param_owner: {} not a type parameter",
584 self.node_to_string(id))
589 pub fn ty_param_name(&self, id: NodeId) -> Name {
591 NodeItem(&Item { node: ItemTrait(..), .. }) => {
592 keywords::SelfType.name()
594 NodeTyParam(tp) => tp.name,
596 bug!("ty_param_name: {} not a type parameter",
597 self.node_to_string(id))
602 pub fn trait_impls(&self, trait_did: DefId) -> &'hir [NodeId] {
603 self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
605 // NB: intentionally bypass `self.forest.krate()` so that we
606 // do not trigger a read of the whole krate here
607 self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
610 pub fn trait_auto_impl(&self, trait_did: DefId) -> Option<NodeId> {
611 self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
613 // NB: intentionally bypass `self.forest.krate()` so that we
614 // do not trigger a read of the whole krate here
615 self.forest.krate.trait_auto_impl.get(&trait_did).cloned()
618 pub fn trait_is_auto(&self, trait_did: DefId) -> bool {
619 self.trait_auto_impl(trait_did).is_some()
622 /// Get the attributes on the krate. This is preferable to
623 /// invoking `krate.attrs` because it registers a tighter
624 /// dep-graph access.
625 pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
626 let def_path_hash = self.definitions.def_path_hash(CRATE_DEF_INDEX);
628 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::Hir));
629 &self.forest.krate.attrs
632 /// Retrieve the Node corresponding to `id`, panicking if it cannot
634 pub fn get(&self, id: NodeId) -> Node<'hir> {
635 match self.find(id) {
636 Some(node) => node, // read recorded by `find`
637 None => bug!("couldn't find node id {} in the AST map", id)
641 pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
642 self.as_local_node_id(id).map(|id| self.get(id)) // read recorded by `get`
645 /// Retrieve the Node corresponding to `id`, returning None if
647 pub fn find(&self, id: NodeId) -> Option<Node<'hir>> {
648 let result = self.find_entry(id).and_then(|x| x.to_node());
649 if result.is_some() {
655 /// Similar to get_parent, returns the parent node id or id if there is no
656 /// parent. Note that the parent may be CRATE_NODE_ID, which is not itself
657 /// present in the map -- so passing the return value of get_parent_node to
658 /// get may actually panic.
659 /// This function returns the immediate parent in the AST, whereas get_parent
660 /// returns the enclosing item. Note that this might not be the actual parent
661 /// node in the AST - some kinds of nodes are not in the map and these will
662 /// never appear as the parent_node. So you can always walk the parent_nodes
663 /// from a node to the root of the ast (unless you get the same id back here
664 /// that can happen if the id is not in the map itself or is just weird).
665 pub fn get_parent_node(&self, id: NodeId) -> NodeId {
666 if self.dep_graph.is_fully_enabled() {
667 let hir_id_owner = self.node_to_hir_id(id).owner;
668 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
669 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
672 self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
675 /// Check if the node is an argument. An argument is a local variable whose
676 /// immediate parent is an item or a closure.
677 pub fn is_argument(&self, id: NodeId) -> bool {
678 match self.find(id) {
679 Some(NodeBinding(_)) => (),
682 match self.find(self.get_parent_node(id)) {
684 Some(NodeTraitItem(_)) |
685 Some(NodeImplItem(_)) => true,
686 Some(NodeExpr(e)) => {
688 ExprClosure(..) => true,
696 /// If there is some error when walking the parents (e.g., a node does not
697 /// have a parent in the map or a node can't be found), then we return the
698 /// last good node id we found. Note that reaching the crate root (id == 0),
699 /// is not an error, since items in the crate module have the crate root as
701 fn walk_parent_nodes<F, F2>(&self,
705 -> Result<NodeId, NodeId>
706 where F: Fn(&Node<'hir>) -> bool, F2: Fn(&Node<'hir>) -> bool
708 let mut id = start_id;
710 let parent_node = self.get_parent_node(id);
711 if parent_node == CRATE_NODE_ID {
712 return Ok(CRATE_NODE_ID);
714 if parent_node == id {
718 let node = self.find_entry(parent_node);
722 let node = node.unwrap().to_node();
726 return Ok(parent_node);
727 } else if bail_early(node) {
728 return Err(parent_node);
732 return Err(parent_node);
739 /// Retrieve the NodeId for `id`'s enclosing method, unless there's a
740 /// `while` or `loop` before reaching it, as block tail returns are not
741 /// available in them.
744 /// fn foo(x: usize) -> bool {
746 /// true // `get_return_block` gets passed the `id` corresponding
747 /// } else { // to this, it will return `foo`'s `NodeId`.
754 /// fn foo(x: usize) -> bool {
756 /// true // `get_return_block` gets passed the `id` corresponding
757 /// } // to this, it will return `None`.
761 pub fn get_return_block(&self, id: NodeId) -> Option<NodeId> {
762 let match_fn = |node: &Node| {
767 NodeImplItem(_) => true,
771 let match_non_returning_block = |node: &Node| {
773 NodeExpr(ref expr) => {
775 ExprWhile(..) | ExprLoop(..) => true,
783 match self.walk_parent_nodes(id, match_fn, match_non_returning_block) {
789 /// Retrieve the NodeId for `id`'s parent item, or `id` itself if no
790 /// parent item is in this map. The "parent item" is the closest parent node
791 /// in the AST which is recorded by the map and is an item, either an item
792 /// in a module, trait, or impl.
793 pub fn get_parent(&self, id: NodeId) -> NodeId {
794 match self.walk_parent_nodes(id, |node| match *node {
798 NodeImplItem(_) => true,
806 /// Returns the NodeId of `id`'s nearest module parent, or `id` itself if no
807 /// module parent is in this map.
808 pub fn get_module_parent(&self, id: NodeId) -> DefId {
809 let id = match self.walk_parent_nodes(id, |node| match *node {
810 NodeItem(&Item { node: Item_::ItemMod(_), .. }) => true,
816 self.local_def_id(id)
819 /// Returns the nearest enclosing scope. A scope is an item or block.
820 /// FIXME it is not clear to me that all items qualify as scopes - statics
821 /// and associated types probably shouldn't, for example. Behavior in this
822 /// regard should be expected to be highly unstable.
823 pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
824 match self.walk_parent_nodes(id, |node| match *node {
829 NodeBlock(_) => true,
837 pub fn get_parent_did(&self, id: NodeId) -> DefId {
838 self.local_def_id(self.get_parent(id))
841 pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
842 let parent = self.get_parent(id);
843 let abi = match self.find_entry(parent) {
844 Some(EntryItem(_, _, i)) => {
846 ItemForeignMod(ref nm) => Some(nm.abi),
854 self.read(id); // reveals some of the content of a node
857 None => bug!("expected foreign mod or inlined parent, found {}",
858 self.node_to_string(parent))
862 pub fn expect_item(&self, id: NodeId) -> &'hir Item {
863 match self.find(id) { // read recorded by `find`
864 Some(NodeItem(item)) => item,
865 _ => bug!("expected item, found {}", self.node_to_string(id))
869 pub fn expect_impl_item(&self, id: NodeId) -> &'hir ImplItem {
870 match self.find(id) {
871 Some(NodeImplItem(item)) => item,
872 _ => bug!("expected impl item, found {}", self.node_to_string(id))
876 pub fn expect_trait_item(&self, id: NodeId) -> &'hir TraitItem {
877 match self.find(id) {
878 Some(NodeTraitItem(item)) => item,
879 _ => bug!("expected trait item, found {}", self.node_to_string(id))
883 pub fn expect_variant_data(&self, id: NodeId) -> &'hir VariantData {
884 match self.find(id) {
885 Some(NodeItem(i)) => {
887 ItemStruct(ref struct_def, _) |
888 ItemUnion(ref struct_def, _) => struct_def,
890 bug!("struct ID bound to non-struct {}",
891 self.node_to_string(id));
895 Some(NodeStructCtor(data)) => data,
896 Some(NodeVariant(variant)) => &variant.node.data,
898 bug!("expected struct or variant, found {}",
899 self.node_to_string(id));
904 pub fn expect_variant(&self, id: NodeId) -> &'hir Variant {
905 match self.find(id) {
906 Some(NodeVariant(variant)) => variant,
907 _ => bug!("expected variant, found {}", self.node_to_string(id)),
911 pub fn expect_foreign_item(&self, id: NodeId) -> &'hir ForeignItem {
912 match self.find(id) {
913 Some(NodeForeignItem(item)) => item,
914 _ => bug!("expected foreign item, found {}", self.node_to_string(id))
918 pub fn expect_expr(&self, id: NodeId) -> &'hir Expr {
919 match self.find(id) { // read recorded by find
920 Some(NodeExpr(expr)) => expr,
921 _ => bug!("expected expr, found {}", self.node_to_string(id))
925 pub fn get_inlined_body_untracked(&self, def_id: DefId) -> Option<&'hir Body> {
926 self.inlined_bodies.borrow().get(&def_id).cloned()
929 pub fn intern_inlined_body(&self, def_id: DefId, body: Body) -> &'hir Body {
930 let body = self.forest.inlined_bodies.alloc(body);
931 self.inlined_bodies.borrow_mut().insert(def_id, body);
935 /// Returns the name associated with the given NodeId's AST.
936 pub fn name(&self, id: NodeId) -> Name {
938 NodeItem(i) => i.name,
939 NodeForeignItem(i) => i.name,
940 NodeImplItem(ii) => ii.name,
941 NodeTraitItem(ti) => ti.name,
942 NodeVariant(v) => v.node.name,
943 NodeField(f) => f.name,
944 NodeLifetime(lt) => lt.name.name(),
945 NodeTyParam(tp) => tp.name,
946 NodeBinding(&Pat { node: PatKind::Binding(_,_,l,_), .. }) => l.node,
947 NodeStructCtor(_) => self.name(self.get_parent(id)),
948 _ => bug!("no name for {}", self.node_to_string(id))
952 /// Given a node ID, get a list of attributes associated with the AST
953 /// corresponding to the Node ID
954 pub fn attrs(&self, id: NodeId) -> &'hir [ast::Attribute] {
955 self.read(id); // reveals attributes on the node
956 let attrs = match self.find(id) {
957 Some(NodeItem(i)) => Some(&i.attrs[..]),
958 Some(NodeForeignItem(fi)) => Some(&fi.attrs[..]),
959 Some(NodeTraitItem(ref ti)) => Some(&ti.attrs[..]),
960 Some(NodeImplItem(ref ii)) => Some(&ii.attrs[..]),
961 Some(NodeVariant(ref v)) => Some(&v.node.attrs[..]),
962 Some(NodeField(ref f)) => Some(&f.attrs[..]),
963 Some(NodeExpr(ref e)) => Some(&*e.attrs),
964 Some(NodeStmt(ref s)) => Some(s.node.attrs()),
965 // unit/tuple structs take the attributes straight from
966 // the struct definition.
967 Some(NodeStructCtor(_)) => {
968 return self.attrs(self.get_parent(id));
975 /// Returns an iterator that yields the node id's with paths that
976 /// match `parts`. (Requires `parts` is non-empty.)
978 /// For example, if given `parts` equal to `["bar", "quux"]`, then
979 /// the iterator will produce node id's for items with paths
980 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
981 /// any other such items it can find in the map.
982 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
983 -> NodesMatchingSuffix<'a, 'hir> {
984 NodesMatchingSuffix {
986 item_name: parts.last().unwrap(),
987 in_which: &parts[..parts.len() - 1],
992 pub fn span(&self, id: NodeId) -> Span {
993 self.read(id); // reveals span from node
994 match self.find_entry(id) {
995 Some(EntryItem(_, _, item)) => item.span,
996 Some(EntryForeignItem(_, _, foreign_item)) => foreign_item.span,
997 Some(EntryTraitItem(_, _, trait_method)) => trait_method.span,
998 Some(EntryImplItem(_, _, impl_item)) => impl_item.span,
999 Some(EntryVariant(_, _, variant)) => variant.span,
1000 Some(EntryField(_, _, field)) => field.span,
1001 Some(EntryExpr(_, _, expr)) => expr.span,
1002 Some(EntryStmt(_, _, stmt)) => stmt.span,
1003 Some(EntryTy(_, _, ty)) => ty.span,
1004 Some(EntryTraitRef(_, _, tr)) => tr.path.span,
1005 Some(EntryBinding(_, _, pat)) => pat.span,
1006 Some(EntryPat(_, _, pat)) => pat.span,
1007 Some(EntryBlock(_, _, block)) => block.span,
1008 Some(EntryStructCtor(_, _, _)) => self.expect_item(self.get_parent(id)).span,
1009 Some(EntryLifetime(_, _, lifetime)) => lifetime.span,
1010 Some(EntryTyParam(_, _, ty_param)) => ty_param.span,
1011 Some(EntryVisibility(_, _, &Visibility::Restricted { ref path, .. })) => path.span,
1012 Some(EntryVisibility(_, _, v)) => bug!("unexpected Visibility {:?}", v),
1013 Some(EntryLocal(_, _, local)) => local.span,
1014 Some(EntryMacroDef(_, macro_def)) => macro_def.span,
1016 Some(RootCrate(_)) => self.forest.krate.span,
1017 Some(NotPresent) | None => {
1018 bug!("hir::map::Map::span: id not in map: {:?}", id)
1023 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
1024 self.as_local_node_id(id).map(|id| self.span(id))
1027 pub fn node_to_string(&self, id: NodeId) -> String {
1028 node_id_to_string(self, id, true)
1031 pub fn node_to_user_string(&self, id: NodeId) -> String {
1032 node_id_to_string(self, id, false)
1035 pub fn node_to_pretty_string(&self, id: NodeId) -> String {
1036 print::to_string(self, |s| s.print_node(self.get(id)))
1040 pub struct NodesMatchingSuffix<'a, 'hir:'a> {
1042 item_name: &'a String,
1043 in_which: &'a [String],
1047 impl<'a, 'hir> NodesMatchingSuffix<'a, 'hir> {
1048 /// Returns true only if some suffix of the module path for parent
1049 /// matches `self.in_which`.
1051 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
1052 /// returns true if parent's path ends with the suffix
1053 /// `x_0::x_1::...::x_k`.
1054 fn suffix_matches(&self, parent: NodeId) -> bool {
1055 let mut cursor = parent;
1056 for part in self.in_which.iter().rev() {
1057 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
1058 None => return false,
1059 Some((node_id, name)) => (node_id, name),
1061 if mod_name != &**part {
1064 cursor = self.map.get_parent(mod_id);
1068 // Finds the first mod in parent chain for `id`, along with
1071 // If `id` itself is a mod named `m` with parent `p`, then
1072 // returns `Some(id, m, p)`. If `id` has no mod in its parent
1073 // chain, then returns `None`.
1074 fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
1076 match map.find(id)? {
1077 NodeItem(item) if item_is_mod(&item) =>
1078 return Some((id, item.name)),
1081 let parent = map.get_parent(id);
1082 if parent == id { return None }
1086 fn item_is_mod(item: &Item) -> bool {
1095 // We are looking at some node `n` with a given name and parent
1096 // id; do their names match what I am seeking?
1097 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
1098 name == &**self.item_name && self.suffix_matches(parent_of_n)
1102 impl<'a, 'hir> Iterator for NodesMatchingSuffix<'a, 'hir> {
1105 fn next(&mut self) -> Option<NodeId> {
1108 if idx.as_usize() >= self.map.entry_count() {
1111 self.idx = NodeId::from_u32(self.idx.as_u32() + 1);
1112 let name = match self.map.find_entry(idx) {
1113 Some(EntryItem(_, _, n)) => n.name(),
1114 Some(EntryForeignItem(_, _, n))=> n.name(),
1115 Some(EntryTraitItem(_, _, n)) => n.name(),
1116 Some(EntryImplItem(_, _, n)) => n.name(),
1117 Some(EntryVariant(_, _, n)) => n.name(),
1118 Some(EntryField(_, _, n)) => n.name(),
1121 if self.matches_names(self.map.get_parent(idx), name) {
1129 fn name(&self) -> Name;
1132 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
1134 impl Named for Item { fn name(&self) -> Name { self.name } }
1135 impl Named for ForeignItem { fn name(&self) -> Name { self.name } }
1136 impl Named for Variant_ { fn name(&self) -> Name { self.name } }
1137 impl Named for StructField { fn name(&self) -> Name { self.name } }
1138 impl Named for TraitItem { fn name(&self) -> Name { self.name } }
1139 impl Named for ImplItem { fn name(&self) -> Name { self.name } }
1142 pub fn map_crate<'hir>(sess: &::session::Session,
1143 cstore: &dyn CrateStore,
1144 forest: &'hir mut Forest,
1145 definitions: &'hir Definitions)
1147 let (map, crate_hash) = {
1148 let hcx = ::ich::StableHashingContext::new(sess, &forest.krate, definitions, cstore);
1150 let mut collector = NodeCollector::root(&forest.krate,
1154 intravisit::walk_crate(&mut collector, &forest.krate);
1156 let crate_disambiguator = sess.local_crate_disambiguator();
1157 let cmdline_args = sess.opts.dep_tracking_hash();
1158 collector.finalize_and_compute_crate_hash(crate_disambiguator,
1164 if log_enabled!(::log::Level::Debug) {
1165 // This only makes sense for ordered stores; note the
1166 // enumerate to count the number of entries.
1167 let (entries_less_1, _) = map.iter().filter(|&x| {
1169 NotPresent => false,
1172 }).enumerate().last().expect("AST map was empty after folding?");
1174 let entries = entries_less_1 + 1;
1175 let vector_length = map.len();
1176 debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
1177 entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
1180 // Build the reverse mapping of `node_to_hir_id`.
1181 let hir_to_node_id = definitions.node_to_hir_id.iter_enumerated()
1182 .map(|(node_id, &hir_id)| (hir_id, node_id)).collect();
1186 dep_graph: forest.dep_graph.clone(),
1191 inlined_bodies: RefCell::new(DefIdMap()),
1194 hir_id_validator::check_crate(&map);
1199 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1200 /// except it avoids creating a dependency on the whole crate.
1201 impl<'hir> print::PpAnn for Map<'hir> {
1202 fn nested(&self, state: &mut print::State, nested: print::Nested) -> io::Result<()> {
1204 Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1205 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1206 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1207 Nested::Body(id) => state.print_expr(&self.body(id).value),
1208 Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
1213 impl<'a> print::State<'a> {
1214 pub fn print_node(&mut self, node: Node) -> io::Result<()> {
1216 NodeItem(a) => self.print_item(&a),
1217 NodeForeignItem(a) => self.print_foreign_item(&a),
1218 NodeTraitItem(a) => self.print_trait_item(a),
1219 NodeImplItem(a) => self.print_impl_item(a),
1220 NodeVariant(a) => self.print_variant(&a),
1221 NodeExpr(a) => self.print_expr(&a),
1222 NodeStmt(a) => self.print_stmt(&a),
1223 NodeTy(a) => self.print_type(&a),
1224 NodeTraitRef(a) => self.print_trait_ref(&a),
1226 NodePat(a) => self.print_pat(&a),
1228 use syntax::print::pprust::PrintState;
1230 // containing cbox, will be closed by print-block at }
1231 self.cbox(print::indent_unit)?;
1232 // head-ibox, will be closed by print-block after {
1234 self.print_block(&a)
1236 NodeLifetime(a) => self.print_lifetime(&a),
1237 NodeVisibility(a) => self.print_visibility(&a),
1238 NodeTyParam(_) => bug!("cannot print TyParam"),
1239 NodeField(_) => bug!("cannot print StructField"),
1240 // these cases do not carry enough information in the
1241 // hir_map to reconstruct their full structure for pretty
1243 NodeStructCtor(_) => bug!("cannot print isolated StructCtor"),
1244 NodeLocal(a) => self.print_local_decl(&a),
1245 NodeMacroDef(_) => bug!("cannot print MacroDef"),
1250 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
1251 let id_str = format!(" (id={})", id);
1252 let id_str = if include_id { &id_str[..] } else { "" };
1255 // This functionality is used for debugging, try to use TyCtxt to get
1256 // the user-friendly path, otherwise fall back to stringifying DefPath.
1257 ::ty::tls::with_opt(|tcx| {
1258 if let Some(tcx) = tcx {
1259 tcx.node_path_str(id)
1260 } else if let Some(path) = map.def_path_from_id(id) {
1261 path.data.into_iter().map(|elem| {
1262 elem.data.to_string()
1263 }).collect::<Vec<_>>().join("::")
1265 String::from("<missing path>")
1270 match map.find(id) {
1271 Some(NodeItem(item)) => {
1272 let item_str = match item.node {
1273 ItemExternCrate(..) => "extern crate",
1274 ItemUse(..) => "use",
1275 ItemStatic(..) => "static",
1276 ItemConst(..) => "const",
1278 ItemMod(..) => "mod",
1279 ItemForeignMod(..) => "foreign mod",
1280 ItemGlobalAsm(..) => "global asm",
1282 ItemEnum(..) => "enum",
1283 ItemStruct(..) => "struct",
1284 ItemUnion(..) => "union",
1285 ItemTrait(..) => "trait",
1286 ItemTraitAlias(..) => "trait alias",
1287 ItemImpl(..) => "impl",
1289 format!("{} {}{}", item_str, path_str(), id_str)
1291 Some(NodeForeignItem(_)) => {
1292 format!("foreign item {}{}", path_str(), id_str)
1294 Some(NodeImplItem(ii)) => {
1296 ImplItemKind::Const(..) => {
1297 format!("assoc const {} in {}{}", ii.name, path_str(), id_str)
1299 ImplItemKind::Method(..) => {
1300 format!("method {} in {}{}", ii.name, path_str(), id_str)
1302 ImplItemKind::Type(_) => {
1303 format!("assoc type {} in {}{}", ii.name, path_str(), id_str)
1307 Some(NodeTraitItem(ti)) => {
1308 let kind = match ti.node {
1309 TraitItemKind::Const(..) => "assoc constant",
1310 TraitItemKind::Method(..) => "trait method",
1311 TraitItemKind::Type(..) => "assoc type",
1314 format!("{} {} in {}{}", kind, ti.name, path_str(), id_str)
1316 Some(NodeVariant(ref variant)) => {
1317 format!("variant {} in {}{}",
1321 Some(NodeField(ref field)) => {
1322 format!("field {} in {}{}",
1326 Some(NodeExpr(_)) => {
1327 format!("expr {}{}", map.node_to_pretty_string(id), id_str)
1329 Some(NodeStmt(_)) => {
1330 format!("stmt {}{}", map.node_to_pretty_string(id), id_str)
1332 Some(NodeTy(_)) => {
1333 format!("type {}{}", map.node_to_pretty_string(id), id_str)
1335 Some(NodeTraitRef(_)) => {
1336 format!("trait_ref {}{}", map.node_to_pretty_string(id), id_str)
1338 Some(NodeBinding(_)) => {
1339 format!("local {}{}", map.node_to_pretty_string(id), id_str)
1341 Some(NodePat(_)) => {
1342 format!("pat {}{}", map.node_to_pretty_string(id), id_str)
1344 Some(NodeBlock(_)) => {
1345 format!("block {}{}", map.node_to_pretty_string(id), id_str)
1347 Some(NodeLocal(_)) => {
1348 format!("local {}{}", map.node_to_pretty_string(id), id_str)
1350 Some(NodeStructCtor(_)) => {
1351 format!("struct_ctor {}{}", path_str(), id_str)
1353 Some(NodeLifetime(_)) => {
1354 format!("lifetime {}{}", map.node_to_pretty_string(id), id_str)
1356 Some(NodeTyParam(ref ty_param)) => {
1357 format!("typaram {:?}{}", ty_param, id_str)
1359 Some(NodeVisibility(ref vis)) => {
1360 format!("visibility {:?}{}", vis, id_str)
1362 Some(NodeMacroDef(_)) => {
1363 format!("macro {}{}", path_str(), id_str)
1366 format!("unknown node{}", id_str)
1371 pub fn describe_def(tcx: TyCtxt, def_id: DefId) -> Option<Def> {
1372 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1373 tcx.hir.describe_def(node_id)
1375 bug!("Calling local describe_def query provider for upstream DefId: {:?}",