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, InlinedRootPath};
18 use dep_graph::{DepGraph, DepNode};
20 use middle::cstore::InlinedItem;
21 use middle::cstore::InlinedItem as II;
22 use hir::def_id::{CRATE_DEF_INDEX, DefId, DefIndex};
25 use syntax::ast::{self, Name, NodeId, CRATE_NODE_ID};
26 use syntax::codemap::Spanned;
30 use hir::print as pprust;
32 use arena::TypedArena;
33 use std::cell::RefCell;
42 #[derive(Copy, Clone, Debug)]
45 NodeForeignItem(&'ast ForeignItem),
46 NodeTraitItem(&'ast TraitItem),
47 NodeImplItem(&'ast ImplItem),
48 NodeVariant(&'ast Variant),
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),
65 /// Represents an entry and its parent NodeID.
66 /// The odd layout is to bring down the total size.
67 #[derive(Copy, Debug)]
68 pub enum MapEntry<'ast> {
69 /// Placeholder for holes in the map.
72 /// All the node types, with a parent ID.
73 EntryItem(NodeId, &'ast Item),
74 EntryForeignItem(NodeId, &'ast ForeignItem),
75 EntryTraitItem(NodeId, &'ast TraitItem),
76 EntryImplItem(NodeId, &'ast ImplItem),
77 EntryVariant(NodeId, &'ast Variant),
78 EntryExpr(NodeId, &'ast Expr),
79 EntryStmt(NodeId, &'ast Stmt),
80 EntryTy(NodeId, &'ast Ty),
81 EntryTraitRef(NodeId, &'ast TraitRef),
82 EntryLocal(NodeId, &'ast Pat),
83 EntryPat(NodeId, &'ast Pat),
84 EntryBlock(NodeId, &'ast Block),
85 EntryStructCtor(NodeId, &'ast VariantData),
86 EntryLifetime(NodeId, &'ast Lifetime),
87 EntryTyParam(NodeId, &'ast TyParam),
88 EntryVisibility(NodeId, &'ast Visibility),
90 /// Roots for node trees.
92 RootInlinedParent(&'ast InlinedItem)
95 impl<'ast> Clone for MapEntry<'ast> {
96 fn clone(&self) -> MapEntry<'ast> {
101 impl<'ast> MapEntry<'ast> {
102 fn from_node(p: NodeId, node: Node<'ast>) -> MapEntry<'ast> {
104 NodeItem(n) => EntryItem(p, n),
105 NodeForeignItem(n) => EntryForeignItem(p, n),
106 NodeTraitItem(n) => EntryTraitItem(p, n),
107 NodeImplItem(n) => EntryImplItem(p, n),
108 NodeVariant(n) => EntryVariant(p, n),
109 NodeExpr(n) => EntryExpr(p, n),
110 NodeStmt(n) => EntryStmt(p, n),
111 NodeTy(n) => EntryTy(p, n),
112 NodeTraitRef(n) => EntryTraitRef(p, n),
113 NodeLocal(n) => EntryLocal(p, n),
114 NodePat(n) => EntryPat(p, n),
115 NodeBlock(n) => EntryBlock(p, n),
116 NodeStructCtor(n) => EntryStructCtor(p, n),
117 NodeLifetime(n) => EntryLifetime(p, n),
118 NodeTyParam(n) => EntryTyParam(p, n),
119 NodeVisibility(n) => EntryVisibility(p, n),
123 fn parent_node(self) -> Option<NodeId> {
125 EntryItem(id, _) => id,
126 EntryForeignItem(id, _) => id,
127 EntryTraitItem(id, _) => id,
128 EntryImplItem(id, _) => id,
129 EntryVariant(id, _) => id,
130 EntryExpr(id, _) => id,
131 EntryStmt(id, _) => id,
132 EntryTy(id, _) => id,
133 EntryTraitRef(id, _) => id,
134 EntryLocal(id, _) => id,
135 EntryPat(id, _) => id,
136 EntryBlock(id, _) => id,
137 EntryStructCtor(id, _) => id,
138 EntryLifetime(id, _) => id,
139 EntryTyParam(id, _) => id,
140 EntryVisibility(id, _) => id,
144 RootInlinedParent(_) => return None,
148 fn to_node(self) -> Option<Node<'ast>> {
150 EntryItem(_, n) => NodeItem(n),
151 EntryForeignItem(_, n) => NodeForeignItem(n),
152 EntryTraitItem(_, n) => NodeTraitItem(n),
153 EntryImplItem(_, n) => NodeImplItem(n),
154 EntryVariant(_, n) => NodeVariant(n),
155 EntryExpr(_, n) => NodeExpr(n),
156 EntryStmt(_, n) => NodeStmt(n),
157 EntryTy(_, n) => NodeTy(n),
158 EntryTraitRef(_, n) => NodeTraitRef(n),
159 EntryLocal(_, n) => NodeLocal(n),
160 EntryPat(_, n) => NodePat(n),
161 EntryBlock(_, n) => NodeBlock(n),
162 EntryStructCtor(_, n) => NodeStructCtor(n),
163 EntryLifetime(_, n) => NodeLifetime(n),
164 EntryTyParam(_, n) => NodeTyParam(n),
165 EntryVisibility(_, n) => NodeVisibility(n),
171 /// Stores a crate and any number of inlined items from other crates.
174 pub dep_graph: DepGraph,
175 inlined_items: TypedArena<InlinedItem>
179 pub fn new(krate: Crate, dep_graph: &DepGraph) -> Forest {
182 dep_graph: dep_graph.clone(),
183 inlined_items: TypedArena::new()
187 pub fn krate<'ast>(&'ast self) -> &'ast Crate {
188 self.dep_graph.read(DepNode::Krate);
193 /// Represents a mapping from Node IDs to AST elements and their parent
196 pub struct Map<'ast> {
197 /// The backing storage for all the AST nodes.
198 pub forest: &'ast Forest,
200 /// Same as the dep_graph in forest, just available with one fewer
201 /// deref. This is a gratuitious micro-optimization.
202 pub dep_graph: DepGraph,
204 /// NodeIds are sequential integers from 0, so we can be
205 /// super-compact by storing them in a vector. Not everything with
206 /// a NodeId is in the map, but empirically the occupancy is about
207 /// 75-80%, so there's not too much overhead (certainly less than
208 /// a hashmap, since they (at the time of writing) have a maximum
209 /// of 75% occupancy).
211 /// Also, indexing is pretty quick when you've got a vector and
212 /// plain old integers.
213 map: RefCell<Vec<MapEntry<'ast>>>,
215 definitions: RefCell<Definitions>,
217 /// All NodeIds that are numerically greater or equal to this value come
218 /// from inlined items.
219 local_node_id_watermark: NodeId,
221 /// All def-indices that are numerically greater or equal to this value come
222 /// from inlined items.
223 local_def_id_watermark: usize,
226 impl<'ast> Map<'ast> {
227 pub fn is_inlined_def_id(&self, id: DefId) -> bool {
228 id.is_local() && id.index.as_usize() >= self.local_def_id_watermark
231 pub fn is_inlined_node_id(&self, id: NodeId) -> bool {
232 id >= self.local_node_id_watermark
235 /// Registers a read in the dependency graph of the AST node with
236 /// the given `id`. This needs to be called each time a public
237 /// function returns the HIR for a node -- in other words, when it
238 /// "reveals" the content of a node to the caller (who might not
239 /// otherwise have had access to those contents, and hence needs a
240 /// read recorded). If the function just returns a DefId or
241 /// NodeId, no actual content was returned, so no read is needed.
242 pub fn read(&self, id: NodeId) {
243 self.dep_graph.read(self.dep_node(id));
246 fn dep_node(&self, id0: NodeId) -> DepNode<DefId> {
247 let map = self.map.borrow();
249 if !self.is_inlined_node_id(id) {
251 match map[id.as_usize()] {
252 EntryItem(_, item) => {
253 let def_id = self.local_def_id(item.id);
256 // You would expect that `item.id == id`, but this
257 // is not always the case. In particular, for a
258 // ViewPath item like `use self::{mem, foo}`, we
259 // map the ids for `mem` and `foo` to the
260 // enclosing view path item. This seems mega super
261 // ultra wrong, but then who am I to judge?
263 assert!(!self.is_inlined_def_id(def_id));
264 return DepNode::Hir(def_id);
267 EntryImplItem(..) => {
268 let def_id = self.local_def_id(id);
269 assert!(!self.is_inlined_def_id(def_id));
270 return DepNode::Hir(def_id);
273 EntryForeignItem(p, _) |
274 EntryTraitItem(p, _) |
279 EntryTraitRef(p, _) |
283 EntryStructCtor(p, _) |
284 EntryLifetime(p, _) |
286 EntryVisibility(p, _) =>
290 return DepNode::Krate,
292 RootInlinedParent(_) =>
293 bug!("node {} has inlined ancestor but is not inlined", id0),
296 // Some nodes, notably struct fields, are not
297 // present in the map for whatever reason, but
298 // they *do* have def-ids. So if we encounter an
299 // empty hole, check for that case.
300 return self.opt_local_def_id(id)
301 .map(|def_id| DepNode::Hir(def_id))
303 bug!("Walking parents from `{}` \
304 led to `NotPresent` at `{}`",
310 // reading from an inlined def-id is really a read out of
311 // the metadata from which we loaded the item.
313 match map[id.as_usize()] {
315 EntryForeignItem(p, _) |
316 EntryTraitItem(p, _) |
317 EntryImplItem(p, _) |
322 EntryTraitRef(p, _) |
326 EntryStructCtor(p, _) |
327 EntryLifetime(p, _) |
329 EntryVisibility(p, _) =>
332 RootInlinedParent(parent) => match *parent {
333 InlinedItem::Item(def_id, _) |
334 InlinedItem::TraitItem(def_id, _) |
335 InlinedItem::ImplItem(def_id, _) =>
336 return DepNode::MetaData(def_id)
340 bug!("node {} has crate ancestor but is inlined", id0),
343 bug!("node {} is inlined but not present in map", id0),
349 pub fn num_local_def_ids(&self) -> usize {
350 self.definitions.borrow().len()
353 pub fn def_key(&self, def_id: DefId) -> DefKey {
354 assert!(def_id.is_local());
355 self.definitions.borrow().def_key(def_id.index)
358 pub fn def_path_from_id(&self, id: NodeId) -> Option<DefPath> {
359 self.opt_local_def_id(id).map(|def_id| {
360 self.def_path(def_id)
364 pub fn def_path(&self, def_id: DefId) -> DefPath {
365 assert!(def_id.is_local());
366 self.definitions.borrow().def_path(def_id.index)
369 pub fn def_index_for_def_key(&self, def_key: DefKey) -> Option<DefIndex> {
370 self.definitions.borrow().def_index_for_def_key(def_key)
373 pub fn local_def_id(&self, node: NodeId) -> DefId {
374 self.opt_local_def_id(node).unwrap_or_else(|| {
375 bug!("local_def_id: no entry for `{}`, which has a map of `{:?}`",
376 node, self.find_entry(node))
380 pub fn opt_local_def_id(&self, node: NodeId) -> Option<DefId> {
381 self.definitions.borrow().opt_local_def_id(node)
384 pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
385 self.definitions.borrow().as_local_node_id(def_id)
388 fn entry_count(&self) -> usize {
389 self.map.borrow().len()
392 fn find_entry(&self, id: NodeId) -> Option<MapEntry<'ast>> {
393 self.map.borrow().get(id.as_usize()).cloned()
396 pub fn krate(&self) -> &'ast Crate {
400 pub fn impl_item(&self, id: ImplItemId) -> &'ast ImplItem {
401 self.read(id.node_id);
403 // NB: intentionally bypass `self.forest.krate()` so that we
404 // do not trigger a read of the whole krate here
405 self.forest.krate.impl_item(id)
408 /// Get the attributes on the krate. This is preferable to
409 /// invoking `krate.attrs` because it registers a tighter
410 /// dep-graph access.
411 pub fn krate_attrs(&self) -> &'ast [ast::Attribute] {
412 let crate_root_def_id = DefId::local(CRATE_DEF_INDEX);
413 self.dep_graph.read(DepNode::Hir(crate_root_def_id));
414 &self.forest.krate.attrs
417 /// Retrieve the Node corresponding to `id`, panicking if it cannot
419 pub fn get(&self, id: NodeId) -> Node<'ast> {
420 match self.find(id) {
421 Some(node) => node, // read recorded by `find`
422 None => bug!("couldn't find node id {} in the AST map", id)
426 pub fn get_if_local(&self, id: DefId) -> Option<Node<'ast>> {
427 self.as_local_node_id(id).map(|id| self.get(id)) // read recorded by `get`
430 /// Retrieve the Node corresponding to `id`, returning None if
432 pub fn find(&self, id: NodeId) -> Option<Node<'ast>> {
433 let result = self.find_entry(id).and_then(|x| x.to_node());
434 if result.is_some() {
440 /// Similar to get_parent, returns the parent node id or id if there is no
442 /// This function returns the immediate parent in the AST, whereas get_parent
443 /// returns the enclosing item. Note that this might not be the actual parent
444 /// node in the AST - some kinds of nodes are not in the map and these will
445 /// never appear as the parent_node. So you can always walk the parent_nodes
446 /// from a node to the root of the ast (unless you get the same id back here
447 /// that can happen if the id is not in the map itself or is just weird).
448 pub fn get_parent_node(&self, id: NodeId) -> NodeId {
449 self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
452 /// Check if the node is an argument. An argument is a local variable whose
453 /// immediate parent is an item or a closure.
454 pub fn is_argument(&self, id: NodeId) -> bool {
455 match self.find(id) {
456 Some(NodeLocal(_)) => (),
459 match self.find(self.get_parent_node(id)) {
461 Some(NodeTraitItem(_)) |
462 Some(NodeImplItem(_)) => true,
463 Some(NodeExpr(e)) => {
465 ExprClosure(..) => true,
473 /// If there is some error when walking the parents (e.g., a node does not
474 /// have a parent in the map or a node can't be found), then we return the
475 /// last good node id we found. Note that reaching the crate root (id == 0),
476 /// is not an error, since items in the crate module have the crate root as
478 fn walk_parent_nodes<F>(&self, start_id: NodeId, found: F) -> Result<NodeId, NodeId>
479 where F: Fn(&Node<'ast>) -> bool
481 let mut id = start_id;
483 let parent_node = self.get_parent_node(id);
484 if parent_node == CRATE_NODE_ID {
485 return Ok(CRATE_NODE_ID);
487 if parent_node == id {
491 let node = self.find_entry(parent_node);
495 let node = node.unwrap().to_node();
499 return Ok(parent_node);
503 return Err(parent_node);
510 /// Retrieve the NodeId for `id`'s parent item, or `id` itself if no
511 /// parent item is in this map. The "parent item" is the closest parent node
512 /// in the AST which is recorded by the map and is an item, either an item
513 /// in a module, trait, or impl.
514 pub fn get_parent(&self, id: NodeId) -> NodeId {
515 match self.walk_parent_nodes(id, |node| match *node {
519 NodeImplItem(_) => true,
527 /// Returns the NodeId of `id`'s nearest module parent, or `id` itself if no
528 /// module parent is in this map.
529 pub fn get_module_parent(&self, id: NodeId) -> NodeId {
530 match self.walk_parent_nodes(id, |node| match *node {
531 NodeItem(&Item { node: Item_::ItemMod(_), .. }) => true,
539 /// Returns the nearest enclosing scope. A scope is an item or block.
540 /// FIXME it is not clear to me that all items qualify as scopes - statics
541 /// and associated types probably shouldn't, for example. Behaviour in this
542 /// regard should be expected to be highly unstable.
543 pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
544 match self.walk_parent_nodes(id, |node| match *node {
549 NodeBlock(_) => true,
557 pub fn get_parent_did(&self, id: NodeId) -> DefId {
558 let parent = self.get_parent(id);
559 match self.find_entry(parent) {
560 Some(RootInlinedParent(&II::TraitItem(did, _))) |
561 Some(RootInlinedParent(&II::ImplItem(did, _))) => did,
562 _ => self.local_def_id(parent)
566 pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
567 let parent = self.get_parent(id);
568 let abi = match self.find_entry(parent) {
569 Some(EntryItem(_, i)) => {
571 ItemForeignMod(ref nm) => Some(nm.abi),
575 /// Wrong but OK, because the only inlined foreign items are intrinsics.
576 Some(RootInlinedParent(_)) => Some(Abi::RustIntrinsic),
581 self.read(id); // reveals some of the content of a node
584 None => bug!("expected foreign mod or inlined parent, found {}",
585 self.node_to_string(parent))
589 pub fn expect_item(&self, id: NodeId) -> &'ast Item {
590 match self.find(id) { // read recorded by `find`
591 Some(NodeItem(item)) => item,
592 _ => bug!("expected item, found {}", self.node_to_string(id))
596 pub fn expect_impl_item(&self, id: NodeId) -> &'ast ImplItem {
597 match self.find(id) {
598 Some(NodeImplItem(item)) => item,
599 _ => bug!("expected impl item, found {}", self.node_to_string(id))
603 pub fn expect_trait_item(&self, id: NodeId) -> &'ast TraitItem {
604 match self.find(id) {
605 Some(NodeTraitItem(item)) => item,
606 _ => bug!("expected trait item, found {}", self.node_to_string(id))
610 pub fn expect_variant_data(&self, id: NodeId) -> &'ast VariantData {
611 match self.find(id) {
612 Some(NodeItem(i)) => {
614 ItemStruct(ref struct_def, _) |
615 ItemUnion(ref struct_def, _) => struct_def,
617 bug!("struct ID bound to non-struct {}",
618 self.node_to_string(id));
622 Some(NodeStructCtor(data)) => data,
623 Some(NodeVariant(variant)) => &variant.node.data,
625 bug!("expected struct or variant, found {}",
626 self.node_to_string(id));
631 pub fn expect_variant(&self, id: NodeId) -> &'ast Variant {
632 match self.find(id) {
633 Some(NodeVariant(variant)) => variant,
634 _ => bug!("expected variant, found {}", self.node_to_string(id)),
638 pub fn expect_foreign_item(&self, id: NodeId) -> &'ast ForeignItem {
639 match self.find(id) {
640 Some(NodeForeignItem(item)) => item,
641 _ => bug!("expected foreign item, found {}", self.node_to_string(id))
645 pub fn expect_expr(&self, id: NodeId) -> &'ast Expr {
646 match self.find(id) { // read recorded by find
647 Some(NodeExpr(expr)) => expr,
648 _ => bug!("expected expr, found {}", self.node_to_string(id))
652 pub fn expect_inlined_item(&self, id: NodeId) -> &'ast InlinedItem {
653 match self.find_entry(id) {
654 Some(RootInlinedParent(inlined_item)) => inlined_item,
655 _ => bug!("expected inlined item, found {}", self.node_to_string(id)),
659 /// Returns the name associated with the given NodeId's AST.
660 pub fn name(&self, id: NodeId) -> Name {
662 NodeItem(i) => i.name,
663 NodeForeignItem(i) => i.name,
664 NodeImplItem(ii) => ii.name,
665 NodeTraitItem(ti) => ti.name,
666 NodeVariant(v) => v.node.name,
667 NodeLifetime(lt) => lt.name,
668 NodeTyParam(tp) => tp.name,
669 NodeLocal(&Pat { node: PatKind::Binding(_,l,_), .. }) => l.node,
670 NodeStructCtor(_) => self.name(self.get_parent(id)),
671 _ => bug!("no name for {}", self.node_to_string(id))
675 /// Given a node ID, get a list of attributes associated with the AST
676 /// corresponding to the Node ID
677 pub fn attrs(&self, id: NodeId) -> &'ast [ast::Attribute] {
678 self.read(id); // reveals attributes on the node
679 let attrs = match self.find(id) {
680 Some(NodeItem(i)) => Some(&i.attrs[..]),
681 Some(NodeForeignItem(fi)) => Some(&fi.attrs[..]),
682 Some(NodeTraitItem(ref ti)) => Some(&ti.attrs[..]),
683 Some(NodeImplItem(ref ii)) => Some(&ii.attrs[..]),
684 Some(NodeVariant(ref v)) => Some(&v.node.attrs[..]),
685 Some(NodeExpr(ref e)) => Some(&*e.attrs),
686 Some(NodeStmt(ref s)) => Some(s.node.attrs()),
687 // unit/tuple structs take the attributes straight from
688 // the struct definition.
689 Some(NodeStructCtor(_)) => {
690 return self.attrs(self.get_parent(id));
697 /// Returns an iterator that yields the node id's with paths that
698 /// match `parts`. (Requires `parts` is non-empty.)
700 /// For example, if given `parts` equal to `["bar", "quux"]`, then
701 /// the iterator will produce node id's for items with paths
702 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
703 /// any other such items it can find in the map.
704 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
705 -> NodesMatchingSuffix<'a, 'ast> {
706 NodesMatchingSuffix {
708 item_name: parts.last().unwrap(),
709 in_which: &parts[..parts.len() - 1],
714 pub fn opt_span(&self, id: NodeId) -> Option<Span> {
715 let sp = match self.find(id) {
716 Some(NodeItem(item)) => item.span,
717 Some(NodeForeignItem(foreign_item)) => foreign_item.span,
718 Some(NodeTraitItem(trait_method)) => trait_method.span,
719 Some(NodeImplItem(ref impl_item)) => impl_item.span,
720 Some(NodeVariant(variant)) => variant.span,
721 Some(NodeExpr(expr)) => expr.span,
722 Some(NodeStmt(stmt)) => stmt.span,
723 Some(NodeTy(ty)) => ty.span,
724 Some(NodeTraitRef(tr)) => tr.path.span,
725 Some(NodeLocal(pat)) => pat.span,
726 Some(NodePat(pat)) => pat.span,
727 Some(NodeBlock(block)) => block.span,
728 Some(NodeStructCtor(_)) => self.expect_item(self.get_parent(id)).span,
729 Some(NodeTyParam(ty_param)) => ty_param.span,
730 Some(NodeVisibility(&Visibility::Restricted { ref path, .. })) => path.span,
736 pub fn span(&self, id: NodeId) -> Span {
737 self.read(id); // reveals span from node
739 .unwrap_or_else(|| bug!("AstMap.span: could not find span for id {:?}", id))
742 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
743 self.as_local_node_id(id).map(|id| self.span(id))
746 pub fn def_id_span(&self, def_id: DefId, fallback: Span) -> Span {
747 if let Some(node_id) = self.as_local_node_id(def_id) {
748 self.opt_span(node_id).unwrap_or(fallback)
754 pub fn node_to_string(&self, id: NodeId) -> String {
755 node_id_to_string(self, id, true)
758 pub fn node_to_user_string(&self, id: NodeId) -> String {
759 node_id_to_string(self, id, false)
763 pub struct NodesMatchingSuffix<'a, 'ast:'a> {
765 item_name: &'a String,
766 in_which: &'a [String],
770 impl<'a, 'ast> NodesMatchingSuffix<'a, 'ast> {
771 /// Returns true only if some suffix of the module path for parent
772 /// matches `self.in_which`.
774 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
775 /// returns true if parent's path ends with the suffix
776 /// `x_0::x_1::...::x_k`.
777 fn suffix_matches(&self, parent: NodeId) -> bool {
778 let mut cursor = parent;
779 for part in self.in_which.iter().rev() {
780 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
781 None => return false,
782 Some((node_id, name)) => (node_id, name),
784 if mod_name != &**part {
787 cursor = self.map.get_parent(mod_id);
791 // Finds the first mod in parent chain for `id`, along with
794 // If `id` itself is a mod named `m` with parent `p`, then
795 // returns `Some(id, m, p)`. If `id` has no mod in its parent
796 // chain, then returns `None`.
797 fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
801 Some(NodeItem(item)) if item_is_mod(&item) =>
802 return Some((id, item.name)),
805 let parent = map.get_parent(id);
806 if parent == id { return None }
810 fn item_is_mod(item: &Item) -> bool {
819 // We are looking at some node `n` with a given name and parent
820 // id; do their names match what I am seeking?
821 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
822 name == &**self.item_name && self.suffix_matches(parent_of_n)
826 impl<'a, 'ast> Iterator for NodesMatchingSuffix<'a, 'ast> {
829 fn next(&mut self) -> Option<NodeId> {
832 if idx.as_usize() >= self.map.entry_count() {
835 self.idx = NodeId::from_u32(self.idx.as_u32() + 1);
836 let name = match self.map.find_entry(idx) {
837 Some(EntryItem(_, n)) => n.name(),
838 Some(EntryForeignItem(_, n))=> n.name(),
839 Some(EntryTraitItem(_, n)) => n.name(),
840 Some(EntryImplItem(_, n)) => n.name(),
841 Some(EntryVariant(_, n)) => n.name(),
844 if self.matches_names(self.map.get_parent(idx), name) {
852 fn name(&self) -> Name;
855 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
857 impl Named for Item { fn name(&self) -> Name { self.name } }
858 impl Named for ForeignItem { fn name(&self) -> Name { self.name } }
859 impl Named for Variant_ { fn name(&self) -> Name { self.name } }
860 impl Named for TraitItem { fn name(&self) -> Name { self.name } }
861 impl Named for ImplItem { fn name(&self) -> Name { self.name } }
863 pub fn map_crate<'ast>(forest: &'ast mut Forest,
864 definitions: Definitions)
866 let mut collector = NodeCollector::root(&forest.krate);
867 intravisit::walk_crate(&mut collector, &forest.krate);
868 let map = collector.map;
870 if log_enabled!(::log::DEBUG) {
871 // This only makes sense for ordered stores; note the
872 // enumerate to count the number of entries.
873 let (entries_less_1, _) = map.iter().filter(|&x| {
878 }).enumerate().last().expect("AST map was empty after folding?");
880 let entries = entries_less_1 + 1;
881 let vector_length = map.len();
882 debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
883 entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
886 let local_node_id_watermark = NodeId::new(map.len());
887 let local_def_id_watermark = definitions.len();
891 dep_graph: forest.dep_graph.clone(),
892 map: RefCell::new(map),
893 definitions: RefCell::new(definitions),
894 local_node_id_watermark: local_node_id_watermark,
895 local_def_id_watermark: local_def_id_watermark,
899 /// Used for items loaded from external crate that are being inlined into this
901 pub fn map_decoded_item<'ast>(map: &Map<'ast>,
902 parent_def_path: DefPath,
903 parent_def_id: DefId,
905 ii_parent_id: NodeId)
906 -> &'ast InlinedItem {
907 let _ignore = map.forest.dep_graph.in_ignore();
909 let ii = map.forest.inlined_items.alloc(ii);
911 let defs = &mut *map.definitions.borrow_mut();
912 let mut def_collector = DefCollector::extend(ii_parent_id,
913 parent_def_path.clone(),
916 def_collector.walk_item(ii, map.krate());
918 let mut collector = NodeCollector::extend(map.krate(),
923 mem::replace(&mut *map.map.borrow_mut(), vec![]));
924 ii.visit(&mut collector);
925 *map.map.borrow_mut() = collector.map;
930 pub trait NodePrinter {
931 fn print_node(&mut self, node: &Node) -> io::Result<()>;
934 impl<'a> NodePrinter for pprust::State<'a> {
935 fn print_node(&mut self, node: &Node) -> io::Result<()> {
937 NodeItem(a) => self.print_item(&a),
938 NodeForeignItem(a) => self.print_foreign_item(&a),
939 NodeTraitItem(a) => self.print_trait_item(a),
940 NodeImplItem(a) => self.print_impl_item(a),
941 NodeVariant(a) => self.print_variant(&a),
942 NodeExpr(a) => self.print_expr(&a),
943 NodeStmt(a) => self.print_stmt(&a),
944 NodeTy(a) => self.print_type(&a),
945 NodeTraitRef(a) => self.print_trait_ref(&a),
946 NodePat(a) => self.print_pat(&a),
947 NodeBlock(a) => self.print_block(&a),
948 NodeLifetime(a) => self.print_lifetime(&a),
949 NodeVisibility(a) => self.print_visibility(&a),
950 NodeTyParam(_) => bug!("cannot print TyParam"),
951 // these cases do not carry enough information in the
952 // ast_map to reconstruct their full structure for pretty
954 NodeLocal(_) => bug!("cannot print isolated Local"),
955 NodeStructCtor(_) => bug!("cannot print isolated StructCtor"),
960 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
961 let id_str = format!(" (id={})", id);
962 let id_str = if include_id { &id_str[..] } else { "" };
965 // This functionality is used for debugging, try to use TyCtxt to get
966 // the user-friendly path, otherwise fall back to stringifying DefPath.
967 ::ty::tls::with_opt(|tcx| {
968 if let Some(tcx) = tcx {
969 tcx.node_path_str(id)
970 } else if let Some(path) = map.def_path_from_id(id) {
971 path.data.into_iter().map(|elem| {
972 elem.data.to_string()
973 }).collect::<Vec<_>>().join("::")
975 String::from("<missing path>")
981 Some(NodeItem(item)) => {
982 let item_str = match item.node {
983 ItemExternCrate(..) => "extern crate",
984 ItemUse(..) => "use",
985 ItemStatic(..) => "static",
986 ItemConst(..) => "const",
988 ItemMod(..) => "mod",
989 ItemForeignMod(..) => "foreign mod",
991 ItemEnum(..) => "enum",
992 ItemStruct(..) => "struct",
993 ItemUnion(..) => "union",
994 ItemTrait(..) => "trait",
995 ItemImpl(..) => "impl",
996 ItemDefaultImpl(..) => "default impl",
998 format!("{} {}{}", item_str, path_str(), id_str)
1000 Some(NodeForeignItem(_)) => {
1001 format!("foreign item {}{}", path_str(), id_str)
1003 Some(NodeImplItem(ii)) => {
1005 ImplItemKind::Const(..) => {
1006 format!("assoc const {} in {}{}", ii.name, path_str(), id_str)
1008 ImplItemKind::Method(..) => {
1009 format!("method {} in {}{}", ii.name, path_str(), id_str)
1011 ImplItemKind::Type(_) => {
1012 format!("assoc type {} in {}{}", ii.name, path_str(), id_str)
1016 Some(NodeTraitItem(ti)) => {
1017 let kind = match ti.node {
1018 ConstTraitItem(..) => "assoc constant",
1019 MethodTraitItem(..) => "trait method",
1020 TypeTraitItem(..) => "assoc type",
1023 format!("{} {} in {}{}", kind, ti.name, path_str(), id_str)
1025 Some(NodeVariant(ref variant)) => {
1026 format!("variant {} in {}{}",
1030 Some(NodeExpr(ref expr)) => {
1031 format!("expr {}{}", pprust::expr_to_string(&expr), id_str)
1033 Some(NodeStmt(ref stmt)) => {
1034 format!("stmt {}{}", pprust::stmt_to_string(&stmt), id_str)
1036 Some(NodeTy(ref ty)) => {
1037 format!("type {}{}", pprust::ty_to_string(&ty), id_str)
1039 Some(NodeTraitRef(ref tr)) => {
1040 format!("trait_ref {}{}", pprust::path_to_string(&tr.path), id_str)
1042 Some(NodeLocal(ref pat)) => {
1043 format!("local {}{}", pprust::pat_to_string(&pat), id_str)
1045 Some(NodePat(ref pat)) => {
1046 format!("pat {}{}", pprust::pat_to_string(&pat), id_str)
1048 Some(NodeBlock(ref block)) => {
1049 format!("block {}{}", pprust::block_to_string(&block), id_str)
1051 Some(NodeStructCtor(_)) => {
1052 format!("struct_ctor {}{}", path_str(), id_str)
1054 Some(NodeLifetime(ref l)) => {
1055 format!("lifetime {}{}",
1056 pprust::lifetime_to_string(&l), id_str)
1058 Some(NodeTyParam(ref ty_param)) => {
1059 format!("typaram {:?}{}", ty_param, id_str)
1061 Some(NodeVisibility(ref vis)) => {
1062 format!("visibility {:?}{}", vis, id_str)
1065 format!("unknown node{}", id_str)