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 middle::cstore::InlinedItem;
21 use hir::def_id::{CRATE_DEF_INDEX, DefId, DefIndex};
24 use syntax::ast::{self, Name, NodeId, CRATE_NODE_ID};
25 use syntax::codemap::Spanned;
29 use hir::print as pprust;
31 use arena::TypedArena;
32 use std::cell::RefCell;
41 #[derive(Copy, Clone, Debug)]
44 NodeForeignItem(&'ast ForeignItem),
45 NodeTraitItem(&'ast TraitItem),
46 NodeImplItem(&'ast ImplItem),
47 NodeVariant(&'ast Variant),
48 NodeField(&'ast StructField),
52 NodeTraitRef(&'ast TraitRef),
55 NodeBlock(&'ast Block),
57 /// NodeStructCtor represents a tuple struct.
58 NodeStructCtor(&'ast VariantData),
60 NodeLifetime(&'ast Lifetime),
61 NodeTyParam(&'ast TyParam),
62 NodeVisibility(&'ast Visibility),
64 NodeInlinedItem(&'ast InlinedItem),
67 /// Represents an entry and its parent NodeID.
68 /// The odd layout is to bring down the total size.
69 #[derive(Copy, Debug)]
70 pub enum MapEntry<'ast> {
71 /// Placeholder for holes in the map.
74 /// All the node types, with a parent ID.
75 EntryItem(NodeId, &'ast Item),
76 EntryForeignItem(NodeId, &'ast ForeignItem),
77 EntryTraitItem(NodeId, &'ast TraitItem),
78 EntryImplItem(NodeId, &'ast ImplItem),
79 EntryVariant(NodeId, &'ast Variant),
80 EntryField(NodeId, &'ast StructField),
81 EntryExpr(NodeId, &'ast Expr),
82 EntryStmt(NodeId, &'ast Stmt),
83 EntryTy(NodeId, &'ast Ty),
84 EntryTraitRef(NodeId, &'ast TraitRef),
85 EntryLocal(NodeId, &'ast Pat),
86 EntryPat(NodeId, &'ast Pat),
87 EntryBlock(NodeId, &'ast Block),
88 EntryStructCtor(NodeId, &'ast VariantData),
89 EntryLifetime(NodeId, &'ast Lifetime),
90 EntryTyParam(NodeId, &'ast TyParam),
91 EntryVisibility(NodeId, &'ast Visibility),
93 /// Roots for node trees.
95 RootInlinedParent(&'ast InlinedItem)
98 impl<'ast> Clone for MapEntry<'ast> {
99 fn clone(&self) -> MapEntry<'ast> {
104 impl<'ast> MapEntry<'ast> {
105 fn from_node(p: NodeId, node: Node<'ast>) -> MapEntry<'ast> {
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),
125 NodeInlinedItem(n) => RootInlinedParent(n),
129 fn parent_node(self) -> Option<NodeId> {
131 EntryItem(id, _) => id,
132 EntryForeignItem(id, _) => id,
133 EntryTraitItem(id, _) => id,
134 EntryImplItem(id, _) => id,
135 EntryVariant(id, _) => id,
136 EntryField(id, _) => id,
137 EntryExpr(id, _) => id,
138 EntryStmt(id, _) => id,
139 EntryTy(id, _) => id,
140 EntryTraitRef(id, _) => id,
141 EntryLocal(id, _) => id,
142 EntryPat(id, _) => id,
143 EntryBlock(id, _) => id,
144 EntryStructCtor(id, _) => id,
145 EntryLifetime(id, _) => id,
146 EntryTyParam(id, _) => id,
147 EntryVisibility(id, _) => id,
151 RootInlinedParent(_) => return None,
155 fn to_node(self) -> Option<Node<'ast>> {
157 EntryItem(_, n) => NodeItem(n),
158 EntryForeignItem(_, n) => NodeForeignItem(n),
159 EntryTraitItem(_, n) => NodeTraitItem(n),
160 EntryImplItem(_, n) => NodeImplItem(n),
161 EntryVariant(_, n) => NodeVariant(n),
162 EntryField(_, n) => NodeField(n),
163 EntryExpr(_, n) => NodeExpr(n),
164 EntryStmt(_, n) => NodeStmt(n),
165 EntryTy(_, n) => NodeTy(n),
166 EntryTraitRef(_, n) => NodeTraitRef(n),
167 EntryLocal(_, n) => NodeLocal(n),
168 EntryPat(_, n) => NodePat(n),
169 EntryBlock(_, n) => NodeBlock(n),
170 EntryStructCtor(_, n) => NodeStructCtor(n),
171 EntryLifetime(_, n) => NodeLifetime(n),
172 EntryTyParam(_, n) => NodeTyParam(n),
173 EntryVisibility(_, n) => NodeVisibility(n),
174 RootInlinedParent(n) => NodeInlinedItem(n),
180 /// Stores a crate and any number of inlined items from other crates.
183 pub dep_graph: DepGraph,
184 inlined_items: TypedArena<InlinedItem>
188 pub fn new(krate: Crate, dep_graph: &DepGraph) -> Forest {
191 dep_graph: dep_graph.clone(),
192 inlined_items: TypedArena::new()
196 pub fn krate<'ast>(&'ast self) -> &'ast Crate {
197 self.dep_graph.read(DepNode::Krate);
202 /// Represents a mapping from Node IDs to AST elements and their parent
205 pub struct Map<'ast> {
206 /// The backing storage for all the AST nodes.
207 pub forest: &'ast Forest,
209 /// Same as the dep_graph in forest, just available with one fewer
210 /// deref. This is a gratuitious micro-optimization.
211 pub dep_graph: DepGraph,
213 /// NodeIds are sequential integers from 0, so we can be
214 /// super-compact by storing them in a vector. Not everything with
215 /// a NodeId is in the map, but empirically the occupancy is about
216 /// 75-80%, so there's not too much overhead (certainly less than
217 /// a hashmap, since they (at the time of writing) have a maximum
218 /// of 75% occupancy).
220 /// Also, indexing is pretty quick when you've got a vector and
221 /// plain old integers.
222 map: RefCell<Vec<MapEntry<'ast>>>,
224 definitions: Definitions,
226 /// All NodeIds that are numerically greater or equal to this value come
227 /// from inlined items.
228 local_node_id_watermark: NodeId,
231 impl<'ast> Map<'ast> {
232 pub fn is_inlined_node_id(&self, id: NodeId) -> bool {
233 id >= self.local_node_id_watermark
236 /// Registers a read in the dependency graph of the AST node with
237 /// the given `id`. This needs to be called each time a public
238 /// function returns the HIR for a node -- in other words, when it
239 /// "reveals" the content of a node to the caller (who might not
240 /// otherwise have had access to those contents, and hence needs a
241 /// read recorded). If the function just returns a DefId or
242 /// NodeId, no actual content was returned, so no read is needed.
243 pub fn read(&self, id: NodeId) {
244 self.dep_graph.read(self.dep_node(id));
247 fn dep_node(&self, id0: NodeId) -> DepNode<DefId> {
248 let map = self.map.borrow();
250 if !self.is_inlined_node_id(id) {
251 let mut last_expr = None;
253 match map[id.as_usize()] {
254 EntryItem(_, item) => {
255 assert_eq!(id, item.id);
256 let def_id = self.local_def_id(id);
258 if let Some(last_id) = last_expr {
259 // The body of the item may have a separate dep node
260 // (Note that trait items don't currently have
261 // their own dep node, so there's also just one
262 // HirBody node for all the items)
263 if self.is_body(last_id, item) {
264 return DepNode::HirBody(def_id);
267 return DepNode::Hir(def_id);
270 EntryImplItem(_, item) => {
271 let def_id = self.local_def_id(id);
273 if let Some(last_id) = last_expr {
274 // The body of the item may have a separate dep node
275 if self.is_impl_item_body(last_id, item) {
276 return DepNode::HirBody(def_id);
279 return DepNode::Hir(def_id);
282 EntryForeignItem(p, _) |
283 EntryTraitItem(p, _) |
288 EntryTraitRef(p, _) |
292 EntryStructCtor(p, _) |
293 EntryLifetime(p, _) |
295 EntryVisibility(p, _) =>
299 last_expr = Some(id);
304 return DepNode::Hir(DefId::local(CRATE_DEF_INDEX));
307 RootInlinedParent(_) =>
308 bug!("node {} has inlined ancestor but is not inlined", id0),
311 // Some nodes, notably struct fields, are not
312 // present in the map for whatever reason, but
313 // they *do* have def-ids. So if we encounter an
314 // empty hole, check for that case.
315 return self.opt_local_def_id(id)
316 .map(|def_id| DepNode::Hir(def_id))
318 bug!("Walking parents from `{}` \
319 led to `NotPresent` at `{}`",
325 // reading from an inlined def-id is really a read out of
326 // the metadata from which we loaded the item.
328 match map[id.as_usize()] {
330 EntryForeignItem(p, _) |
331 EntryTraitItem(p, _) |
332 EntryImplItem(p, _) |
338 EntryTraitRef(p, _) |
342 EntryStructCtor(p, _) |
343 EntryLifetime(p, _) |
345 EntryVisibility(p, _) =>
348 RootInlinedParent(parent) =>
349 return DepNode::MetaData(parent.def_id),
352 bug!("node {} has crate ancestor but is inlined", id0),
355 bug!("node {} is inlined but not present in map", id0),
361 fn is_body(&self, node_id: NodeId, item: &Item) -> bool {
363 ItemFn(_, _, _, _, _, body) => body.node_id() == node_id,
364 // Since trait items currently don't get their own dep nodes,
365 // we check here whether node_id is the body of any of the items.
366 // If they get their own dep nodes, this can go away
367 ItemTrait(_, _, _, ref trait_items) => {
368 trait_items.iter().any(|trait_item| { match trait_item.node {
369 MethodTraitItem(_, Some(body)) => body.node_id() == node_id,
377 fn is_impl_item_body(&self, node_id: NodeId, item: &ImplItem) -> bool {
379 ImplItemKind::Method(_, body) => body.node_id() == node_id,
384 pub fn num_local_def_ids(&self) -> usize {
385 self.definitions.len()
388 pub fn definitions(&self) -> &Definitions {
392 pub fn def_key(&self, def_id: DefId) -> DefKey {
393 assert!(def_id.is_local());
394 self.definitions.def_key(def_id.index)
397 pub fn def_path_from_id(&self, id: NodeId) -> Option<DefPath> {
398 self.opt_local_def_id(id).map(|def_id| {
399 self.def_path(def_id)
403 pub fn def_path(&self, def_id: DefId) -> DefPath {
404 assert!(def_id.is_local());
405 self.definitions.def_path(def_id.index)
408 pub fn def_index_for_def_key(&self, def_key: DefKey) -> Option<DefIndex> {
409 self.definitions.def_index_for_def_key(def_key)
412 pub fn local_def_id(&self, node: NodeId) -> DefId {
413 self.opt_local_def_id(node).unwrap_or_else(|| {
414 bug!("local_def_id: no entry for `{}`, which has a map of `{:?}`",
415 node, self.find_entry(node))
419 pub fn opt_local_def_id(&self, node: NodeId) -> Option<DefId> {
420 self.definitions.opt_local_def_id(node)
423 pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
424 self.definitions.as_local_node_id(def_id)
427 fn entry_count(&self) -> usize {
428 self.map.borrow().len()
431 fn find_entry(&self, id: NodeId) -> Option<MapEntry<'ast>> {
432 self.map.borrow().get(id.as_usize()).cloned()
435 pub fn krate(&self) -> &'ast Crate {
439 pub fn impl_item(&self, id: ImplItemId) -> &'ast ImplItem {
440 self.read(id.node_id);
442 // NB: intentionally bypass `self.forest.krate()` so that we
443 // do not trigger a read of the whole krate here
444 self.forest.krate.impl_item(id)
447 /// Get the attributes on the krate. This is preferable to
448 /// invoking `krate.attrs` because it registers a tighter
449 /// dep-graph access.
450 pub fn krate_attrs(&self) -> &'ast [ast::Attribute] {
451 let crate_root_def_id = DefId::local(CRATE_DEF_INDEX);
452 self.dep_graph.read(DepNode::Hir(crate_root_def_id));
453 &self.forest.krate.attrs
456 /// Retrieve the Node corresponding to `id`, panicking if it cannot
458 pub fn get(&self, id: NodeId) -> Node<'ast> {
459 match self.find(id) {
460 Some(node) => node, // read recorded by `find`
461 None => bug!("couldn't find node id {} in the AST map", id)
465 pub fn get_if_local(&self, id: DefId) -> Option<Node<'ast>> {
466 self.as_local_node_id(id).map(|id| self.get(id)) // read recorded by `get`
469 /// Retrieve the Node corresponding to `id`, returning None if
471 pub fn find(&self, id: NodeId) -> Option<Node<'ast>> {
472 let result = self.find_entry(id).and_then(|x| x.to_node());
473 if result.is_some() {
479 /// Similar to get_parent, returns the parent node id or id if there is no
481 /// This function returns the immediate parent in the AST, whereas get_parent
482 /// returns the enclosing item. Note that this might not be the actual parent
483 /// node in the AST - some kinds of nodes are not in the map and these will
484 /// never appear as the parent_node. So you can always walk the parent_nodes
485 /// from a node to the root of the ast (unless you get the same id back here
486 /// that can happen if the id is not in the map itself or is just weird).
487 pub fn get_parent_node(&self, id: NodeId) -> NodeId {
488 self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
491 /// Check if the node is an argument. An argument is a local variable whose
492 /// immediate parent is an item or a closure.
493 pub fn is_argument(&self, id: NodeId) -> bool {
494 match self.find(id) {
495 Some(NodeLocal(_)) => (),
498 match self.find(self.get_parent_node(id)) {
500 Some(NodeTraitItem(_)) |
501 Some(NodeImplItem(_)) => true,
502 Some(NodeExpr(e)) => {
504 ExprClosure(..) => true,
512 /// If there is some error when walking the parents (e.g., a node does not
513 /// have a parent in the map or a node can't be found), then we return the
514 /// last good node id we found. Note that reaching the crate root (id == 0),
515 /// is not an error, since items in the crate module have the crate root as
517 fn walk_parent_nodes<F>(&self, start_id: NodeId, found: F) -> Result<NodeId, NodeId>
518 where F: Fn(&Node<'ast>) -> bool
520 let mut id = start_id;
522 let parent_node = self.get_parent_node(id);
523 if parent_node == CRATE_NODE_ID {
524 return Ok(CRATE_NODE_ID);
526 if parent_node == id {
530 let node = self.find_entry(parent_node);
534 let node = node.unwrap().to_node();
538 return Ok(parent_node);
542 return Err(parent_node);
549 /// Retrieve the NodeId for `id`'s parent item, or `id` itself if no
550 /// parent item is in this map. The "parent item" is the closest parent node
551 /// in the AST which is recorded by the map and is an item, either an item
552 /// in a module, trait, or impl.
553 pub fn get_parent(&self, id: NodeId) -> NodeId {
554 match self.walk_parent_nodes(id, |node| match *node {
558 NodeImplItem(_) => true,
566 /// Returns the NodeId of `id`'s nearest module parent, or `id` itself if no
567 /// module parent is in this map.
568 pub fn get_module_parent(&self, id: NodeId) -> NodeId {
569 match self.walk_parent_nodes(id, |node| match *node {
570 NodeItem(&Item { node: Item_::ItemMod(_), .. }) => true,
578 /// Returns the nearest enclosing scope. A scope is an item or block.
579 /// FIXME it is not clear to me that all items qualify as scopes - statics
580 /// and associated types probably shouldn't, for example. Behaviour in this
581 /// regard should be expected to be highly unstable.
582 pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
583 match self.walk_parent_nodes(id, |node| match *node {
588 NodeBlock(_) => true,
596 pub fn get_parent_did(&self, id: NodeId) -> DefId {
597 let parent = self.get_parent(id);
598 match self.find_entry(parent) {
599 Some(RootInlinedParent(ii)) => ii.def_id,
600 _ => self.local_def_id(parent)
604 pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
605 let parent = self.get_parent(id);
606 let abi = match self.find_entry(parent) {
607 Some(EntryItem(_, i)) => {
609 ItemForeignMod(ref nm) => Some(nm.abi),
613 /// Wrong but OK, because the only inlined foreign items are intrinsics.
614 Some(RootInlinedParent(_)) => Some(Abi::RustIntrinsic),
619 self.read(id); // reveals some of the content of a node
622 None => bug!("expected foreign mod or inlined parent, found {}",
623 self.node_to_string(parent))
627 pub fn expect_item(&self, id: NodeId) -> &'ast Item {
628 match self.find(id) { // read recorded by `find`
629 Some(NodeItem(item)) => item,
630 _ => bug!("expected item, found {}", self.node_to_string(id))
634 pub fn expect_impl_item(&self, id: NodeId) -> &'ast ImplItem {
635 match self.find(id) {
636 Some(NodeImplItem(item)) => item,
637 _ => bug!("expected impl item, found {}", self.node_to_string(id))
641 pub fn expect_trait_item(&self, id: NodeId) -> &'ast TraitItem {
642 match self.find(id) {
643 Some(NodeTraitItem(item)) => item,
644 _ => bug!("expected trait item, found {}", self.node_to_string(id))
648 pub fn expect_variant_data(&self, id: NodeId) -> &'ast VariantData {
649 match self.find(id) {
650 Some(NodeItem(i)) => {
652 ItemStruct(ref struct_def, _) |
653 ItemUnion(ref struct_def, _) => struct_def,
655 bug!("struct ID bound to non-struct {}",
656 self.node_to_string(id));
660 Some(NodeStructCtor(data)) => data,
661 Some(NodeVariant(variant)) => &variant.node.data,
663 bug!("expected struct or variant, found {}",
664 self.node_to_string(id));
669 pub fn expect_variant(&self, id: NodeId) -> &'ast Variant {
670 match self.find(id) {
671 Some(NodeVariant(variant)) => variant,
672 _ => bug!("expected variant, found {}", self.node_to_string(id)),
676 pub fn expect_foreign_item(&self, id: NodeId) -> &'ast ForeignItem {
677 match self.find(id) {
678 Some(NodeForeignItem(item)) => item,
679 _ => bug!("expected foreign item, found {}", self.node_to_string(id))
683 pub fn expect_expr(&self, id: NodeId) -> &'ast Expr {
684 match self.find(id) { // read recorded by find
685 Some(NodeExpr(expr)) => expr,
686 _ => bug!("expected expr, found {}", self.node_to_string(id))
690 pub fn expect_inlined_item(&self, id: NodeId) -> &'ast InlinedItem {
691 match self.find_entry(id) {
692 Some(RootInlinedParent(inlined_item)) => inlined_item,
693 _ => bug!("expected inlined item, found {}", self.node_to_string(id)),
697 pub fn expr(&self, id: ExprId) -> &'ast Expr {
698 self.expect_expr(id.node_id())
701 /// Returns the name associated with the given NodeId's AST.
702 pub fn name(&self, id: NodeId) -> Name {
704 NodeItem(i) => i.name,
705 NodeForeignItem(i) => i.name,
706 NodeImplItem(ii) => ii.name,
707 NodeTraitItem(ti) => ti.name,
708 NodeVariant(v) => v.node.name,
709 NodeField(f) => f.name,
710 NodeLifetime(lt) => lt.name,
711 NodeTyParam(tp) => tp.name,
712 NodeLocal(&Pat { node: PatKind::Binding(_,_,l,_), .. }) => l.node,
713 NodeStructCtor(_) => self.name(self.get_parent(id)),
714 _ => bug!("no name for {}", self.node_to_string(id))
718 /// Given a node ID, get a list of attributes associated with the AST
719 /// corresponding to the Node ID
720 pub fn attrs(&self, id: NodeId) -> &'ast [ast::Attribute] {
721 self.read(id); // reveals attributes on the node
722 let attrs = match self.find(id) {
723 Some(NodeItem(i)) => Some(&i.attrs[..]),
724 Some(NodeForeignItem(fi)) => Some(&fi.attrs[..]),
725 Some(NodeTraitItem(ref ti)) => Some(&ti.attrs[..]),
726 Some(NodeImplItem(ref ii)) => Some(&ii.attrs[..]),
727 Some(NodeVariant(ref v)) => Some(&v.node.attrs[..]),
728 Some(NodeField(ref f)) => Some(&f.attrs[..]),
729 Some(NodeExpr(ref e)) => Some(&*e.attrs),
730 Some(NodeStmt(ref s)) => Some(s.node.attrs()),
731 // unit/tuple structs take the attributes straight from
732 // the struct definition.
733 Some(NodeStructCtor(_)) => {
734 return self.attrs(self.get_parent(id));
741 /// Returns an iterator that yields the node id's with paths that
742 /// match `parts`. (Requires `parts` is non-empty.)
744 /// For example, if given `parts` equal to `["bar", "quux"]`, then
745 /// the iterator will produce node id's for items with paths
746 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
747 /// any other such items it can find in the map.
748 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
749 -> NodesMatchingSuffix<'a, 'ast> {
750 NodesMatchingSuffix {
752 item_name: parts.last().unwrap(),
753 in_which: &parts[..parts.len() - 1],
758 pub fn span(&self, id: NodeId) -> Span {
759 self.read(id); // reveals span from node
760 match self.find_entry(id) {
761 Some(EntryItem(_, item)) => item.span,
762 Some(EntryForeignItem(_, foreign_item)) => foreign_item.span,
763 Some(EntryTraitItem(_, trait_method)) => trait_method.span,
764 Some(EntryImplItem(_, impl_item)) => impl_item.span,
765 Some(EntryVariant(_, variant)) => variant.span,
766 Some(EntryField(_, field)) => field.span,
767 Some(EntryExpr(_, expr)) => expr.span,
768 Some(EntryStmt(_, stmt)) => stmt.span,
769 Some(EntryTy(_, ty)) => ty.span,
770 Some(EntryTraitRef(_, tr)) => tr.path.span,
771 Some(EntryLocal(_, pat)) => pat.span,
772 Some(EntryPat(_, pat)) => pat.span,
773 Some(EntryBlock(_, block)) => block.span,
774 Some(EntryStructCtor(_, _)) => self.expect_item(self.get_parent(id)).span,
775 Some(EntryLifetime(_, lifetime)) => lifetime.span,
776 Some(EntryTyParam(_, ty_param)) => ty_param.span,
777 Some(EntryVisibility(_, &Visibility::Restricted { ref path, .. })) => path.span,
778 Some(EntryVisibility(_, v)) => bug!("unexpected Visibility {:?}", v),
780 Some(RootCrate) => self.forest.krate.span,
781 Some(RootInlinedParent(parent)) => parent.body.span,
782 Some(NotPresent) | None => {
783 bug!("hir::map::Map::span: id not in map: {:?}", id)
788 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
789 self.as_local_node_id(id).map(|id| self.span(id))
792 pub fn node_to_string(&self, id: NodeId) -> String {
793 node_id_to_string(self, id, true)
796 pub fn node_to_user_string(&self, id: NodeId) -> String {
797 node_id_to_string(self, id, false)
801 pub struct NodesMatchingSuffix<'a, 'ast:'a> {
803 item_name: &'a String,
804 in_which: &'a [String],
808 impl<'a, 'ast> NodesMatchingSuffix<'a, 'ast> {
809 /// Returns true only if some suffix of the module path for parent
810 /// matches `self.in_which`.
812 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
813 /// returns true if parent's path ends with the suffix
814 /// `x_0::x_1::...::x_k`.
815 fn suffix_matches(&self, parent: NodeId) -> bool {
816 let mut cursor = parent;
817 for part in self.in_which.iter().rev() {
818 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
819 None => return false,
820 Some((node_id, name)) => (node_id, name),
822 if mod_name != &**part {
825 cursor = self.map.get_parent(mod_id);
829 // Finds the first mod in parent chain for `id`, along with
832 // If `id` itself is a mod named `m` with parent `p`, then
833 // returns `Some(id, m, p)`. If `id` has no mod in its parent
834 // chain, then returns `None`.
835 fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
839 Some(NodeItem(item)) if item_is_mod(&item) =>
840 return Some((id, item.name)),
843 let parent = map.get_parent(id);
844 if parent == id { return None }
848 fn item_is_mod(item: &Item) -> bool {
857 // We are looking at some node `n` with a given name and parent
858 // id; do their names match what I am seeking?
859 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
860 name == &**self.item_name && self.suffix_matches(parent_of_n)
864 impl<'a, 'ast> Iterator for NodesMatchingSuffix<'a, 'ast> {
867 fn next(&mut self) -> Option<NodeId> {
870 if idx.as_usize() >= self.map.entry_count() {
873 self.idx = NodeId::from_u32(self.idx.as_u32() + 1);
874 let name = match self.map.find_entry(idx) {
875 Some(EntryItem(_, n)) => n.name(),
876 Some(EntryForeignItem(_, n))=> n.name(),
877 Some(EntryTraitItem(_, n)) => n.name(),
878 Some(EntryImplItem(_, n)) => n.name(),
879 Some(EntryVariant(_, n)) => n.name(),
880 Some(EntryField(_, n)) => n.name(),
883 if self.matches_names(self.map.get_parent(idx), name) {
891 fn name(&self) -> Name;
894 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
896 impl Named for Item { fn name(&self) -> Name { self.name } }
897 impl Named for ForeignItem { fn name(&self) -> Name { self.name } }
898 impl Named for Variant_ { fn name(&self) -> Name { self.name } }
899 impl Named for StructField { fn name(&self) -> Name { self.name } }
900 impl Named for TraitItem { fn name(&self) -> Name { self.name } }
901 impl Named for ImplItem { fn name(&self) -> Name { self.name } }
903 pub fn map_crate<'ast>(forest: &'ast mut Forest,
904 definitions: Definitions)
906 let mut collector = NodeCollector::root(&forest.krate);
907 intravisit::walk_crate(&mut collector, &forest.krate);
908 let map = collector.map;
910 if log_enabled!(::log::DEBUG) {
911 // This only makes sense for ordered stores; note the
912 // enumerate to count the number of entries.
913 let (entries_less_1, _) = map.iter().filter(|&x| {
918 }).enumerate().last().expect("AST map was empty after folding?");
920 let entries = entries_less_1 + 1;
921 let vector_length = map.len();
922 debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
923 entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
926 let local_node_id_watermark = NodeId::new(map.len());
930 dep_graph: forest.dep_graph.clone(),
931 map: RefCell::new(map),
932 definitions: definitions,
933 local_node_id_watermark: local_node_id_watermark,
937 /// Used for items loaded from external crate that are being inlined into this
939 pub fn map_decoded_item<'ast>(map: &Map<'ast>,
941 ii_parent_id: NodeId)
942 -> &'ast InlinedItem {
943 let _ignore = map.forest.dep_graph.in_ignore();
945 let ii = map.forest.inlined_items.alloc(ii);
947 let mut collector = NodeCollector::extend(map.krate(),
950 mem::replace(&mut *map.map.borrow_mut(), vec![]));
951 ii.visit(&mut collector);
952 *map.map.borrow_mut() = collector.map;
957 pub trait NodePrinter {
958 fn print_node(&mut self, node: &Node) -> io::Result<()>;
961 impl<'a> NodePrinter for pprust::State<'a> {
962 fn print_node(&mut self, node: &Node) -> io::Result<()> {
964 NodeItem(a) => self.print_item(&a),
965 NodeForeignItem(a) => self.print_foreign_item(&a),
966 NodeTraitItem(a) => self.print_trait_item(a),
967 NodeImplItem(a) => self.print_impl_item(a),
968 NodeVariant(a) => self.print_variant(&a),
969 NodeExpr(a) => self.print_expr(&a),
970 NodeStmt(a) => self.print_stmt(&a),
971 NodeTy(a) => self.print_type(&a),
972 NodeTraitRef(a) => self.print_trait_ref(&a),
973 NodePat(a) => self.print_pat(&a),
974 NodeBlock(a) => self.print_block(&a),
975 NodeLifetime(a) => self.print_lifetime(&a),
976 NodeVisibility(a) => self.print_visibility(&a),
977 NodeTyParam(_) => bug!("cannot print TyParam"),
978 NodeField(_) => bug!("cannot print StructField"),
979 // these cases do not carry enough information in the
980 // ast_map to reconstruct their full structure for pretty
982 NodeLocal(_) => bug!("cannot print isolated Local"),
983 NodeStructCtor(_) => bug!("cannot print isolated StructCtor"),
985 NodeInlinedItem(_) => bug!("cannot print inlined item"),
990 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
991 let id_str = format!(" (id={})", id);
992 let id_str = if include_id { &id_str[..] } else { "" };
995 // This functionality is used for debugging, try to use TyCtxt to get
996 // the user-friendly path, otherwise fall back to stringifying DefPath.
997 ::ty::tls::with_opt(|tcx| {
998 if let Some(tcx) = tcx {
999 tcx.node_path_str(id)
1000 } else if let Some(path) = map.def_path_from_id(id) {
1001 path.data.into_iter().map(|elem| {
1002 elem.data.to_string()
1003 }).collect::<Vec<_>>().join("::")
1005 String::from("<missing path>")
1010 match map.find(id) {
1011 Some(NodeItem(item)) => {
1012 let item_str = match item.node {
1013 ItemExternCrate(..) => "extern crate",
1014 ItemUse(..) => "use",
1015 ItemStatic(..) => "static",
1016 ItemConst(..) => "const",
1018 ItemMod(..) => "mod",
1019 ItemForeignMod(..) => "foreign mod",
1021 ItemEnum(..) => "enum",
1022 ItemStruct(..) => "struct",
1023 ItemUnion(..) => "union",
1024 ItemTrait(..) => "trait",
1025 ItemImpl(..) => "impl",
1026 ItemDefaultImpl(..) => "default impl",
1028 format!("{} {}{}", item_str, path_str(), id_str)
1030 Some(NodeForeignItem(_)) => {
1031 format!("foreign item {}{}", path_str(), id_str)
1033 Some(NodeImplItem(ii)) => {
1035 ImplItemKind::Const(..) => {
1036 format!("assoc const {} in {}{}", ii.name, path_str(), id_str)
1038 ImplItemKind::Method(..) => {
1039 format!("method {} in {}{}", ii.name, path_str(), id_str)
1041 ImplItemKind::Type(_) => {
1042 format!("assoc type {} in {}{}", ii.name, path_str(), id_str)
1046 Some(NodeTraitItem(ti)) => {
1047 let kind = match ti.node {
1048 ConstTraitItem(..) => "assoc constant",
1049 MethodTraitItem(..) => "trait method",
1050 TypeTraitItem(..) => "assoc type",
1053 format!("{} {} in {}{}", kind, ti.name, path_str(), id_str)
1055 Some(NodeVariant(ref variant)) => {
1056 format!("variant {} in {}{}",
1060 Some(NodeField(ref field)) => {
1061 format!("field {} in {}{}",
1065 Some(NodeExpr(ref expr)) => {
1066 format!("expr {}{}", pprust::expr_to_string(&expr), id_str)
1068 Some(NodeStmt(ref stmt)) => {
1069 format!("stmt {}{}", pprust::stmt_to_string(&stmt), id_str)
1071 Some(NodeTy(ref ty)) => {
1072 format!("type {}{}", pprust::ty_to_string(&ty), id_str)
1074 Some(NodeTraitRef(ref tr)) => {
1075 format!("trait_ref {}{}", pprust::path_to_string(&tr.path), id_str)
1077 Some(NodeLocal(ref pat)) => {
1078 format!("local {}{}", pprust::pat_to_string(&pat), id_str)
1080 Some(NodePat(ref pat)) => {
1081 format!("pat {}{}", pprust::pat_to_string(&pat), id_str)
1083 Some(NodeBlock(ref block)) => {
1084 format!("block {}{}", pprust::block_to_string(&block), id_str)
1086 Some(NodeStructCtor(_)) => {
1087 format!("struct_ctor {}{}", path_str(), id_str)
1089 Some(NodeLifetime(ref l)) => {
1090 format!("lifetime {}{}",
1091 pprust::lifetime_to_string(&l), id_str)
1093 Some(NodeTyParam(ref ty_param)) => {
1094 format!("typaram {:?}{}", ty_param, id_str)
1096 Some(NodeVisibility(ref vis)) => {
1097 format!("visibility {:?}{}", vis, id_str)
1099 Some(NodeInlinedItem(_)) => {
1100 format!("inlined item {}", id_str)
1103 format!("unknown node{}", id_str)