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;
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 /// Retrieve the Node corresponding to `id`, returning None if
669 pub fn find(&self, id: NodeId) -> Option<Node<'hir>> {
670 let result = self.find_entry(id).and_then(|x| x.to_node());
671 if result.is_some() {
677 /// Similar to get_parent, returns the parent node id or id if there is no
678 /// parent. Note that the parent may be CRATE_NODE_ID, which is not itself
679 /// present in the map -- so passing the return value of get_parent_node to
680 /// get may actually panic.
681 /// This function returns the immediate parent in the AST, whereas get_parent
682 /// returns the enclosing item. Note that this might not be the actual parent
683 /// node in the AST - some kinds of nodes are not in the map and these will
684 /// never appear as the parent_node. So you can always walk the parent_nodes
685 /// from a node to the root of the ast (unless you get the same id back here
686 /// that can happen if the id is not in the map itself or is just weird).
687 pub fn get_parent_node(&self, id: NodeId) -> NodeId {
688 if self.dep_graph.is_fully_enabled() {
689 let hir_id_owner = self.node_to_hir_id(id).owner;
690 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
691 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
694 self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
697 /// Check if the node is an argument. An argument is a local variable whose
698 /// immediate parent is an item or a closure.
699 pub fn is_argument(&self, id: NodeId) -> bool {
700 match self.find(id) {
701 Some(NodeBinding(_)) => (),
704 match self.find(self.get_parent_node(id)) {
706 Some(NodeTraitItem(_)) |
707 Some(NodeImplItem(_)) => true,
708 Some(NodeExpr(e)) => {
710 ExprClosure(..) => true,
718 /// If there is some error when walking the parents (e.g., a node does not
719 /// have a parent in the map or a node can't be found), then we return the
720 /// last good node id we found. Note that reaching the crate root (id == 0),
721 /// is not an error, since items in the crate module have the crate root as
723 fn walk_parent_nodes<F, F2>(&self,
727 -> Result<NodeId, NodeId>
728 where F: Fn(&Node<'hir>) -> bool, F2: Fn(&Node<'hir>) -> bool
730 let mut id = start_id;
732 let parent_node = self.get_parent_node(id);
733 if parent_node == CRATE_NODE_ID {
734 return Ok(CRATE_NODE_ID);
736 if parent_node == id {
740 let node = self.find_entry(parent_node);
744 let node = node.unwrap().to_node();
748 return Ok(parent_node);
749 } else if bail_early(node) {
750 return Err(parent_node);
754 return Err(parent_node);
761 /// Retrieve the NodeId for `id`'s enclosing method, unless there's a
762 /// `while` or `loop` before reaching it, as block tail returns are not
763 /// available in them.
766 /// fn foo(x: usize) -> bool {
768 /// true // `get_return_block` gets passed the `id` corresponding
769 /// } else { // to this, it will return `foo`'s `NodeId`.
776 /// fn foo(x: usize) -> bool {
778 /// true // `get_return_block` gets passed the `id` corresponding
779 /// } // to this, it will return `None`.
783 pub fn get_return_block(&self, id: NodeId) -> Option<NodeId> {
784 let match_fn = |node: &Node| {
789 NodeImplItem(_) => true,
793 let match_non_returning_block = |node: &Node| {
795 NodeExpr(ref expr) => {
797 ExprWhile(..) | ExprLoop(..) => true,
805 match self.walk_parent_nodes(id, match_fn, match_non_returning_block) {
811 /// Retrieve the NodeId for `id`'s parent item, or `id` itself if no
812 /// parent item is in this map. The "parent item" is the closest parent node
813 /// in the HIR which is recorded by the map and is an item, either an item
814 /// in a module, trait, or impl.
815 pub fn get_parent(&self, id: NodeId) -> NodeId {
816 match self.walk_parent_nodes(id, |node| match *node {
820 NodeImplItem(_) => true,
828 /// Returns the NodeId of `id`'s nearest module parent, or `id` itself if no
829 /// module parent is in this map.
830 pub fn get_module_parent(&self, id: NodeId) -> DefId {
831 let id = match self.walk_parent_nodes(id, |node| match *node {
832 NodeItem(&Item { node: Item_::ItemMod(_), .. }) => true,
838 self.local_def_id(id)
841 /// Returns the nearest enclosing scope. A scope is an item or block.
842 /// FIXME it is not clear to me that all items qualify as scopes - statics
843 /// and associated types probably shouldn't, for example. Behavior in this
844 /// regard should be expected to be highly unstable.
845 pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
846 match self.walk_parent_nodes(id, |node| match *node {
851 NodeBlock(_) => true,
859 pub fn get_parent_did(&self, id: NodeId) -> DefId {
860 self.local_def_id(self.get_parent(id))
863 pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
864 let parent = self.get_parent(id);
865 let abi = match self.find_entry(parent) {
866 Some(EntryItem(_, _, i)) => {
868 ItemForeignMod(ref nm) => Some(nm.abi),
876 self.read(id); // reveals some of the content of a node
879 None => bug!("expected foreign mod or inlined parent, found {}",
880 self.node_to_string(parent))
884 pub fn expect_item(&self, id: NodeId) -> &'hir Item {
885 match self.find(id) { // read recorded by `find`
886 Some(NodeItem(item)) => item,
887 _ => bug!("expected item, found {}", self.node_to_string(id))
891 pub fn expect_impl_item(&self, id: NodeId) -> &'hir ImplItem {
892 match self.find(id) {
893 Some(NodeImplItem(item)) => item,
894 _ => bug!("expected impl item, found {}", self.node_to_string(id))
898 pub fn expect_trait_item(&self, id: NodeId) -> &'hir TraitItem {
899 match self.find(id) {
900 Some(NodeTraitItem(item)) => item,
901 _ => bug!("expected trait item, found {}", self.node_to_string(id))
905 pub fn expect_variant_data(&self, id: NodeId) -> &'hir VariantData {
906 match self.find(id) {
907 Some(NodeItem(i)) => {
909 ItemStruct(ref struct_def, _) |
910 ItemUnion(ref struct_def, _) => struct_def,
912 bug!("struct ID bound to non-struct {}",
913 self.node_to_string(id));
917 Some(NodeStructCtor(data)) => data,
918 Some(NodeVariant(variant)) => &variant.node.data,
920 bug!("expected struct or variant, found {}",
921 self.node_to_string(id));
926 pub fn expect_variant(&self, id: NodeId) -> &'hir Variant {
927 match self.find(id) {
928 Some(NodeVariant(variant)) => variant,
929 _ => bug!("expected variant, found {}", self.node_to_string(id)),
933 pub fn expect_foreign_item(&self, id: NodeId) -> &'hir ForeignItem {
934 match self.find(id) {
935 Some(NodeForeignItem(item)) => item,
936 _ => bug!("expected foreign item, found {}", self.node_to_string(id))
940 pub fn expect_expr(&self, id: NodeId) -> &'hir Expr {
941 match self.find(id) { // read recorded by find
942 Some(NodeExpr(expr)) => expr,
943 _ => bug!("expected expr, found {}", self.node_to_string(id))
947 /// Returns the name associated with the given NodeId's AST.
948 pub fn name(&self, id: NodeId) -> Name {
950 NodeItem(i) => i.name,
951 NodeForeignItem(i) => i.name,
952 NodeImplItem(ii) => ii.ident.name,
953 NodeTraitItem(ti) => ti.ident.name,
954 NodeVariant(v) => v.node.name,
955 NodeField(f) => f.ident.name,
956 NodeLifetime(lt) => lt.name.ident().name,
957 NodeGenericParam(param) => param.name.ident().name,
958 NodeBinding(&Pat { node: PatKind::Binding(_,_,l,_), .. }) => l.name,
959 NodeStructCtor(_) => self.name(self.get_parent(id)),
960 _ => bug!("no name for {}", self.node_to_string(id))
964 /// Given a node ID, get a list of attributes associated with the AST
965 /// corresponding to the Node ID
966 pub fn attrs(&self, id: NodeId) -> &'hir [ast::Attribute] {
967 self.read(id); // reveals attributes on the node
968 let attrs = match self.find(id) {
969 Some(NodeItem(i)) => Some(&i.attrs[..]),
970 Some(NodeForeignItem(fi)) => Some(&fi.attrs[..]),
971 Some(NodeTraitItem(ref ti)) => Some(&ti.attrs[..]),
972 Some(NodeImplItem(ref ii)) => Some(&ii.attrs[..]),
973 Some(NodeVariant(ref v)) => Some(&v.node.attrs[..]),
974 Some(NodeField(ref f)) => Some(&f.attrs[..]),
975 Some(NodeExpr(ref e)) => Some(&*e.attrs),
976 Some(NodeStmt(ref s)) => Some(s.node.attrs()),
977 Some(NodeGenericParam(param)) => Some(¶m.attrs[..]),
978 // unit/tuple structs take the attributes straight from
979 // the struct definition.
980 Some(NodeStructCtor(_)) => {
981 return self.attrs(self.get_parent(id));
988 /// Returns an iterator that yields the node id's with paths that
989 /// match `parts`. (Requires `parts` is non-empty.)
991 /// For example, if given `parts` equal to `["bar", "quux"]`, then
992 /// the iterator will produce node id's for items with paths
993 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
994 /// any other such items it can find in the map.
995 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
996 -> NodesMatchingSuffix<'a, 'hir> {
997 NodesMatchingSuffix {
999 item_name: parts.last().unwrap(),
1000 in_which: &parts[..parts.len() - 1],
1005 pub fn span(&self, id: NodeId) -> Span {
1006 self.read(id); // reveals span from node
1007 match self.find_entry(id) {
1008 Some(EntryItem(_, _, item)) => item.span,
1009 Some(EntryForeignItem(_, _, foreign_item)) => foreign_item.span,
1010 Some(EntryTraitItem(_, _, trait_method)) => trait_method.span,
1011 Some(EntryImplItem(_, _, impl_item)) => impl_item.span,
1012 Some(EntryVariant(_, _, variant)) => variant.span,
1013 Some(EntryField(_, _, field)) => field.span,
1014 Some(EntryAnonConst(_, _, constant)) => self.body(constant.body).value.span,
1015 Some(EntryExpr(_, _, expr)) => expr.span,
1016 Some(EntryStmt(_, _, stmt)) => stmt.span,
1017 Some(EntryTy(_, _, ty)) => ty.span,
1018 Some(EntryTraitRef(_, _, tr)) => tr.path.span,
1019 Some(EntryBinding(_, _, pat)) => pat.span,
1020 Some(EntryPat(_, _, pat)) => pat.span,
1021 Some(EntryBlock(_, _, block)) => block.span,
1022 Some(EntryStructCtor(_, _, _)) => self.expect_item(self.get_parent(id)).span,
1023 Some(EntryLifetime(_, _, lifetime)) => lifetime.span,
1024 Some(EntryGenericParam(_, _, param)) => param.span,
1025 Some(EntryVisibility(_, _, &Visibility::Restricted { ref path, .. })) => path.span,
1026 Some(EntryVisibility(_, _, v)) => bug!("unexpected Visibility {:?}", v),
1027 Some(EntryLocal(_, _, local)) => local.span,
1028 Some(EntryMacroDef(_, macro_def)) => macro_def.span,
1030 Some(RootCrate(_)) => self.forest.krate.span,
1031 Some(NotPresent) | None => {
1032 bug!("hir::map::Map::span: id not in map: {:?}", id)
1037 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
1038 self.as_local_node_id(id).map(|id| self.span(id))
1041 pub fn node_to_string(&self, id: NodeId) -> String {
1042 node_id_to_string(self, id, true)
1045 pub fn node_to_user_string(&self, id: NodeId) -> String {
1046 node_id_to_string(self, id, false)
1049 pub fn node_to_pretty_string(&self, id: NodeId) -> String {
1050 print::to_string(self, |s| s.print_node(self.get(id)))
1054 pub struct NodesMatchingSuffix<'a, 'hir:'a> {
1056 item_name: &'a String,
1057 in_which: &'a [String],
1061 impl<'a, 'hir> NodesMatchingSuffix<'a, 'hir> {
1062 /// Returns true only if some suffix of the module path for parent
1063 /// matches `self.in_which`.
1065 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
1066 /// returns true if parent's path ends with the suffix
1067 /// `x_0::x_1::...::x_k`.
1068 fn suffix_matches(&self, parent: NodeId) -> bool {
1069 let mut cursor = parent;
1070 for part in self.in_which.iter().rev() {
1071 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
1072 None => return false,
1073 Some((node_id, name)) => (node_id, name),
1075 if mod_name != &**part {
1078 cursor = self.map.get_parent(mod_id);
1082 // Finds the first mod in parent chain for `id`, along with
1085 // If `id` itself is a mod named `m` with parent `p`, then
1086 // returns `Some(id, m, p)`. If `id` has no mod in its parent
1087 // chain, then returns `None`.
1088 fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
1090 match map.find(id)? {
1091 NodeItem(item) if item_is_mod(&item) =>
1092 return Some((id, item.name)),
1095 let parent = map.get_parent(id);
1096 if parent == id { return None }
1100 fn item_is_mod(item: &Item) -> bool {
1109 // We are looking at some node `n` with a given name and parent
1110 // id; do their names match what I am seeking?
1111 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
1112 name == &**self.item_name && self.suffix_matches(parent_of_n)
1116 impl<'a, 'hir> Iterator for NodesMatchingSuffix<'a, 'hir> {
1119 fn next(&mut self) -> Option<NodeId> {
1122 if idx.as_usize() >= self.map.entry_count() {
1125 self.idx = NodeId::from_u32(self.idx.as_u32() + 1);
1126 let name = match self.map.find_entry(idx) {
1127 Some(EntryItem(_, _, n)) => n.name(),
1128 Some(EntryForeignItem(_, _, n))=> n.name(),
1129 Some(EntryTraitItem(_, _, n)) => n.name(),
1130 Some(EntryImplItem(_, _, n)) => n.name(),
1131 Some(EntryVariant(_, _, n)) => n.name(),
1132 Some(EntryField(_, _, n)) => n.name(),
1135 if self.matches_names(self.map.get_parent(idx), name) {
1143 fn name(&self) -> Name;
1146 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
1148 impl Named for Item { fn name(&self) -> Name { self.name } }
1149 impl Named for ForeignItem { fn name(&self) -> Name { self.name } }
1150 impl Named for Variant_ { fn name(&self) -> Name { self.name } }
1151 impl Named for StructField { fn name(&self) -> Name { self.ident.name } }
1152 impl Named for TraitItem { fn name(&self) -> Name { self.ident.name } }
1153 impl Named for ImplItem { fn name(&self) -> Name { self.ident.name } }
1156 pub fn map_crate<'hir>(sess: &::session::Session,
1157 cstore: &dyn CrateStore,
1158 forest: &'hir mut Forest,
1159 definitions: &'hir Definitions)
1161 let (map, crate_hash) = {
1162 let hcx = ::ich::StableHashingContext::new(sess, &forest.krate, definitions, cstore);
1164 let mut collector = NodeCollector::root(&forest.krate,
1168 intravisit::walk_crate(&mut collector, &forest.krate);
1170 let crate_disambiguator = sess.local_crate_disambiguator();
1171 let cmdline_args = sess.opts.dep_tracking_hash();
1172 collector.finalize_and_compute_crate_hash(crate_disambiguator,
1178 if log_enabled!(::log::Level::Debug) {
1179 // This only makes sense for ordered stores; note the
1180 // enumerate to count the number of entries.
1181 let (entries_less_1, _) = map.iter().filter(|&x| {
1183 NotPresent => false,
1186 }).enumerate().last().expect("AST map was empty after folding?");
1188 let entries = entries_less_1 + 1;
1189 let vector_length = map.len();
1190 debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
1191 entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
1194 // Build the reverse mapping of `node_to_hir_id`.
1195 let hir_to_node_id = definitions.node_to_hir_id.iter_enumerated()
1196 .map(|(node_id, &hir_id)| (hir_id, node_id)).collect();
1200 dep_graph: forest.dep_graph.clone(),
1207 hir_id_validator::check_crate(&map);
1212 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1213 /// except it avoids creating a dependency on the whole crate.
1214 impl<'hir> print::PpAnn for Map<'hir> {
1215 fn nested(&self, state: &mut print::State, nested: print::Nested) -> io::Result<()> {
1217 Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1218 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1219 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1220 Nested::Body(id) => state.print_expr(&self.body(id).value),
1221 Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
1226 impl<'a> print::State<'a> {
1227 pub fn print_node(&mut self, node: Node) -> io::Result<()> {
1229 NodeItem(a) => self.print_item(&a),
1230 NodeForeignItem(a) => self.print_foreign_item(&a),
1231 NodeTraitItem(a) => self.print_trait_item(a),
1232 NodeImplItem(a) => self.print_impl_item(a),
1233 NodeVariant(a) => self.print_variant(&a),
1234 NodeAnonConst(a) => self.print_anon_const(&a),
1235 NodeExpr(a) => self.print_expr(&a),
1236 NodeStmt(a) => self.print_stmt(&a),
1237 NodeTy(a) => self.print_type(&a),
1238 NodeTraitRef(a) => self.print_trait_ref(&a),
1240 NodePat(a) => self.print_pat(&a),
1242 use syntax::print::pprust::PrintState;
1244 // containing cbox, will be closed by print-block at }
1245 self.cbox(print::indent_unit)?;
1246 // head-ibox, will be closed by print-block after {
1248 self.print_block(&a)
1250 NodeLifetime(a) => self.print_lifetime(&a),
1251 NodeVisibility(a) => self.print_visibility(&a),
1252 NodeGenericParam(_) => bug!("cannot print NodeGenericParam"),
1253 NodeField(_) => bug!("cannot print StructField"),
1254 // these cases do not carry enough information in the
1255 // hir_map to reconstruct their full structure for pretty
1257 NodeStructCtor(_) => bug!("cannot print isolated StructCtor"),
1258 NodeLocal(a) => self.print_local_decl(&a),
1259 NodeMacroDef(_) => bug!("cannot print MacroDef"),
1264 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
1265 let id_str = format!(" (id={})", id);
1266 let id_str = if include_id { &id_str[..] } else { "" };
1269 // This functionality is used for debugging, try to use TyCtxt to get
1270 // the user-friendly path, otherwise fall back to stringifying DefPath.
1271 ::ty::tls::with_opt(|tcx| {
1272 if let Some(tcx) = tcx {
1273 tcx.node_path_str(id)
1274 } else if let Some(path) = map.def_path_from_id(id) {
1275 path.data.into_iter().map(|elem| {
1276 elem.data.to_string()
1277 }).collect::<Vec<_>>().join("::")
1279 String::from("<missing path>")
1284 match map.find(id) {
1285 Some(NodeItem(item)) => {
1286 let item_str = match item.node {
1287 ItemExternCrate(..) => "extern crate",
1288 ItemUse(..) => "use",
1289 ItemStatic(..) => "static",
1290 ItemConst(..) => "const",
1292 ItemMod(..) => "mod",
1293 ItemForeignMod(..) => "foreign mod",
1294 ItemGlobalAsm(..) => "global asm",
1296 ItemExistential(..) => "existential",
1297 ItemEnum(..) => "enum",
1298 ItemStruct(..) => "struct",
1299 ItemUnion(..) => "union",
1300 ItemTrait(..) => "trait",
1301 ItemTraitAlias(..) => "trait alias",
1302 ItemImpl(..) => "impl",
1304 format!("{} {}{}", item_str, path_str(), id_str)
1306 Some(NodeForeignItem(_)) => {
1307 format!("foreign item {}{}", path_str(), id_str)
1309 Some(NodeImplItem(ii)) => {
1311 ImplItemKind::Const(..) => {
1312 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1314 ImplItemKind::Method(..) => {
1315 format!("method {} in {}{}", ii.ident, path_str(), id_str)
1317 ImplItemKind::Type(_) => {
1318 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1322 Some(NodeTraitItem(ti)) => {
1323 let kind = match ti.node {
1324 TraitItemKind::Const(..) => "assoc constant",
1325 TraitItemKind::Method(..) => "trait method",
1326 TraitItemKind::Type(..) => "assoc type",
1329 format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1331 Some(NodeVariant(ref variant)) => {
1332 format!("variant {} in {}{}",
1336 Some(NodeField(ref field)) => {
1337 format!("field {} in {}{}",
1341 Some(NodeAnonConst(_)) => {
1342 format!("const {}{}", map.node_to_pretty_string(id), id_str)
1344 Some(NodeExpr(_)) => {
1345 format!("expr {}{}", map.node_to_pretty_string(id), id_str)
1347 Some(NodeStmt(_)) => {
1348 format!("stmt {}{}", map.node_to_pretty_string(id), id_str)
1350 Some(NodeTy(_)) => {
1351 format!("type {}{}", map.node_to_pretty_string(id), id_str)
1353 Some(NodeTraitRef(_)) => {
1354 format!("trait_ref {}{}", map.node_to_pretty_string(id), id_str)
1356 Some(NodeBinding(_)) => {
1357 format!("local {}{}", map.node_to_pretty_string(id), id_str)
1359 Some(NodePat(_)) => {
1360 format!("pat {}{}", map.node_to_pretty_string(id), id_str)
1362 Some(NodeBlock(_)) => {
1363 format!("block {}{}", map.node_to_pretty_string(id), id_str)
1365 Some(NodeLocal(_)) => {
1366 format!("local {}{}", map.node_to_pretty_string(id), id_str)
1368 Some(NodeStructCtor(_)) => {
1369 format!("struct_ctor {}{}", path_str(), id_str)
1371 Some(NodeLifetime(_)) => {
1372 format!("lifetime {}{}", map.node_to_pretty_string(id), id_str)
1374 Some(NodeGenericParam(ref param)) => {
1375 format!("generic_param {:?}{}", param, id_str)
1377 Some(NodeVisibility(ref vis)) => {
1378 format!("visibility {:?}{}", vis, id_str)
1380 Some(NodeMacroDef(_)) => {
1381 format!("macro {}{}", path_str(), id_str)
1384 format!("unknown node{}", id_str)
1389 pub fn describe_def(tcx: TyCtxt, def_id: DefId) -> Option<Def> {
1390 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1391 tcx.hir.describe_def(node_id)
1393 bug!("Calling local describe_def query provider for upstream DefId: {:?}",