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};
18 use dep_graph::{DepGraph, DepNode};
20 use hir::def_id::{CRATE_DEF_INDEX, DefId, DefIndex, 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;
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),
58 NodeBlock(&'hir Block),
60 /// NodeStructCtor represents a tuple struct.
61 NodeStructCtor(&'hir VariantData),
63 NodeLifetime(&'hir Lifetime),
64 NodeTyParam(&'hir TyParam),
65 NodeVisibility(&'hir Visibility),
68 /// Represents an entry and its parent NodeID.
69 /// The odd layout is to bring down the total size.
70 #[derive(Copy, Debug)]
72 /// Placeholder for holes in the map.
75 /// All the node types, with a parent ID.
76 EntryItem(NodeId, &'hir Item),
77 EntryForeignItem(NodeId, &'hir ForeignItem),
78 EntryTraitItem(NodeId, &'hir TraitItem),
79 EntryImplItem(NodeId, &'hir ImplItem),
80 EntryVariant(NodeId, &'hir Variant),
81 EntryField(NodeId, &'hir StructField),
82 EntryExpr(NodeId, &'hir Expr),
83 EntryStmt(NodeId, &'hir Stmt),
84 EntryTy(NodeId, &'hir Ty),
85 EntryTraitRef(NodeId, &'hir TraitRef),
86 EntryLocal(NodeId, &'hir Pat),
87 EntryPat(NodeId, &'hir Pat),
88 EntryBlock(NodeId, &'hir Block),
89 EntryStructCtor(NodeId, &'hir VariantData),
90 EntryLifetime(NodeId, &'hir Lifetime),
91 EntryTyParam(NodeId, &'hir TyParam),
92 EntryVisibility(NodeId, &'hir Visibility),
94 /// Roots for node trees.
98 impl<'hir> Clone for MapEntry<'hir> {
99 fn clone(&self) -> MapEntry<'hir> {
104 impl<'hir> MapEntry<'hir> {
105 fn from_node(p: NodeId, node: Node<'hir>) -> MapEntry<'hir> {
107 NodeItem(n) => EntryItem(p, n),
108 NodeForeignItem(n) => EntryForeignItem(p, n),
109 NodeTraitItem(n) => EntryTraitItem(p, n),
110 NodeImplItem(n) => EntryImplItem(p, n),
111 NodeVariant(n) => EntryVariant(p, n),
112 NodeField(n) => EntryField(p, n),
113 NodeExpr(n) => EntryExpr(p, n),
114 NodeStmt(n) => EntryStmt(p, n),
115 NodeTy(n) => EntryTy(p, n),
116 NodeTraitRef(n) => EntryTraitRef(p, n),
117 NodeLocal(n) => EntryLocal(p, n),
118 NodePat(n) => EntryPat(p, n),
119 NodeBlock(n) => EntryBlock(p, n),
120 NodeStructCtor(n) => EntryStructCtor(p, n),
121 NodeLifetime(n) => EntryLifetime(p, n),
122 NodeTyParam(n) => EntryTyParam(p, n),
123 NodeVisibility(n) => EntryVisibility(p, n),
127 fn parent_node(self) -> Option<NodeId> {
129 EntryItem(id, _) => id,
130 EntryForeignItem(id, _) => id,
131 EntryTraitItem(id, _) => id,
132 EntryImplItem(id, _) => id,
133 EntryVariant(id, _) => id,
134 EntryField(id, _) => id,
135 EntryExpr(id, _) => id,
136 EntryStmt(id, _) => id,
137 EntryTy(id, _) => id,
138 EntryTraitRef(id, _) => id,
139 EntryLocal(id, _) => id,
140 EntryPat(id, _) => id,
141 EntryBlock(id, _) => id,
142 EntryStructCtor(id, _) => id,
143 EntryLifetime(id, _) => id,
144 EntryTyParam(id, _) => id,
145 EntryVisibility(id, _) => id,
148 RootCrate => return None,
152 fn to_node(self) -> Option<Node<'hir>> {
154 EntryItem(_, n) => NodeItem(n),
155 EntryForeignItem(_, n) => NodeForeignItem(n),
156 EntryTraitItem(_, n) => NodeTraitItem(n),
157 EntryImplItem(_, n) => NodeImplItem(n),
158 EntryVariant(_, n) => NodeVariant(n),
159 EntryField(_, n) => NodeField(n),
160 EntryExpr(_, n) => NodeExpr(n),
161 EntryStmt(_, n) => NodeStmt(n),
162 EntryTy(_, n) => NodeTy(n),
163 EntryTraitRef(_, n) => NodeTraitRef(n),
164 EntryLocal(_, n) => NodeLocal(n),
165 EntryPat(_, n) => NodePat(n),
166 EntryBlock(_, n) => NodeBlock(n),
167 EntryStructCtor(_, n) => NodeStructCtor(n),
168 EntryLifetime(_, n) => NodeLifetime(n),
169 EntryTyParam(_, n) => NodeTyParam(n),
170 EntryVisibility(_, n) => NodeVisibility(n),
175 fn associated_body(self) -> Option<BodyId> {
177 EntryItem(_, item) => {
180 ItemStatic(.., body) |
181 ItemFn(_, _, _, _, _, body) => Some(body),
186 EntryTraitItem(_, item) => {
188 TraitItemKind::Const(_, Some(body)) |
189 TraitItemKind::Method(_, TraitMethod::Provided(body)) => Some(body),
194 EntryImplItem(_, item) => {
196 ImplItemKind::Const(_, body) |
197 ImplItemKind::Method(_, body) => Some(body),
202 EntryExpr(_, expr) => {
204 ExprClosure(.., body, _) => Some(body),
213 fn is_body_owner(self, node_id: NodeId) -> bool {
214 match self.associated_body() {
215 Some(b) => b.node_id == node_id,
221 /// Stores a crate and any number of inlined items from other crates.
224 pub dep_graph: DepGraph,
225 inlined_bodies: TypedArena<Body>
229 pub fn new(krate: Crate, dep_graph: &DepGraph) -> Forest {
232 dep_graph: dep_graph.clone(),
233 inlined_bodies: TypedArena::new()
237 pub fn krate<'hir>(&'hir self) -> &'hir Crate {
238 self.dep_graph.read(DepNode::Krate);
243 /// Represents a mapping from Node IDs to AST elements and their parent
246 pub struct Map<'hir> {
247 /// The backing storage for all the AST nodes.
248 pub forest: &'hir Forest,
250 /// Same as the dep_graph in forest, just available with one fewer
251 /// deref. This is a gratuitious micro-optimization.
252 pub dep_graph: DepGraph,
254 /// NodeIds are sequential integers from 0, so we can be
255 /// super-compact by storing them in a vector. Not everything with
256 /// a NodeId is in the map, but empirically the occupancy is about
257 /// 75-80%, so there's not too much overhead (certainly less than
258 /// a hashmap, since they (at the time of writing) have a maximum
259 /// of 75% occupancy).
261 /// Also, indexing is pretty quick when you've got a vector and
262 /// plain old integers.
263 map: Vec<MapEntry<'hir>>,
265 definitions: Definitions,
267 /// Bodies inlined from other crates are cached here.
268 inlined_bodies: RefCell<DefIdMap<&'hir Body>>,
271 impl<'hir> Map<'hir> {
272 /// Registers a read in the dependency graph of the AST node with
273 /// the given `id`. This needs to be called each time a public
274 /// function returns the HIR for a node -- in other words, when it
275 /// "reveals" the content of a node to the caller (who might not
276 /// otherwise have had access to those contents, and hence needs a
277 /// read recorded). If the function just returns a DefId or
278 /// NodeId, no actual content was returned, so no read is needed.
279 pub fn read(&self, id: NodeId) {
280 self.dep_graph.read(self.dep_node(id));
283 fn dep_node(&self, id0: NodeId) -> DepNode<DefId> {
285 let mut last_expr = None;
287 let entry = self.map[id.as_usize()];
291 EntryImplItem(..) => {
292 if let Some(last_id) = last_expr {
293 // The body may have a separate dep node
294 if entry.is_body_owner(last_id) {
295 let def_id = self.local_def_id(id);
296 return DepNode::HirBody(def_id);
299 return DepNode::Hir(self.local_def_id(id));
302 EntryVariant(p, v) => {
305 if last_expr.is_some() {
306 if v.node.disr_expr.map(|e| e.node_id) == last_expr {
307 // The enum parent holds both Hir and HirBody nodes.
308 let def_id = self.local_def_id(id);
309 return DepNode::HirBody(def_id);
314 EntryForeignItem(p, _) |
318 EntryTraitRef(p, _) |
322 EntryStructCtor(p, _) |
323 EntryLifetime(p, _) |
325 EntryVisibility(p, _) =>
329 last_expr = Some(id);
334 return DepNode::Hir(DefId::local(CRATE_DEF_INDEX));
338 // Some nodes, notably macro definitions, are not
339 // present in the map for whatever reason, but
340 // they *do* have def-ids. So if we encounter an
341 // empty hole, check for that case.
342 return self.opt_local_def_id(id)
343 .map(|def_id| DepNode::Hir(def_id))
345 bug!("Walking parents from `{}` \
346 led to `NotPresent` at `{}`",
353 pub fn definitions(&self) -> &Definitions {
357 pub fn def_key(&self, def_id: DefId) -> DefKey {
358 assert!(def_id.is_local());
359 self.definitions.def_key(def_id.index)
362 pub fn def_path_from_id(&self, id: NodeId) -> Option<DefPath> {
363 self.opt_local_def_id(id).map(|def_id| {
364 self.def_path(def_id)
368 pub fn def_path(&self, def_id: DefId) -> DefPath {
369 assert!(def_id.is_local());
370 self.definitions.def_path(def_id.index)
373 pub fn def_index_for_def_key(&self, def_key: DefKey) -> Option<DefIndex> {
374 self.definitions.def_index_for_def_key(def_key)
377 pub fn local_def_id(&self, node: NodeId) -> DefId {
378 self.opt_local_def_id(node).unwrap_or_else(|| {
379 bug!("local_def_id: no entry for `{}`, which has a map of `{:?}`",
380 node, self.find_entry(node))
384 pub fn opt_local_def_id(&self, node: NodeId) -> Option<DefId> {
385 self.definitions.opt_local_def_id(node)
388 pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
389 self.definitions.as_local_node_id(def_id)
392 fn entry_count(&self) -> usize {
396 fn find_entry(&self, id: NodeId) -> Option<MapEntry<'hir>> {
397 self.map.get(id.as_usize()).cloned()
400 pub fn krate(&self) -> &'hir Crate {
404 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem {
405 self.read(id.node_id);
407 // NB: intentionally bypass `self.forest.krate()` so that we
408 // do not trigger a read of the whole krate here
409 self.forest.krate.trait_item(id)
412 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem {
413 self.read(id.node_id);
415 // NB: intentionally bypass `self.forest.krate()` so that we
416 // do not trigger a read of the whole krate here
417 self.forest.krate.impl_item(id)
420 pub fn body(&self, id: BodyId) -> &'hir Body {
421 self.read(id.node_id);
423 // NB: intentionally bypass `self.forest.krate()` so that we
424 // do not trigger a read of the whole krate here
425 self.forest.krate.body(id)
428 /// Returns the `NodeId` that corresponds to the definition of
429 /// which this is the body of, i.e. a `fn`, `const` or `static`
430 /// item (possibly associated), or a closure, or the body itself
431 /// for embedded constant expressions (e.g. `N` in `[T; N]`).
432 pub fn body_owner(&self, BodyId { node_id }: BodyId) -> NodeId {
433 let parent = self.get_parent_node(node_id);
434 if self.map[parent.as_usize()].is_body_owner(node_id) {
441 pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
442 self.local_def_id(self.body_owner(id))
445 /// Given a node id, returns the `BodyId` associated with it,
446 /// if the node is a body owner, otherwise returns `None`.
447 pub fn maybe_body_owned_by(&self, id: NodeId) -> Option<BodyId> {
448 if let Some(entry) = self.find_entry(id) {
449 if let Some(body_id) = entry.associated_body() {
450 // For item-like things and closures, the associated
451 // body has its own distinct id, and that is returned
452 // by `associated_body`.
455 // For some expressions, the expression is its own body.
456 if let EntryExpr(_, expr) = entry {
457 Some(BodyId { node_id: expr.id })
463 bug!("no entry for id `{}`", id)
467 /// Given a body owner's id, returns the `BodyId` associated with it.
468 pub fn body_owned_by(&self, id: NodeId) -> BodyId {
469 self.maybe_body_owned_by(id).unwrap_or_else(|| {
470 span_bug!(self.span(id), "body_owned_by: {} has no associated body",
471 self.node_to_string(id));
475 pub fn ty_param_owner(&self, id: NodeId) -> NodeId {
477 NodeItem(&Item { node: ItemTrait(..), .. }) => id,
478 NodeTyParam(_) => self.get_parent_node(id),
480 bug!("ty_param_owner: {} not a type parameter",
481 self.node_to_string(id))
486 pub fn ty_param_name(&self, id: NodeId) -> Name {
488 NodeItem(&Item { node: ItemTrait(..), .. }) => {
489 keywords::SelfType.name()
491 NodeTyParam(tp) => tp.name,
493 bug!("ty_param_name: {} not a type parameter",
494 self.node_to_string(id))
499 pub fn trait_impls(&self, trait_did: DefId) -> &'hir [NodeId] {
500 self.dep_graph.read(DepNode::AllLocalTraitImpls);
502 // NB: intentionally bypass `self.forest.krate()` so that we
503 // do not trigger a read of the whole krate here
504 self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
507 pub fn trait_default_impl(&self, trait_did: DefId) -> Option<NodeId> {
508 self.dep_graph.read(DepNode::AllLocalTraitImpls);
510 // NB: intentionally bypass `self.forest.krate()` so that we
511 // do not trigger a read of the whole krate here
512 self.forest.krate.trait_default_impl.get(&trait_did).cloned()
515 pub fn trait_is_auto(&self, trait_did: DefId) -> bool {
516 self.trait_default_impl(trait_did).is_some()
519 /// Get the attributes on the krate. This is preferable to
520 /// invoking `krate.attrs` because it registers a tighter
521 /// dep-graph access.
522 pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
523 let crate_root_def_id = DefId::local(CRATE_DEF_INDEX);
524 self.dep_graph.read(DepNode::Hir(crate_root_def_id));
525 &self.forest.krate.attrs
528 /// Retrieve the Node corresponding to `id`, panicking if it cannot
530 pub fn get(&self, id: NodeId) -> Node<'hir> {
531 match self.find(id) {
532 Some(node) => node, // read recorded by `find`
533 None => bug!("couldn't find node id {} in the AST map", id)
537 pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
538 self.as_local_node_id(id).map(|id| self.get(id)) // read recorded by `get`
541 /// Retrieve the Node corresponding to `id`, returning None if
543 pub fn find(&self, id: NodeId) -> Option<Node<'hir>> {
544 let result = self.find_entry(id).and_then(|x| x.to_node());
545 if result.is_some() {
551 /// Similar to get_parent, returns the parent node id or id if there is no
553 /// This function returns the immediate parent in the AST, whereas get_parent
554 /// returns the enclosing item. Note that this might not be the actual parent
555 /// node in the AST - some kinds of nodes are not in the map and these will
556 /// never appear as the parent_node. So you can always walk the parent_nodes
557 /// from a node to the root of the ast (unless you get the same id back here
558 /// that can happen if the id is not in the map itself or is just weird).
559 pub fn get_parent_node(&self, id: NodeId) -> NodeId {
560 self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
563 /// Check if the node is an argument. An argument is a local variable whose
564 /// immediate parent is an item or a closure.
565 pub fn is_argument(&self, id: NodeId) -> bool {
566 match self.find(id) {
567 Some(NodeLocal(_)) => (),
570 match self.find(self.get_parent_node(id)) {
572 Some(NodeTraitItem(_)) |
573 Some(NodeImplItem(_)) => true,
574 Some(NodeExpr(e)) => {
576 ExprClosure(..) => true,
584 /// If there is some error when walking the parents (e.g., a node does not
585 /// have a parent in the map or a node can't be found), then we return the
586 /// last good node id we found. Note that reaching the crate root (id == 0),
587 /// is not an error, since items in the crate module have the crate root as
589 fn walk_parent_nodes<F>(&self, start_id: NodeId, found: F) -> Result<NodeId, NodeId>
590 where F: Fn(&Node<'hir>) -> bool
592 let mut id = start_id;
594 let parent_node = self.get_parent_node(id);
595 if parent_node == CRATE_NODE_ID {
596 return Ok(CRATE_NODE_ID);
598 if parent_node == id {
602 let node = self.find_entry(parent_node);
606 let node = node.unwrap().to_node();
610 return Ok(parent_node);
614 return Err(parent_node);
621 /// Retrieve the NodeId for `id`'s parent item, or `id` itself if no
622 /// parent item is in this map. The "parent item" is the closest parent node
623 /// in the AST which is recorded by the map and is an item, either an item
624 /// in a module, trait, or impl.
625 pub fn get_parent(&self, id: NodeId) -> NodeId {
626 match self.walk_parent_nodes(id, |node| match *node {
630 NodeImplItem(_) => true,
638 /// Returns the NodeId of `id`'s nearest module parent, or `id` itself if no
639 /// module parent is in this map.
640 pub fn get_module_parent(&self, id: NodeId) -> NodeId {
641 match self.walk_parent_nodes(id, |node| match *node {
642 NodeItem(&Item { node: Item_::ItemMod(_), .. }) => true,
650 /// Returns the nearest enclosing scope. A scope is an item or block.
651 /// FIXME it is not clear to me that all items qualify as scopes - statics
652 /// and associated types probably shouldn't, for example. Behaviour in this
653 /// regard should be expected to be highly unstable.
654 pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
655 match self.walk_parent_nodes(id, |node| match *node {
660 NodeBlock(_) => true,
668 pub fn get_parent_did(&self, id: NodeId) -> DefId {
669 self.local_def_id(self.get_parent(id))
672 pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
673 let parent = self.get_parent(id);
674 let abi = match self.find_entry(parent) {
675 Some(EntryItem(_, i)) => {
677 ItemForeignMod(ref nm) => Some(nm.abi),
685 self.read(id); // reveals some of the content of a node
688 None => bug!("expected foreign mod or inlined parent, found {}",
689 self.node_to_string(parent))
693 pub fn expect_item(&self, id: NodeId) -> &'hir Item {
694 match self.find(id) { // read recorded by `find`
695 Some(NodeItem(item)) => item,
696 _ => bug!("expected item, found {}", self.node_to_string(id))
700 pub fn expect_impl_item(&self, id: NodeId) -> &'hir ImplItem {
701 match self.find(id) {
702 Some(NodeImplItem(item)) => item,
703 _ => bug!("expected impl item, found {}", self.node_to_string(id))
707 pub fn expect_trait_item(&self, id: NodeId) -> &'hir TraitItem {
708 match self.find(id) {
709 Some(NodeTraitItem(item)) => item,
710 _ => bug!("expected trait item, found {}", self.node_to_string(id))
714 pub fn expect_variant_data(&self, id: NodeId) -> &'hir VariantData {
715 match self.find(id) {
716 Some(NodeItem(i)) => {
718 ItemStruct(ref struct_def, _) |
719 ItemUnion(ref struct_def, _) => struct_def,
721 bug!("struct ID bound to non-struct {}",
722 self.node_to_string(id));
726 Some(NodeStructCtor(data)) => data,
727 Some(NodeVariant(variant)) => &variant.node.data,
729 bug!("expected struct or variant, found {}",
730 self.node_to_string(id));
735 pub fn expect_variant(&self, id: NodeId) -> &'hir Variant {
736 match self.find(id) {
737 Some(NodeVariant(variant)) => variant,
738 _ => bug!("expected variant, found {}", self.node_to_string(id)),
742 pub fn expect_foreign_item(&self, id: NodeId) -> &'hir ForeignItem {
743 match self.find(id) {
744 Some(NodeForeignItem(item)) => item,
745 _ => bug!("expected foreign item, found {}", self.node_to_string(id))
749 pub fn expect_expr(&self, id: NodeId) -> &'hir Expr {
750 match self.find(id) { // read recorded by find
751 Some(NodeExpr(expr)) => expr,
752 _ => bug!("expected expr, found {}", self.node_to_string(id))
756 pub fn get_inlined_body(&self, def_id: DefId) -> Option<&'hir Body> {
757 self.inlined_bodies.borrow().get(&def_id).map(|&body| {
758 self.dep_graph.read(DepNode::MetaData(def_id));
763 pub fn intern_inlined_body(&self, def_id: DefId, body: Body) -> &'hir Body {
764 let body = self.forest.inlined_bodies.alloc(body);
765 self.inlined_bodies.borrow_mut().insert(def_id, body);
769 /// Returns the name associated with the given NodeId's AST.
770 pub fn name(&self, id: NodeId) -> Name {
772 NodeItem(i) => i.name,
773 NodeForeignItem(i) => i.name,
774 NodeImplItem(ii) => ii.name,
775 NodeTraitItem(ti) => ti.name,
776 NodeVariant(v) => v.node.name,
777 NodeField(f) => f.name,
778 NodeLifetime(lt) => lt.name,
779 NodeTyParam(tp) => tp.name,
780 NodeLocal(&Pat { node: PatKind::Binding(_,_,l,_), .. }) => l.node,
781 NodeStructCtor(_) => self.name(self.get_parent(id)),
782 _ => bug!("no name for {}", self.node_to_string(id))
786 /// Given a node ID, get a list of attributes associated with the AST
787 /// corresponding to the Node ID
788 pub fn attrs(&self, id: NodeId) -> &'hir [ast::Attribute] {
789 self.read(id); // reveals attributes on the node
790 let attrs = match self.find(id) {
791 Some(NodeItem(i)) => Some(&i.attrs[..]),
792 Some(NodeForeignItem(fi)) => Some(&fi.attrs[..]),
793 Some(NodeTraitItem(ref ti)) => Some(&ti.attrs[..]),
794 Some(NodeImplItem(ref ii)) => Some(&ii.attrs[..]),
795 Some(NodeVariant(ref v)) => Some(&v.node.attrs[..]),
796 Some(NodeField(ref f)) => Some(&f.attrs[..]),
797 Some(NodeExpr(ref e)) => Some(&*e.attrs),
798 Some(NodeStmt(ref s)) => Some(s.node.attrs()),
799 // unit/tuple structs take the attributes straight from
800 // the struct definition.
801 Some(NodeStructCtor(_)) => {
802 return self.attrs(self.get_parent(id));
809 /// Returns an iterator that yields the node id's with paths that
810 /// match `parts`. (Requires `parts` is non-empty.)
812 /// For example, if given `parts` equal to `["bar", "quux"]`, then
813 /// the iterator will produce node id's for items with paths
814 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
815 /// any other such items it can find in the map.
816 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
817 -> NodesMatchingSuffix<'a, 'hir> {
818 NodesMatchingSuffix {
820 item_name: parts.last().unwrap(),
821 in_which: &parts[..parts.len() - 1],
826 pub fn span(&self, id: NodeId) -> Span {
827 self.read(id); // reveals span from node
828 match self.find_entry(id) {
829 Some(EntryItem(_, item)) => item.span,
830 Some(EntryForeignItem(_, foreign_item)) => foreign_item.span,
831 Some(EntryTraitItem(_, trait_method)) => trait_method.span,
832 Some(EntryImplItem(_, impl_item)) => impl_item.span,
833 Some(EntryVariant(_, variant)) => variant.span,
834 Some(EntryField(_, field)) => field.span,
835 Some(EntryExpr(_, expr)) => expr.span,
836 Some(EntryStmt(_, stmt)) => stmt.span,
837 Some(EntryTy(_, ty)) => ty.span,
838 Some(EntryTraitRef(_, tr)) => tr.path.span,
839 Some(EntryLocal(_, pat)) => pat.span,
840 Some(EntryPat(_, pat)) => pat.span,
841 Some(EntryBlock(_, block)) => block.span,
842 Some(EntryStructCtor(_, _)) => self.expect_item(self.get_parent(id)).span,
843 Some(EntryLifetime(_, lifetime)) => lifetime.span,
844 Some(EntryTyParam(_, ty_param)) => ty_param.span,
845 Some(EntryVisibility(_, &Visibility::Restricted { ref path, .. })) => path.span,
846 Some(EntryVisibility(_, v)) => bug!("unexpected Visibility {:?}", v),
848 Some(RootCrate) => self.forest.krate.span,
849 Some(NotPresent) | None => {
850 bug!("hir::map::Map::span: id not in map: {:?}", id)
855 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
856 self.as_local_node_id(id).map(|id| self.span(id))
859 pub fn node_to_string(&self, id: NodeId) -> String {
860 node_id_to_string(self, id, true)
863 pub fn node_to_user_string(&self, id: NodeId) -> String {
864 node_id_to_string(self, id, false)
867 pub fn node_to_pretty_string(&self, id: NodeId) -> String {
868 print::to_string(self, |s| s.print_node(self.get(id)))
872 pub struct NodesMatchingSuffix<'a, 'hir:'a> {
874 item_name: &'a String,
875 in_which: &'a [String],
879 impl<'a, 'hir> NodesMatchingSuffix<'a, 'hir> {
880 /// Returns true only if some suffix of the module path for parent
881 /// matches `self.in_which`.
883 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
884 /// returns true if parent's path ends with the suffix
885 /// `x_0::x_1::...::x_k`.
886 fn suffix_matches(&self, parent: NodeId) -> bool {
887 let mut cursor = parent;
888 for part in self.in_which.iter().rev() {
889 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
890 None => return false,
891 Some((node_id, name)) => (node_id, name),
893 if mod_name != &**part {
896 cursor = self.map.get_parent(mod_id);
900 // Finds the first mod in parent chain for `id`, along with
903 // If `id` itself is a mod named `m` with parent `p`, then
904 // returns `Some(id, m, p)`. If `id` has no mod in its parent
905 // chain, then returns `None`.
906 fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
910 Some(NodeItem(item)) if item_is_mod(&item) =>
911 return Some((id, item.name)),
914 let parent = map.get_parent(id);
915 if parent == id { return None }
919 fn item_is_mod(item: &Item) -> bool {
928 // We are looking at some node `n` with a given name and parent
929 // id; do their names match what I am seeking?
930 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
931 name == &**self.item_name && self.suffix_matches(parent_of_n)
935 impl<'a, 'hir> Iterator for NodesMatchingSuffix<'a, 'hir> {
938 fn next(&mut self) -> Option<NodeId> {
941 if idx.as_usize() >= self.map.entry_count() {
944 self.idx = NodeId::from_u32(self.idx.as_u32() + 1);
945 let name = match self.map.find_entry(idx) {
946 Some(EntryItem(_, n)) => n.name(),
947 Some(EntryForeignItem(_, n))=> n.name(),
948 Some(EntryTraitItem(_, n)) => n.name(),
949 Some(EntryImplItem(_, n)) => n.name(),
950 Some(EntryVariant(_, n)) => n.name(),
951 Some(EntryField(_, n)) => n.name(),
954 if self.matches_names(self.map.get_parent(idx), name) {
962 fn name(&self) -> Name;
965 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
967 impl Named for Item { fn name(&self) -> Name { self.name } }
968 impl Named for ForeignItem { fn name(&self) -> Name { self.name } }
969 impl Named for Variant_ { fn name(&self) -> Name { self.name } }
970 impl Named for StructField { fn name(&self) -> Name { self.name } }
971 impl Named for TraitItem { fn name(&self) -> Name { self.name } }
972 impl Named for ImplItem { fn name(&self) -> Name { self.name } }
974 pub fn map_crate<'hir>(forest: &'hir mut Forest,
975 definitions: Definitions)
977 let mut collector = NodeCollector::root(&forest.krate);
978 intravisit::walk_crate(&mut collector, &forest.krate);
979 let map = collector.map;
981 if log_enabled!(::log::LogLevel::Debug) {
982 // This only makes sense for ordered stores; note the
983 // enumerate to count the number of entries.
984 let (entries_less_1, _) = map.iter().filter(|&x| {
989 }).enumerate().last().expect("AST map was empty after folding?");
991 let entries = entries_less_1 + 1;
992 let vector_length = map.len();
993 debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
994 entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
999 dep_graph: forest.dep_graph.clone(),
1001 definitions: definitions,
1002 inlined_bodies: RefCell::new(DefIdMap()),
1005 hir_id_validator::check_crate(&map);
1010 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1011 /// except it avoids creating a dependency on the whole crate.
1012 impl<'hir> print::PpAnn for Map<'hir> {
1013 fn nested(&self, state: &mut print::State, nested: print::Nested) -> io::Result<()> {
1015 Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1016 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1017 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1018 Nested::Body(id) => state.print_expr(&self.body(id).value),
1019 Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
1024 impl<'a> print::State<'a> {
1025 pub fn print_node(&mut self, node: Node) -> io::Result<()> {
1027 NodeItem(a) => self.print_item(&a),
1028 NodeForeignItem(a) => self.print_foreign_item(&a),
1029 NodeTraitItem(a) => self.print_trait_item(a),
1030 NodeImplItem(a) => self.print_impl_item(a),
1031 NodeVariant(a) => self.print_variant(&a),
1032 NodeExpr(a) => self.print_expr(&a),
1033 NodeStmt(a) => self.print_stmt(&a),
1034 NodeTy(a) => self.print_type(&a),
1035 NodeTraitRef(a) => self.print_trait_ref(&a),
1037 NodePat(a) => self.print_pat(&a),
1039 use syntax::print::pprust::PrintState;
1041 // containing cbox, will be closed by print-block at }
1042 self.cbox(print::indent_unit)?;
1043 // head-ibox, will be closed by print-block after {
1045 self.print_block(&a)
1047 NodeLifetime(a) => self.print_lifetime(&a),
1048 NodeVisibility(a) => self.print_visibility(&a),
1049 NodeTyParam(_) => bug!("cannot print TyParam"),
1050 NodeField(_) => bug!("cannot print StructField"),
1051 // these cases do not carry enough information in the
1052 // hir_map to reconstruct their full structure for pretty
1054 NodeStructCtor(_) => bug!("cannot print isolated StructCtor"),
1059 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
1060 let id_str = format!(" (id={})", id);
1061 let id_str = if include_id { &id_str[..] } else { "" };
1064 // This functionality is used for debugging, try to use TyCtxt to get
1065 // the user-friendly path, otherwise fall back to stringifying DefPath.
1066 ::ty::tls::with_opt(|tcx| {
1067 if let Some(tcx) = tcx {
1068 tcx.node_path_str(id)
1069 } else if let Some(path) = map.def_path_from_id(id) {
1070 path.data.into_iter().map(|elem| {
1071 elem.data.to_string()
1072 }).collect::<Vec<_>>().join("::")
1074 String::from("<missing path>")
1079 match map.find(id) {
1080 Some(NodeItem(item)) => {
1081 let item_str = match item.node {
1082 ItemExternCrate(..) => "extern crate",
1083 ItemUse(..) => "use",
1084 ItemStatic(..) => "static",
1085 ItemConst(..) => "const",
1087 ItemMod(..) => "mod",
1088 ItemForeignMod(..) => "foreign mod",
1089 ItemGlobalAsm(..) => "global asm",
1091 ItemEnum(..) => "enum",
1092 ItemStruct(..) => "struct",
1093 ItemUnion(..) => "union",
1094 ItemTrait(..) => "trait",
1095 ItemImpl(..) => "impl",
1096 ItemDefaultImpl(..) => "default impl",
1098 format!("{} {}{}", item_str, path_str(), id_str)
1100 Some(NodeForeignItem(_)) => {
1101 format!("foreign item {}{}", path_str(), id_str)
1103 Some(NodeImplItem(ii)) => {
1105 ImplItemKind::Const(..) => {
1106 format!("assoc const {} in {}{}", ii.name, path_str(), id_str)
1108 ImplItemKind::Method(..) => {
1109 format!("method {} in {}{}", ii.name, path_str(), id_str)
1111 ImplItemKind::Type(_) => {
1112 format!("assoc type {} in {}{}", ii.name, path_str(), id_str)
1116 Some(NodeTraitItem(ti)) => {
1117 let kind = match ti.node {
1118 TraitItemKind::Const(..) => "assoc constant",
1119 TraitItemKind::Method(..) => "trait method",
1120 TraitItemKind::Type(..) => "assoc type",
1123 format!("{} {} in {}{}", kind, ti.name, path_str(), id_str)
1125 Some(NodeVariant(ref variant)) => {
1126 format!("variant {} in {}{}",
1130 Some(NodeField(ref field)) => {
1131 format!("field {} in {}{}",
1135 Some(NodeExpr(_)) => {
1136 format!("expr {}{}", map.node_to_pretty_string(id), id_str)
1138 Some(NodeStmt(_)) => {
1139 format!("stmt {}{}", map.node_to_pretty_string(id), id_str)
1141 Some(NodeTy(_)) => {
1142 format!("type {}{}", map.node_to_pretty_string(id), id_str)
1144 Some(NodeTraitRef(_)) => {
1145 format!("trait_ref {}{}", map.node_to_pretty_string(id), id_str)
1147 Some(NodeLocal(_)) => {
1148 format!("local {}{}", map.node_to_pretty_string(id), id_str)
1150 Some(NodePat(_)) => {
1151 format!("pat {}{}", map.node_to_pretty_string(id), id_str)
1153 Some(NodeBlock(_)) => {
1154 format!("block {}{}", map.node_to_pretty_string(id), id_str)
1156 Some(NodeStructCtor(_)) => {
1157 format!("struct_ctor {}{}", path_str(), id_str)
1159 Some(NodeLifetime(_)) => {
1160 format!("lifetime {}{}", map.node_to_pretty_string(id), id_str)
1162 Some(NodeTyParam(ref ty_param)) => {
1163 format!("typaram {:?}{}", ty_param, id_str)
1165 Some(NodeVisibility(ref vis)) => {
1166 format!("visibility {:?}{}", vis, id_str)
1169 format!("unknown node{}", id_str)