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, DefIndexAddressSpace};
23 use syntax::ast::{self, Name, NodeId, CRATE_NODE_ID};
24 use syntax::codemap::Spanned;
28 use hir::print::Nested;
29 use util::nodemap::{DefIdMap, FxHashMap};
31 use arena::TypedArena;
32 use std::cell::RefCell;
41 pub const ITEM_LIKE_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::Low;
42 pub const REGULAR_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::High;
44 #[derive(Copy, Clone, Debug)]
47 NodeForeignItem(&'hir ForeignItem),
48 NodeTraitItem(&'hir TraitItem),
49 NodeImplItem(&'hir ImplItem),
50 NodeVariant(&'hir Variant),
51 NodeField(&'hir StructField),
55 NodeTraitRef(&'hir TraitRef),
56 NodeBinding(&'hir Pat),
58 NodeBlock(&'hir Block),
59 NodeLocal(&'hir Local),
60 NodeMacroDef(&'hir MacroDef),
62 /// NodeStructCtor represents a tuple struct.
63 NodeStructCtor(&'hir VariantData),
65 NodeLifetime(&'hir Lifetime),
66 NodeTyParam(&'hir TyParam),
67 NodeVisibility(&'hir Visibility),
70 /// Represents an entry and its parent NodeID.
71 /// The odd layout is to bring down the total size.
72 #[derive(Copy, Debug)]
74 /// Placeholder for holes in the map.
77 /// All the node types, with a parent ID.
78 EntryItem(NodeId, DepNodeIndex, &'hir Item),
79 EntryForeignItem(NodeId, DepNodeIndex, &'hir ForeignItem),
80 EntryTraitItem(NodeId, DepNodeIndex, &'hir TraitItem),
81 EntryImplItem(NodeId, DepNodeIndex, &'hir ImplItem),
82 EntryVariant(NodeId, DepNodeIndex, &'hir Variant),
83 EntryField(NodeId, DepNodeIndex, &'hir StructField),
84 EntryExpr(NodeId, DepNodeIndex, &'hir Expr),
85 EntryStmt(NodeId, DepNodeIndex, &'hir Stmt),
86 EntryTy(NodeId, DepNodeIndex, &'hir Ty),
87 EntryTraitRef(NodeId, DepNodeIndex, &'hir TraitRef),
88 EntryBinding(NodeId, DepNodeIndex, &'hir Pat),
89 EntryPat(NodeId, DepNodeIndex, &'hir Pat),
90 EntryBlock(NodeId, DepNodeIndex, &'hir Block),
91 EntryStructCtor(NodeId, DepNodeIndex, &'hir VariantData),
92 EntryLifetime(NodeId, DepNodeIndex, &'hir Lifetime),
93 EntryTyParam(NodeId, DepNodeIndex, &'hir TyParam),
94 EntryVisibility(NodeId, DepNodeIndex, &'hir Visibility),
95 EntryLocal(NodeId, DepNodeIndex, &'hir Local),
97 EntryMacroDef(DepNodeIndex, &'hir MacroDef),
99 /// Roots for node trees. The DepNodeIndex is the dependency node of the
100 /// crate's root module.
101 RootCrate(DepNodeIndex),
104 impl<'hir> Clone for MapEntry<'hir> {
105 fn clone(&self) -> MapEntry<'hir> {
110 impl<'hir> MapEntry<'hir> {
111 fn parent_node(self) -> Option<NodeId> {
113 EntryItem(id, _, _) => id,
114 EntryForeignItem(id, _, _) => id,
115 EntryTraitItem(id, _, _) => id,
116 EntryImplItem(id, _, _) => id,
117 EntryVariant(id, _, _) => id,
118 EntryField(id, _, _) => id,
119 EntryExpr(id, _, _) => id,
120 EntryStmt(id, _, _) => id,
121 EntryTy(id, _, _) => id,
122 EntryTraitRef(id, _, _) => id,
123 EntryBinding(id, _, _) => id,
124 EntryPat(id, _, _) => id,
125 EntryBlock(id, _, _) => id,
126 EntryStructCtor(id, _, _) => id,
127 EntryLifetime(id, _, _) => id,
128 EntryTyParam(id, _, _) => id,
129 EntryVisibility(id, _, _) => id,
130 EntryLocal(id, _, _) => id,
134 RootCrate(_) => return None,
138 fn to_node(self) -> Option<Node<'hir>> {
140 EntryItem(_, _, n) => NodeItem(n),
141 EntryForeignItem(_, _, n) => NodeForeignItem(n),
142 EntryTraitItem(_, _, n) => NodeTraitItem(n),
143 EntryImplItem(_, _, n) => NodeImplItem(n),
144 EntryVariant(_, _, n) => NodeVariant(n),
145 EntryField(_, _, n) => NodeField(n),
146 EntryExpr(_, _, n) => NodeExpr(n),
147 EntryStmt(_, _, n) => NodeStmt(n),
148 EntryTy(_, _, n) => NodeTy(n),
149 EntryTraitRef(_, _, n) => NodeTraitRef(n),
150 EntryBinding(_, _, n) => NodeBinding(n),
151 EntryPat(_, _, n) => NodePat(n),
152 EntryBlock(_, _, n) => NodeBlock(n),
153 EntryStructCtor(_, _, n) => NodeStructCtor(n),
154 EntryLifetime(_, _, n) => NodeLifetime(n),
155 EntryTyParam(_, _, n) => NodeTyParam(n),
156 EntryVisibility(_, _, n) => NodeVisibility(n),
157 EntryLocal(_, _, n) => NodeLocal(n),
158 EntryMacroDef(_, n) => NodeMacroDef(n),
161 RootCrate(_) => return None
165 fn associated_body(self) -> Option<BodyId> {
167 EntryItem(_, _, item) => {
170 ItemStatic(.., body) |
171 ItemFn(_, _, _, _, _, body) => Some(body),
176 EntryTraitItem(_, _, item) => {
178 TraitItemKind::Const(_, Some(body)) |
179 TraitItemKind::Method(_, TraitMethod::Provided(body)) => Some(body),
184 EntryImplItem(_, _, item) => {
186 ImplItemKind::Const(_, body) |
187 ImplItemKind::Method(_, body) => Some(body),
192 EntryExpr(_, _, expr) => {
194 ExprClosure(.., body, _, _) => Some(body),
203 fn is_body_owner(self, node_id: NodeId) -> bool {
204 match self.associated_body() {
205 Some(b) => b.node_id == node_id,
211 /// Stores a crate and any number of inlined items from other crates.
214 pub dep_graph: DepGraph,
215 inlined_bodies: TypedArena<Body>
219 pub fn new(krate: Crate, dep_graph: &DepGraph) -> Forest {
222 dep_graph: dep_graph.clone(),
223 inlined_bodies: TypedArena::new()
227 pub fn krate<'hir>(&'hir self) -> &'hir Crate {
228 self.dep_graph.read(DepNode::new_no_params(DepKind::Krate));
233 /// Represents a mapping from Node IDs to AST elements and their parent
236 pub struct Map<'hir> {
237 /// The backing storage for all the AST nodes.
238 pub forest: &'hir Forest,
240 /// Same as the dep_graph in forest, just available with one fewer
241 /// deref. This is a gratuitous micro-optimization.
242 pub dep_graph: DepGraph,
244 /// NodeIds are sequential integers from 0, so we can be
245 /// super-compact by storing them in a vector. Not everything with
246 /// a NodeId is in the map, but empirically the occupancy is about
247 /// 75-80%, so there's not too much overhead (certainly less than
248 /// a hashmap, since they (at the time of writing) have a maximum
249 /// of 75% occupancy).
251 /// Also, indexing is pretty quick when you've got a vector and
252 /// plain old integers.
253 map: Vec<MapEntry<'hir>>,
255 definitions: &'hir Definitions,
257 /// Bodies inlined from other crates are cached here.
258 inlined_bodies: RefCell<DefIdMap<&'hir Body>>,
260 /// The reverse mapping of `node_to_hir_id`.
261 hir_to_node_id: FxHashMap<HirId, NodeId>,
264 impl<'hir> Map<'hir> {
265 /// Registers a read in the dependency graph of the AST node with
266 /// the given `id`. This needs to be called each time a public
267 /// function returns the HIR for a node -- in other words, when it
268 /// "reveals" the content of a node to the caller (who might not
269 /// otherwise have had access to those contents, and hence needs a
270 /// read recorded). If the function just returns a DefId or
271 /// NodeId, no actual content was returned, so no read is needed.
272 pub fn read(&self, id: NodeId) {
273 let entry = self.map[id.as_usize()];
275 EntryItem(_, dep_node_index, _) |
276 EntryTraitItem(_, dep_node_index, _) |
277 EntryImplItem(_, dep_node_index, _) |
278 EntryVariant(_, dep_node_index, _) |
279 EntryForeignItem(_, dep_node_index, _) |
280 EntryField(_, dep_node_index, _) |
281 EntryStmt(_, dep_node_index, _) |
282 EntryTy(_, dep_node_index, _) |
283 EntryTraitRef(_, dep_node_index, _) |
284 EntryBinding(_, dep_node_index, _) |
285 EntryPat(_, dep_node_index, _) |
286 EntryBlock(_, dep_node_index, _) |
287 EntryStructCtor(_, dep_node_index, _) |
288 EntryLifetime(_, dep_node_index, _) |
289 EntryTyParam(_, dep_node_index, _) |
290 EntryVisibility(_, dep_node_index, _) |
291 EntryExpr(_, dep_node_index, _) |
292 EntryLocal(_, dep_node_index, _) |
293 EntryMacroDef(dep_node_index, _) |
294 RootCrate(dep_node_index) => {
295 self.dep_graph.read_index(dep_node_index);
298 bug!("called HirMap::read() with invalid NodeId")
304 pub fn definitions(&self) -> &'hir Definitions {
308 pub fn def_key(&self, def_id: DefId) -> DefKey {
309 assert!(def_id.is_local());
310 self.definitions.def_key(def_id.index)
313 pub fn def_path_from_id(&self, id: NodeId) -> Option<DefPath> {
314 self.opt_local_def_id(id).map(|def_id| {
315 self.def_path(def_id)
319 pub fn def_path(&self, def_id: DefId) -> DefPath {
320 assert!(def_id.is_local());
321 self.definitions.def_path(def_id.index)
325 pub fn local_def_id(&self, node: NodeId) -> DefId {
326 self.opt_local_def_id(node).unwrap_or_else(|| {
327 bug!("local_def_id: no entry for `{}`, which has a map of `{:?}`",
328 node, self.find_entry(node))
333 pub fn opt_local_def_id(&self, node: NodeId) -> Option<DefId> {
334 self.definitions.opt_local_def_id(node)
338 pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
339 self.definitions.as_local_node_id(def_id)
343 pub fn hir_to_node_id(&self, hir_id: HirId) -> NodeId {
344 self.hir_to_node_id[&hir_id]
348 pub fn node_to_hir_id(&self, node_id: NodeId) -> HirId {
349 self.definitions.node_to_hir_id(node_id)
353 pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> HirId {
354 self.definitions.def_index_to_hir_id(def_index)
358 pub fn def_index_to_node_id(&self, def_index: DefIndex) -> NodeId {
359 self.definitions.as_local_node_id(DefId::local(def_index)).unwrap()
362 fn entry_count(&self) -> usize {
366 fn find_entry(&self, id: NodeId) -> Option<MapEntry<'hir>> {
367 self.map.get(id.as_usize()).cloned()
370 pub fn krate(&self) -> &'hir Crate {
374 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem {
375 self.read(id.node_id);
377 // NB: intentionally bypass `self.forest.krate()` so that we
378 // do not trigger a read of the whole krate here
379 self.forest.krate.trait_item(id)
382 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem {
383 self.read(id.node_id);
385 // NB: intentionally bypass `self.forest.krate()` so that we
386 // do not trigger a read of the whole krate here
387 self.forest.krate.impl_item(id)
390 pub fn body(&self, id: BodyId) -> &'hir Body {
391 self.read(id.node_id);
393 // NB: intentionally bypass `self.forest.krate()` so that we
394 // do not trigger a read of the whole krate here
395 self.forest.krate.body(id)
398 /// Returns the `NodeId` that corresponds to the definition of
399 /// which this is the body of, i.e. a `fn`, `const` or `static`
400 /// item (possibly associated), or a closure, or the body itself
401 /// for embedded constant expressions (e.g. `N` in `[T; N]`).
402 pub fn body_owner(&self, BodyId { node_id }: BodyId) -> NodeId {
403 let parent = self.get_parent_node(node_id);
404 if self.map[parent.as_usize()].is_body_owner(node_id) {
411 pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
412 self.local_def_id(self.body_owner(id))
415 /// Given a node id, returns the `BodyId` associated with it,
416 /// if the node is a body owner, otherwise returns `None`.
417 pub fn maybe_body_owned_by(&self, id: NodeId) -> Option<BodyId> {
418 if let Some(entry) = self.find_entry(id) {
419 if self.dep_graph.is_fully_enabled() {
420 let hir_id_owner = self.node_to_hir_id(id).owner;
421 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
422 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
425 if let Some(body_id) = entry.associated_body() {
426 // For item-like things and closures, the associated
427 // body has its own distinct id, and that is returned
428 // by `associated_body`.
431 // For some expressions, the expression is its own body.
432 if let EntryExpr(_, _, expr) = entry {
433 Some(BodyId { node_id: expr.id })
439 bug!("no entry for id `{}`", id)
443 /// Given a body owner's id, returns the `BodyId` associated with it.
444 pub fn body_owned_by(&self, id: NodeId) -> BodyId {
445 self.maybe_body_owned_by(id).unwrap_or_else(|| {
446 span_bug!(self.span(id), "body_owned_by: {} has no associated body",
447 self.node_to_string(id));
451 pub fn body_owner_kind(&self, id: NodeId) -> BodyOwnerKind {
452 // Handle constants in enum discriminants, types, and repeat expressions.
453 let def_id = self.local_def_id(id);
454 let def_key = self.def_key(def_id);
455 if def_key.disambiguated_data.data == DefPathData::Initializer {
456 return BodyOwnerKind::Const;
460 NodeItem(&Item { node: ItemConst(..), .. }) |
461 NodeTraitItem(&TraitItem { node: TraitItemKind::Const(..), .. }) |
462 NodeImplItem(&ImplItem { node: ImplItemKind::Const(..), .. }) => {
465 NodeItem(&Item { node: ItemStatic(_, m, _), .. }) => {
466 BodyOwnerKind::Static(m)
468 // Default to function if it's not a constant or static.
469 _ => BodyOwnerKind::Fn
473 pub fn ty_param_owner(&self, id: NodeId) -> NodeId {
475 NodeItem(&Item { node: ItemTrait(..), .. }) => id,
476 NodeTyParam(_) => self.get_parent_node(id),
478 bug!("ty_param_owner: {} not a type parameter",
479 self.node_to_string(id))
484 pub fn ty_param_name(&self, id: NodeId) -> Name {
486 NodeItem(&Item { node: ItemTrait(..), .. }) => {
487 keywords::SelfType.name()
489 NodeTyParam(tp) => tp.name,
491 bug!("ty_param_name: {} not a type parameter",
492 self.node_to_string(id))
497 pub fn trait_impls(&self, trait_did: DefId) -> &'hir [NodeId] {
498 self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
500 // NB: intentionally bypass `self.forest.krate()` so that we
501 // do not trigger a read of the whole krate here
502 self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
505 pub fn trait_auto_impl(&self, trait_did: DefId) -> Option<NodeId> {
506 self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
508 // NB: intentionally bypass `self.forest.krate()` so that we
509 // do not trigger a read of the whole krate here
510 self.forest.krate.trait_auto_impl.get(&trait_did).cloned()
513 pub fn trait_is_auto(&self, trait_did: DefId) -> bool {
514 self.trait_auto_impl(trait_did).is_some()
517 /// Get the attributes on the krate. This is preferable to
518 /// invoking `krate.attrs` because it registers a tighter
519 /// dep-graph access.
520 pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
521 let def_path_hash = self.definitions.def_path_hash(CRATE_DEF_INDEX);
523 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::Hir));
524 &self.forest.krate.attrs
527 /// Retrieve the Node corresponding to `id`, panicking if it cannot
529 pub fn get(&self, id: NodeId) -> Node<'hir> {
530 match self.find(id) {
531 Some(node) => node, // read recorded by `find`
532 None => bug!("couldn't find node id {} in the AST map", id)
536 pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
537 self.as_local_node_id(id).map(|id| self.get(id)) // read recorded by `get`
540 /// Retrieve the Node corresponding to `id`, returning None if
542 pub fn find(&self, id: NodeId) -> Option<Node<'hir>> {
543 let result = self.find_entry(id).and_then(|x| x.to_node());
544 if result.is_some() {
550 /// Similar to get_parent, returns the parent node id or id if there is no
551 /// parent. Note that the parent may be CRATE_NODE_ID, which is not itself
552 /// present in the map -- so passing the return value of get_parent_node to
553 /// get may actually panic.
554 /// This function returns the immediate parent in the AST, whereas get_parent
555 /// returns the enclosing item. Note that this might not be the actual parent
556 /// node in the AST - some kinds of nodes are not in the map and these will
557 /// never appear as the parent_node. So you can always walk the parent_nodes
558 /// from a node to the root of the ast (unless you get the same id back here
559 /// that can happen if the id is not in the map itself or is just weird).
560 pub fn get_parent_node(&self, id: NodeId) -> NodeId {
561 if self.dep_graph.is_fully_enabled() {
562 let hir_id_owner = self.node_to_hir_id(id).owner;
563 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
564 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
567 self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
570 /// Check if the node is an argument. An argument is a local variable whose
571 /// immediate parent is an item or a closure.
572 pub fn is_argument(&self, id: NodeId) -> bool {
573 match self.find(id) {
574 Some(NodeBinding(_)) => (),
577 match self.find(self.get_parent_node(id)) {
579 Some(NodeTraitItem(_)) |
580 Some(NodeImplItem(_)) => true,
581 Some(NodeExpr(e)) => {
583 ExprClosure(..) => true,
591 /// If there is some error when walking the parents (e.g., a node does not
592 /// have a parent in the map or a node can't be found), then we return the
593 /// last good node id we found. Note that reaching the crate root (id == 0),
594 /// is not an error, since items in the crate module have the crate root as
596 fn walk_parent_nodes<F, F2>(&self,
600 -> Result<NodeId, NodeId>
601 where F: Fn(&Node<'hir>) -> bool, F2: Fn(&Node<'hir>) -> bool
603 let mut id = start_id;
605 let parent_node = self.get_parent_node(id);
606 if parent_node == CRATE_NODE_ID {
607 return Ok(CRATE_NODE_ID);
609 if parent_node == id {
613 let node = self.find_entry(parent_node);
617 let node = node.unwrap().to_node();
621 return Ok(parent_node);
622 } else if bail_early(node) {
623 return Err(parent_node);
627 return Err(parent_node);
634 /// Retrieve the NodeId for `id`'s enclosing method, unless there's a
635 /// `while` or `loop` before reaching it, as block tail returns are not
636 /// available in them.
639 /// fn foo(x: usize) -> bool {
641 /// true // `get_return_block` gets passed the `id` corresponding
642 /// } else { // to this, it will return `foo`'s `NodeId`.
649 /// fn foo(x: usize) -> bool {
651 /// true // `get_return_block` gets passed the `id` corresponding
652 /// } // to this, it will return `None`.
656 pub fn get_return_block(&self, id: NodeId) -> Option<NodeId> {
657 let match_fn = |node: &Node| {
662 NodeImplItem(_) => true,
666 let match_non_returning_block = |node: &Node| {
668 NodeExpr(ref expr) => {
670 ExprWhile(..) | ExprLoop(..) => true,
678 match self.walk_parent_nodes(id, match_fn, match_non_returning_block) {
684 /// Retrieve the NodeId for `id`'s parent item, or `id` itself if no
685 /// parent item is in this map. The "parent item" is the closest parent node
686 /// in the AST which is recorded by the map and is an item, either an item
687 /// in a module, trait, or impl.
688 pub fn get_parent(&self, id: NodeId) -> NodeId {
689 match self.walk_parent_nodes(id, |node| match *node {
693 NodeImplItem(_) => true,
701 /// Returns the NodeId of `id`'s nearest module parent, or `id` itself if no
702 /// module parent is in this map.
703 pub fn get_module_parent(&self, id: NodeId) -> DefId {
704 let id = match self.walk_parent_nodes(id, |node| match *node {
705 NodeItem(&Item { node: Item_::ItemMod(_), .. }) => true,
711 self.local_def_id(id)
714 /// Returns the nearest enclosing scope. A scope is an item or block.
715 /// FIXME it is not clear to me that all items qualify as scopes - statics
716 /// and associated types probably shouldn't, for example. Behavior in this
717 /// regard should be expected to be highly unstable.
718 pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
719 match self.walk_parent_nodes(id, |node| match *node {
724 NodeBlock(_) => true,
732 pub fn get_parent_did(&self, id: NodeId) -> DefId {
733 self.local_def_id(self.get_parent(id))
736 pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
737 let parent = self.get_parent(id);
738 let abi = match self.find_entry(parent) {
739 Some(EntryItem(_, _, i)) => {
741 ItemForeignMod(ref nm) => Some(nm.abi),
749 self.read(id); // reveals some of the content of a node
752 None => bug!("expected foreign mod or inlined parent, found {}",
753 self.node_to_string(parent))
757 pub fn expect_item(&self, id: NodeId) -> &'hir Item {
758 match self.find(id) { // read recorded by `find`
759 Some(NodeItem(item)) => item,
760 _ => bug!("expected item, found {}", self.node_to_string(id))
764 pub fn expect_impl_item(&self, id: NodeId) -> &'hir ImplItem {
765 match self.find(id) {
766 Some(NodeImplItem(item)) => item,
767 _ => bug!("expected impl item, found {}", self.node_to_string(id))
771 pub fn expect_trait_item(&self, id: NodeId) -> &'hir TraitItem {
772 match self.find(id) {
773 Some(NodeTraitItem(item)) => item,
774 _ => bug!("expected trait item, found {}", self.node_to_string(id))
778 pub fn expect_variant_data(&self, id: NodeId) -> &'hir VariantData {
779 match self.find(id) {
780 Some(NodeItem(i)) => {
782 ItemStruct(ref struct_def, _) |
783 ItemUnion(ref struct_def, _) => struct_def,
785 bug!("struct ID bound to non-struct {}",
786 self.node_to_string(id));
790 Some(NodeStructCtor(data)) => data,
791 Some(NodeVariant(variant)) => &variant.node.data,
793 bug!("expected struct or variant, found {}",
794 self.node_to_string(id));
799 pub fn expect_variant(&self, id: NodeId) -> &'hir Variant {
800 match self.find(id) {
801 Some(NodeVariant(variant)) => variant,
802 _ => bug!("expected variant, found {}", self.node_to_string(id)),
806 pub fn expect_foreign_item(&self, id: NodeId) -> &'hir ForeignItem {
807 match self.find(id) {
808 Some(NodeForeignItem(item)) => item,
809 _ => bug!("expected foreign item, found {}", self.node_to_string(id))
813 pub fn expect_expr(&self, id: NodeId) -> &'hir Expr {
814 match self.find(id) { // read recorded by find
815 Some(NodeExpr(expr)) => expr,
816 _ => bug!("expected expr, found {}", self.node_to_string(id))
820 pub fn get_inlined_body_untracked(&self, def_id: DefId) -> Option<&'hir Body> {
821 self.inlined_bodies.borrow().get(&def_id).cloned()
824 pub fn intern_inlined_body(&self, def_id: DefId, body: Body) -> &'hir Body {
825 let body = self.forest.inlined_bodies.alloc(body);
826 self.inlined_bodies.borrow_mut().insert(def_id, body);
830 /// Returns the name associated with the given NodeId's AST.
831 pub fn name(&self, id: NodeId) -> Name {
833 NodeItem(i) => i.name,
834 NodeForeignItem(i) => i.name,
835 NodeImplItem(ii) => ii.name,
836 NodeTraitItem(ti) => ti.name,
837 NodeVariant(v) => v.node.name,
838 NodeField(f) => f.name,
839 NodeLifetime(lt) => lt.name.name(),
840 NodeTyParam(tp) => tp.name,
841 NodeBinding(&Pat { node: PatKind::Binding(_,_,l,_), .. }) => l.node,
842 NodeStructCtor(_) => self.name(self.get_parent(id)),
843 _ => bug!("no name for {}", self.node_to_string(id))
847 /// Given a node ID, get a list of attributes associated with the AST
848 /// corresponding to the Node ID
849 pub fn attrs(&self, id: NodeId) -> &'hir [ast::Attribute] {
850 self.read(id); // reveals attributes on the node
851 let attrs = match self.find(id) {
852 Some(NodeItem(i)) => Some(&i.attrs[..]),
853 Some(NodeForeignItem(fi)) => Some(&fi.attrs[..]),
854 Some(NodeTraitItem(ref ti)) => Some(&ti.attrs[..]),
855 Some(NodeImplItem(ref ii)) => Some(&ii.attrs[..]),
856 Some(NodeVariant(ref v)) => Some(&v.node.attrs[..]),
857 Some(NodeField(ref f)) => Some(&f.attrs[..]),
858 Some(NodeExpr(ref e)) => Some(&*e.attrs),
859 Some(NodeStmt(ref s)) => Some(s.node.attrs()),
860 // unit/tuple structs take the attributes straight from
861 // the struct definition.
862 Some(NodeStructCtor(_)) => {
863 return self.attrs(self.get_parent(id));
870 /// Returns an iterator that yields the node id's with paths that
871 /// match `parts`. (Requires `parts` is non-empty.)
873 /// For example, if given `parts` equal to `["bar", "quux"]`, then
874 /// the iterator will produce node id's for items with paths
875 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
876 /// any other such items it can find in the map.
877 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
878 -> NodesMatchingSuffix<'a, 'hir> {
879 NodesMatchingSuffix {
881 item_name: parts.last().unwrap(),
882 in_which: &parts[..parts.len() - 1],
887 pub fn span(&self, id: NodeId) -> Span {
888 self.read(id); // reveals span from node
889 match self.find_entry(id) {
890 Some(EntryItem(_, _, item)) => item.span,
891 Some(EntryForeignItem(_, _, foreign_item)) => foreign_item.span,
892 Some(EntryTraitItem(_, _, trait_method)) => trait_method.span,
893 Some(EntryImplItem(_, _, impl_item)) => impl_item.span,
894 Some(EntryVariant(_, _, variant)) => variant.span,
895 Some(EntryField(_, _, field)) => field.span,
896 Some(EntryExpr(_, _, expr)) => expr.span,
897 Some(EntryStmt(_, _, stmt)) => stmt.span,
898 Some(EntryTy(_, _, ty)) => ty.span,
899 Some(EntryTraitRef(_, _, tr)) => tr.path.span,
900 Some(EntryBinding(_, _, pat)) => pat.span,
901 Some(EntryPat(_, _, pat)) => pat.span,
902 Some(EntryBlock(_, _, block)) => block.span,
903 Some(EntryStructCtor(_, _, _)) => self.expect_item(self.get_parent(id)).span,
904 Some(EntryLifetime(_, _, lifetime)) => lifetime.span,
905 Some(EntryTyParam(_, _, ty_param)) => ty_param.span,
906 Some(EntryVisibility(_, _, &Visibility::Restricted { ref path, .. })) => path.span,
907 Some(EntryVisibility(_, _, v)) => bug!("unexpected Visibility {:?}", v),
908 Some(EntryLocal(_, _, local)) => local.span,
909 Some(EntryMacroDef(_, macro_def)) => macro_def.span,
911 Some(RootCrate(_)) => self.forest.krate.span,
912 Some(NotPresent) | None => {
913 bug!("hir::map::Map::span: id not in map: {:?}", id)
918 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
919 self.as_local_node_id(id).map(|id| self.span(id))
922 pub fn node_to_string(&self, id: NodeId) -> String {
923 node_id_to_string(self, id, true)
926 pub fn node_to_user_string(&self, id: NodeId) -> String {
927 node_id_to_string(self, id, false)
930 pub fn node_to_pretty_string(&self, id: NodeId) -> String {
931 print::to_string(self, |s| s.print_node(self.get(id)))
935 pub struct NodesMatchingSuffix<'a, 'hir:'a> {
937 item_name: &'a String,
938 in_which: &'a [String],
942 impl<'a, 'hir> NodesMatchingSuffix<'a, 'hir> {
943 /// Returns true only if some suffix of the module path for parent
944 /// matches `self.in_which`.
946 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
947 /// returns true if parent's path ends with the suffix
948 /// `x_0::x_1::...::x_k`.
949 fn suffix_matches(&self, parent: NodeId) -> bool {
950 let mut cursor = parent;
951 for part in self.in_which.iter().rev() {
952 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
953 None => return false,
954 Some((node_id, name)) => (node_id, name),
956 if mod_name != &**part {
959 cursor = self.map.get_parent(mod_id);
963 // Finds the first mod in parent chain for `id`, along with
966 // If `id` itself is a mod named `m` with parent `p`, then
967 // returns `Some(id, m, p)`. If `id` has no mod in its parent
968 // chain, then returns `None`.
969 fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
973 Some(NodeItem(item)) if item_is_mod(&item) =>
974 return Some((id, item.name)),
977 let parent = map.get_parent(id);
978 if parent == id { return None }
982 fn item_is_mod(item: &Item) -> bool {
991 // We are looking at some node `n` with a given name and parent
992 // id; do their names match what I am seeking?
993 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
994 name == &**self.item_name && self.suffix_matches(parent_of_n)
998 impl<'a, 'hir> Iterator for NodesMatchingSuffix<'a, 'hir> {
1001 fn next(&mut self) -> Option<NodeId> {
1004 if idx.as_usize() >= self.map.entry_count() {
1007 self.idx = NodeId::from_u32(self.idx.as_u32() + 1);
1008 let name = match self.map.find_entry(idx) {
1009 Some(EntryItem(_, _, n)) => n.name(),
1010 Some(EntryForeignItem(_, _, n))=> n.name(),
1011 Some(EntryTraitItem(_, _, n)) => n.name(),
1012 Some(EntryImplItem(_, _, n)) => n.name(),
1013 Some(EntryVariant(_, _, n)) => n.name(),
1014 Some(EntryField(_, _, n)) => n.name(),
1017 if self.matches_names(self.map.get_parent(idx), name) {
1025 fn name(&self) -> Name;
1028 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
1030 impl Named for Item { fn name(&self) -> Name { self.name } }
1031 impl Named for ForeignItem { fn name(&self) -> Name { self.name } }
1032 impl Named for Variant_ { fn name(&self) -> Name { self.name } }
1033 impl Named for StructField { fn name(&self) -> Name { self.name } }
1034 impl Named for TraitItem { fn name(&self) -> Name { self.name } }
1035 impl Named for ImplItem { fn name(&self) -> Name { self.name } }
1037 pub fn map_crate<'hir>(sess: &::session::Session,
1038 cstore: &::middle::cstore::CrateStore,
1039 forest: &'hir mut Forest,
1040 definitions: &'hir Definitions)
1043 let hcx = ::ich::StableHashingContext::new(sess, &forest.krate, definitions, cstore);
1045 let mut collector = NodeCollector::root(&forest.krate,
1049 intravisit::walk_crate(&mut collector, &forest.krate);
1051 let crate_disambiguator = sess.local_crate_disambiguator();
1052 collector.finalize_and_compute_crate_hash(crate_disambiguator)
1055 if log_enabled!(::log::LogLevel::Debug) {
1056 // This only makes sense for ordered stores; note the
1057 // enumerate to count the number of entries.
1058 let (entries_less_1, _) = map.iter().filter(|&x| {
1060 NotPresent => false,
1063 }).enumerate().last().expect("AST map was empty after folding?");
1065 let entries = entries_less_1 + 1;
1066 let vector_length = map.len();
1067 debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
1068 entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
1071 // Build the reverse mapping of `node_to_hir_id`.
1072 let hir_to_node_id = definitions.node_to_hir_id.iter_enumerated()
1073 .map(|(node_id, &hir_id)| (hir_id, node_id)).collect();
1077 dep_graph: forest.dep_graph.clone(),
1081 inlined_bodies: RefCell::new(DefIdMap()),
1084 hir_id_validator::check_crate(&map);
1089 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1090 /// except it avoids creating a dependency on the whole crate.
1091 impl<'hir> print::PpAnn for Map<'hir> {
1092 fn nested(&self, state: &mut print::State, nested: print::Nested) -> io::Result<()> {
1094 Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1095 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1096 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1097 Nested::Body(id) => state.print_expr(&self.body(id).value),
1098 Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
1103 impl<'a> print::State<'a> {
1104 pub fn print_node(&mut self, node: Node) -> io::Result<()> {
1106 NodeItem(a) => self.print_item(&a),
1107 NodeForeignItem(a) => self.print_foreign_item(&a),
1108 NodeTraitItem(a) => self.print_trait_item(a),
1109 NodeImplItem(a) => self.print_impl_item(a),
1110 NodeVariant(a) => self.print_variant(&a),
1111 NodeExpr(a) => self.print_expr(&a),
1112 NodeStmt(a) => self.print_stmt(&a),
1113 NodeTy(a) => self.print_type(&a),
1114 NodeTraitRef(a) => self.print_trait_ref(&a),
1116 NodePat(a) => self.print_pat(&a),
1118 use syntax::print::pprust::PrintState;
1120 // containing cbox, will be closed by print-block at }
1121 self.cbox(print::indent_unit)?;
1122 // head-ibox, will be closed by print-block after {
1124 self.print_block(&a)
1126 NodeLifetime(a) => self.print_lifetime(&a),
1127 NodeVisibility(a) => self.print_visibility(&a),
1128 NodeTyParam(_) => bug!("cannot print TyParam"),
1129 NodeField(_) => bug!("cannot print StructField"),
1130 // these cases do not carry enough information in the
1131 // hir_map to reconstruct their full structure for pretty
1133 NodeStructCtor(_) => bug!("cannot print isolated StructCtor"),
1134 NodeLocal(a) => self.print_local_decl(&a),
1135 NodeMacroDef(_) => bug!("cannot print MacroDef"),
1140 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
1141 let id_str = format!(" (id={})", id);
1142 let id_str = if include_id { &id_str[..] } else { "" };
1145 // This functionality is used for debugging, try to use TyCtxt to get
1146 // the user-friendly path, otherwise fall back to stringifying DefPath.
1147 ::ty::tls::with_opt(|tcx| {
1148 if let Some(tcx) = tcx {
1149 tcx.node_path_str(id)
1150 } else if let Some(path) = map.def_path_from_id(id) {
1151 path.data.into_iter().map(|elem| {
1152 elem.data.to_string()
1153 }).collect::<Vec<_>>().join("::")
1155 String::from("<missing path>")
1160 match map.find(id) {
1161 Some(NodeItem(item)) => {
1162 let item_str = match item.node {
1163 ItemExternCrate(..) => "extern crate",
1164 ItemUse(..) => "use",
1165 ItemStatic(..) => "static",
1166 ItemConst(..) => "const",
1168 ItemMod(..) => "mod",
1169 ItemForeignMod(..) => "foreign mod",
1170 ItemGlobalAsm(..) => "global asm",
1172 ItemEnum(..) => "enum",
1173 ItemStruct(..) => "struct",
1174 ItemUnion(..) => "union",
1175 ItemTrait(..) => "trait",
1176 ItemImpl(..) => "impl",
1177 ItemAutoImpl(..) => "default impl",
1179 format!("{} {}{}", item_str, path_str(), id_str)
1181 Some(NodeForeignItem(_)) => {
1182 format!("foreign item {}{}", path_str(), id_str)
1184 Some(NodeImplItem(ii)) => {
1186 ImplItemKind::Const(..) => {
1187 format!("assoc const {} in {}{}", ii.name, path_str(), id_str)
1189 ImplItemKind::Method(..) => {
1190 format!("method {} in {}{}", ii.name, path_str(), id_str)
1192 ImplItemKind::Type(_) => {
1193 format!("assoc type {} in {}{}", ii.name, path_str(), id_str)
1197 Some(NodeTraitItem(ti)) => {
1198 let kind = match ti.node {
1199 TraitItemKind::Const(..) => "assoc constant",
1200 TraitItemKind::Method(..) => "trait method",
1201 TraitItemKind::Type(..) => "assoc type",
1204 format!("{} {} in {}{}", kind, ti.name, path_str(), id_str)
1206 Some(NodeVariant(ref variant)) => {
1207 format!("variant {} in {}{}",
1211 Some(NodeField(ref field)) => {
1212 format!("field {} in {}{}",
1216 Some(NodeExpr(_)) => {
1217 format!("expr {}{}", map.node_to_pretty_string(id), id_str)
1219 Some(NodeStmt(_)) => {
1220 format!("stmt {}{}", map.node_to_pretty_string(id), id_str)
1222 Some(NodeTy(_)) => {
1223 format!("type {}{}", map.node_to_pretty_string(id), id_str)
1225 Some(NodeTraitRef(_)) => {
1226 format!("trait_ref {}{}", map.node_to_pretty_string(id), id_str)
1228 Some(NodeBinding(_)) => {
1229 format!("local {}{}", map.node_to_pretty_string(id), id_str)
1231 Some(NodePat(_)) => {
1232 format!("pat {}{}", map.node_to_pretty_string(id), id_str)
1234 Some(NodeBlock(_)) => {
1235 format!("block {}{}", map.node_to_pretty_string(id), id_str)
1237 Some(NodeLocal(_)) => {
1238 format!("local {}{}", map.node_to_pretty_string(id), id_str)
1240 Some(NodeStructCtor(_)) => {
1241 format!("struct_ctor {}{}", path_str(), id_str)
1243 Some(NodeLifetime(_)) => {
1244 format!("lifetime {}{}", map.node_to_pretty_string(id), id_str)
1246 Some(NodeTyParam(ref ty_param)) => {
1247 format!("typaram {:?}{}", ty_param, id_str)
1249 Some(NodeVisibility(ref vis)) => {
1250 format!("visibility {:?}{}", vis, id_str)
1252 Some(NodeMacroDef(_)) => {
1253 format!("macro {}{}", path_str(), id_str)
1256 format!("unknown node{}", id_str)