1 // Copyright 2012-2013 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 pub use self::PathElem::*;
13 use self::MapEntry::*;
18 use syntax::codemap::{DUMMY_SP, Span, Spanned};
19 use syntax::fold::Folder;
20 use syntax::parse::token;
21 use syntax::print::pprust;
22 use syntax::visit::{self, Visitor};
24 use arena::TypedArena;
25 use std::cell::RefCell;
28 use std::iter::{self, repeat};
34 #[derive(Clone, Copy, PartialEq, Debug)]
41 pub fn name(&self) -> Name {
43 PathMod(name) | PathName(name) => name
48 impl fmt::Display for PathElem {
49 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
50 let slot = token::get_name(self.name());
56 pub struct LinkedPathNode<'a> {
61 #[derive(Copy, Clone)]
62 pub struct LinkedPath<'a>(Option<&'a LinkedPathNode<'a>>);
64 impl<'a> LinkedPath<'a> {
65 pub fn empty() -> LinkedPath<'a> {
69 pub fn from(node: &'a LinkedPathNode) -> LinkedPath<'a> {
70 LinkedPath(Some(node))
74 impl<'a> Iterator for LinkedPath<'a> {
77 fn next(&mut self) -> Option<PathElem> {
88 /// The type of the iterator used by with_path.
89 pub type PathElems<'a, 'b> = iter::Chain<iter::Cloned<slice::Iter<'a, PathElem>>, LinkedPath<'b>>;
91 pub fn path_to_string<PI: Iterator<Item=PathElem>>(path: PI) -> String {
92 let itr = token::get_ident_interner();
94 path.fold(String::new(), |mut s, e| {
95 let e = itr.get(e.name());
104 #[derive(Copy, Clone, Debug)]
105 pub enum Node<'ast> {
106 NodeItem(&'ast Item),
107 NodeForeignItem(&'ast ForeignItem),
108 NodeTraitItem(&'ast TraitItem),
109 NodeImplItem(&'ast ImplItem),
110 NodeVariant(&'ast Variant),
111 NodeExpr(&'ast Expr),
112 NodeStmt(&'ast Stmt),
114 NodeLocal(&'ast Pat),
116 NodeBlock(&'ast Block),
118 /// NodeStructCtor represents a tuple struct.
119 NodeStructCtor(&'ast StructDef),
121 NodeLifetime(&'ast Lifetime),
124 /// Represents an entry and its parent NodeID and parent_node NodeID, see
125 /// get_parent_node for the distinction.
126 /// The odd layout is to bring down the total size.
127 #[derive(Copy, Debug)]
128 enum MapEntry<'ast> {
129 /// Placeholder for holes in the map.
132 /// All the node types, with a parent and scope ID.
133 EntryItem(NodeId, &'ast Item),
134 EntryForeignItem(NodeId, &'ast ForeignItem),
135 EntryTraitItem(NodeId, &'ast TraitItem),
136 EntryImplItem(NodeId, &'ast ImplItem),
137 EntryVariant(NodeId, &'ast Variant),
138 EntryExpr(NodeId, &'ast Expr),
139 EntryStmt(NodeId, &'ast Stmt),
140 EntryArg(NodeId, &'ast Pat),
141 EntryLocal(NodeId, &'ast Pat),
142 EntryPat(NodeId, &'ast Pat),
143 EntryBlock(NodeId, &'ast Block),
144 EntryStructCtor(NodeId, &'ast StructDef),
145 EntryLifetime(NodeId, &'ast Lifetime),
147 /// Roots for node trees.
149 RootInlinedParent(&'ast InlinedParent)
152 impl<'ast> Clone for MapEntry<'ast> {
153 fn clone(&self) -> MapEntry<'ast> {
159 struct InlinedParent {
164 impl<'ast> MapEntry<'ast> {
165 fn from_node(s: NodeId, node: Node<'ast>) -> MapEntry<'ast> {
167 NodeItem(n) => EntryItem(s, n),
168 NodeForeignItem(n) => EntryForeignItem(s, n),
169 NodeTraitItem(n) => EntryTraitItem(s, n),
170 NodeImplItem(n) => EntryImplItem(s, n),
171 NodeVariant(n) => EntryVariant(s, n),
172 NodeExpr(n) => EntryExpr(s, n),
173 NodeStmt(n) => EntryStmt(s, n),
174 NodeArg(n) => EntryArg(s, n),
175 NodeLocal(n) => EntryLocal(s, n),
176 NodePat(n) => EntryPat(s, n),
177 NodeBlock(n) => EntryBlock(s, n),
178 NodeStructCtor(n) => EntryStructCtor(s, n),
179 NodeLifetime(n) => EntryLifetime(s, n)
183 fn parent_node(self) -> Option<NodeId> {
185 EntryItem(id, _) => id,
186 EntryForeignItem(id, _) => id,
187 EntryTraitItem(id, _) => id,
188 EntryImplItem(id, _) => id,
189 EntryVariant(id, _) => id,
190 EntryExpr(id, _) => id,
191 EntryStmt(id, _) => id,
192 EntryArg(id, _) => id,
193 EntryLocal(id, _) => id,
194 EntryPat(id, _) => id,
195 EntryBlock(id, _) => id,
196 EntryStructCtor(id, _) => id,
197 EntryLifetime(id, _) => id,
202 fn to_node(self) -> Option<Node<'ast>> {
204 EntryItem(_, n) => NodeItem(n),
205 EntryForeignItem(_, n) => NodeForeignItem(n),
206 EntryTraitItem(_, n) => NodeTraitItem(n),
207 EntryImplItem(_, n) => NodeImplItem(n),
208 EntryVariant(_, n) => NodeVariant(n),
209 EntryExpr(_, n) => NodeExpr(n),
210 EntryStmt(_, n) => NodeStmt(n),
211 EntryArg(_, n) => NodeArg(n),
212 EntryLocal(_, n) => NodeLocal(n),
213 EntryPat(_, n) => NodePat(n),
214 EntryBlock(_, n) => NodeBlock(n),
215 EntryStructCtor(_, n) => NodeStructCtor(n),
216 EntryLifetime(_, n) => NodeLifetime(n),
222 /// Stores a crate and any number of inlined items from other crates.
225 inlined_items: TypedArena<InlinedParent>
229 pub fn new(krate: Crate) -> Forest {
232 inlined_items: TypedArena::new()
236 pub fn krate<'ast>(&'ast self) -> &'ast Crate {
241 /// Represents a mapping from Node IDs to AST elements and their parent
243 pub struct Map<'ast> {
244 /// The backing storage for all the AST nodes.
245 forest: &'ast Forest,
247 /// NodeIds are sequential integers from 0, so we can be
248 /// super-compact by storing them in a vector. Not everything with
249 /// a NodeId is in the map, but empirically the occupancy is about
250 /// 75-80%, so there's not too much overhead (certainly less than
251 /// a hashmap, since they (at the time of writing) have a maximum
252 /// of 75% occupancy).
254 /// Also, indexing is pretty quick when you've got a vector and
255 /// plain old integers.
256 map: RefCell<Vec<MapEntry<'ast>>>
259 impl<'ast> Map<'ast> {
260 fn entry_count(&self) -> usize {
261 self.map.borrow().len()
264 fn find_entry(&self, id: NodeId) -> Option<MapEntry<'ast>> {
265 self.map.borrow().get(id as usize).cloned()
268 pub fn krate(&self) -> &'ast Crate {
272 /// Retrieve the Node corresponding to `id`, panicking if it cannot
274 pub fn get(&self, id: NodeId) -> Node<'ast> {
275 match self.find(id) {
277 None => panic!("couldn't find node id {} in the AST map", id)
281 /// Retrieve the Node corresponding to `id`, returning None if
283 pub fn find(&self, id: NodeId) -> Option<Node<'ast>> {
284 self.find_entry(id).and_then(|x| x.to_node())
287 /// Retrieve the parent NodeId for `id`, or `id` itself if no
288 /// parent is registered in this map.
289 pub fn get_parent(&self, id: NodeId) -> NodeId {
292 let parent_node = self.get_parent_node(id);
293 if parent_node == 0 {
296 if parent_node == id {
300 let node = self.find_entry(parent_node);
304 let node = node.unwrap().to_node();
306 Some(node) => match node {
323 /// Similar to get_parent, returns the parent node id or id if there is no
325 /// This function returns the most direct parent in the AST, whereas get_parent
326 /// returns the enclosing item. Note that this might not be the actual parent
327 /// node in the AST - some kinds of nodes are not in the map and these will
328 /// never appear as the parent_node. So you can always walk the parent_nodes
329 /// from a node to the root of the ast (unless you get the same id back here
330 /// that can happen if the id is not in the map itself or is just weird).
331 pub fn get_parent_node(&self, id: NodeId) -> NodeId {
332 self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
335 /// Returns the nearest enclosing scope. A scope is an item or block.
336 /// FIXME it is not clear to me that all items qualify as scopes - statics
337 /// and associated types probably shouldn't, for example. Behaviour in this
338 /// regard should be expected to be highly unstable.
339 pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
340 let mut last_id = id;
341 // Walk up the chain of parents until we find a 'scope'.
343 let cur_id = self.get_parent_node(last_id);
344 if cur_id == last_id {
352 match self.get(cur_id) {
367 pub fn get_parent_did(&self, id: NodeId) -> DefId {
368 let parent = self.get_parent(id);
369 match self.find_entry(parent) {
370 Some(RootInlinedParent(&InlinedParent {ii: IITraitItem(did, _), ..})) => did,
371 Some(RootInlinedParent(&InlinedParent {ii: IIImplItem(did, _), ..})) => did,
372 _ => ast_util::local_def(parent)
376 pub fn get_foreign_abi(&self, id: NodeId) -> abi::Abi {
377 let parent = self.get_parent(id);
378 let abi = match self.find_entry(parent) {
379 Some(EntryItem(_, i)) => {
381 ItemForeignMod(ref nm) => Some(nm.abi),
385 /// Wrong but OK, because the only inlined foreign items are intrinsics.
386 Some(RootInlinedParent(_)) => Some(abi::RustIntrinsic),
391 None => panic!("expected foreign mod or inlined parent, found {}",
392 self.node_to_string(parent))
396 pub fn get_foreign_vis(&self, id: NodeId) -> Visibility {
397 let vis = self.expect_foreign_item(id).vis;
398 match self.find(self.get_parent(id)) {
399 Some(NodeItem(i)) => vis.inherit_from(i.vis),
404 pub fn expect_item(&self, id: NodeId) -> &'ast Item {
405 match self.find(id) {
406 Some(NodeItem(item)) => item,
407 _ => panic!("expected item, found {}", self.node_to_string(id))
411 pub fn expect_struct(&self, id: NodeId) -> &'ast StructDef {
412 match self.find(id) {
413 Some(NodeItem(i)) => {
415 ItemStruct(ref struct_def, _) => &**struct_def,
416 _ => panic!("struct ID bound to non-struct")
419 Some(NodeVariant(variant)) => {
420 match variant.node.kind {
421 StructVariantKind(ref struct_def) => &**struct_def,
422 _ => panic!("struct ID bound to enum variant that isn't struct-like"),
425 _ => panic!(format!("expected struct, found {}", self.node_to_string(id))),
429 pub fn expect_variant(&self, id: NodeId) -> &'ast Variant {
430 match self.find(id) {
431 Some(NodeVariant(variant)) => variant,
432 _ => panic!(format!("expected variant, found {}", self.node_to_string(id))),
436 pub fn expect_foreign_item(&self, id: NodeId) -> &'ast ForeignItem {
437 match self.find(id) {
438 Some(NodeForeignItem(item)) => item,
439 _ => panic!("expected foreign item, found {}", self.node_to_string(id))
443 pub fn expect_expr(&self, id: NodeId) -> &'ast Expr {
444 match self.find(id) {
445 Some(NodeExpr(expr)) => expr,
446 _ => panic!("expected expr, found {}", self.node_to_string(id))
450 /// returns the name associated with the given NodeId's AST
451 pub fn get_path_elem(&self, id: NodeId) -> PathElem {
452 let node = self.get(id);
456 ItemMod(_) | ItemForeignMod(_) => {
457 PathMod(item.ident.name)
459 _ => PathName(item.ident.name)
462 NodeForeignItem(i) => PathName(i.ident.name),
463 NodeImplItem(ii) => PathName(ii.ident.name),
464 NodeTraitItem(ti) => PathName(ti.ident.name),
465 NodeVariant(v) => PathName(v.node.name.name),
466 _ => panic!("no path elem for {:?}", node)
470 pub fn with_path<T, F>(&self, id: NodeId, f: F) -> T where
471 F: FnOnce(PathElems) -> T,
473 self.with_path_next(id, LinkedPath::empty(), f)
476 pub fn path_to_string(&self, id: NodeId) -> String {
477 self.with_path(id, |path| path_to_string(path))
480 fn path_to_str_with_ident(&self, id: NodeId, i: Ident) -> String {
481 self.with_path(id, |path| {
482 path_to_string(path.chain(Some(PathName(i.name))))
486 fn with_path_next<T, F>(&self, id: NodeId, next: LinkedPath, f: F) -> T where
487 F: FnOnce(PathElems) -> T,
489 let parent = self.get_parent(id);
490 let parent = match self.find_entry(id) {
491 Some(EntryForeignItem(..)) | Some(EntryVariant(..)) => {
492 // Anonymous extern items, enum variants and struct ctors
493 // go in the parent scope.
494 self.get_parent(parent)
496 // But tuple struct ctors don't have names, so use the path of its
497 // parent, the struct item. Similarly with closure expressions.
498 Some(EntryStructCtor(..)) | Some(EntryExpr(..)) => {
499 return self.with_path_next(parent, next, f);
504 match self.find_entry(id) {
505 Some(RootInlinedParent(data)) => {
506 f(data.path.iter().cloned().chain(next))
508 _ => f([].iter().cloned().chain(next))
511 self.with_path_next(parent, LinkedPath::from(&LinkedPathNode {
512 node: self.get_path_elem(id),
518 /// Given a node ID, get a list of of attributes associated with the AST
519 /// corresponding to the Node ID
520 pub fn attrs(&self, id: NodeId) -> &'ast [Attribute] {
521 let attrs = match self.find(id) {
522 Some(NodeItem(i)) => Some(&i.attrs[..]),
523 Some(NodeForeignItem(fi)) => Some(&fi.attrs[..]),
524 Some(NodeTraitItem(ref ti)) => Some(&ti.attrs[..]),
525 Some(NodeImplItem(ref ii)) => Some(&ii.attrs[..]),
526 Some(NodeVariant(ref v)) => Some(&v.node.attrs[..]),
527 // unit/tuple structs take the attributes straight from
528 // the struct definition.
529 Some(NodeStructCtor(_)) => {
530 return self.attrs(self.get_parent(id));
537 /// Returns an iterator that yields the node id's with paths that
538 /// match `parts`. (Requires `parts` is non-empty.)
540 /// For example, if given `parts` equal to `["bar", "quux"]`, then
541 /// the iterator will produce node id's for items with paths
542 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
543 /// any other such items it can find in the map.
544 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
545 -> NodesMatchingSuffix<'a, 'ast> {
546 NodesMatchingSuffix {
548 item_name: parts.last().unwrap(),
549 in_which: &parts[..parts.len() - 1],
554 pub fn opt_span(&self, id: NodeId) -> Option<Span> {
555 let sp = match self.find(id) {
556 Some(NodeItem(item)) => item.span,
557 Some(NodeForeignItem(foreign_item)) => foreign_item.span,
558 Some(NodeTraitItem(trait_method)) => trait_method.span,
559 Some(NodeImplItem(ref impl_item)) => impl_item.span,
560 Some(NodeVariant(variant)) => variant.span,
561 Some(NodeExpr(expr)) => expr.span,
562 Some(NodeStmt(stmt)) => stmt.span,
563 Some(NodeArg(pat)) | Some(NodeLocal(pat)) => pat.span,
564 Some(NodePat(pat)) => pat.span,
565 Some(NodeBlock(block)) => block.span,
566 Some(NodeStructCtor(_)) => self.expect_item(self.get_parent(id)).span,
572 pub fn span(&self, id: NodeId) -> Span {
574 .unwrap_or_else(|| panic!("AstMap.span: could not find span for id {:?}", id))
577 pub fn def_id_span(&self, def_id: DefId, fallback: Span) -> Span {
578 if def_id.krate == LOCAL_CRATE {
579 self.opt_span(def_id.node).unwrap_or(fallback)
585 pub fn node_to_string(&self, id: NodeId) -> String {
586 node_id_to_string(self, id, true)
589 pub fn node_to_user_string(&self, id: NodeId) -> String {
590 node_id_to_string(self, id, false)
594 pub struct NodesMatchingSuffix<'a, 'ast:'a> {
596 item_name: &'a String,
597 in_which: &'a [String],
601 impl<'a, 'ast> NodesMatchingSuffix<'a, 'ast> {
602 /// Returns true only if some suffix of the module path for parent
603 /// matches `self.in_which`.
605 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
606 /// returns true if parent's path ends with the suffix
607 /// `x_0::x_1::...::x_k`.
608 fn suffix_matches(&self, parent: NodeId) -> bool {
609 let mut cursor = parent;
610 for part in self.in_which.iter().rev() {
611 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
612 None => return false,
613 Some((node_id, name)) => (node_id, name),
615 if &part[..] != mod_name.as_str() {
618 cursor = self.map.get_parent(mod_id);
622 // Finds the first mod in parent chain for `id`, along with
625 // If `id` itself is a mod named `m` with parent `p`, then
626 // returns `Some(id, m, p)`. If `id` has no mod in its parent
627 // chain, then returns `None`.
628 fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
632 Some(NodeItem(item)) if item_is_mod(&*item) =>
633 return Some((id, item.ident.name)),
636 let parent = map.get_parent(id);
637 if parent == id { return None }
641 fn item_is_mod(item: &Item) -> bool {
650 // We are looking at some node `n` with a given name and parent
651 // id; do their names match what I am seeking?
652 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
653 name.as_str() == &self.item_name[..] &&
654 self.suffix_matches(parent_of_n)
658 impl<'a, 'ast> Iterator for NodesMatchingSuffix<'a, 'ast> {
661 fn next(&mut self) -> Option<NodeId> {
664 if idx as usize >= self.map.entry_count() {
668 let name = match self.map.find_entry(idx) {
669 Some(EntryItem(_, n)) => n.name(),
670 Some(EntryForeignItem(_, n))=> n.name(),
671 Some(EntryTraitItem(_, n)) => n.name(),
672 Some(EntryImplItem(_, n)) => n.name(),
673 Some(EntryVariant(_, n)) => n.name(),
676 if self.matches_names(self.map.get_parent(idx), name) {
684 fn name(&self) -> Name;
687 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
689 impl Named for Item { fn name(&self) -> Name { self.ident.name } }
690 impl Named for ForeignItem { fn name(&self) -> Name { self.ident.name } }
691 impl Named for Variant_ { fn name(&self) -> Name { self.name.name } }
692 impl Named for TraitItem { fn name(&self) -> Name { self.ident.name } }
693 impl Named for ImplItem { fn name(&self) -> Name { self.ident.name } }
696 fn new_id(&self, id: NodeId) -> NodeId {
699 fn new_def_id(&self, def_id: DefId) -> DefId {
702 fn new_span(&self, span: Span) -> Span {
707 /// A Folder that updates IDs and Span's according to fold_ops.
708 struct IdAndSpanUpdater<F> {
712 impl<F: FoldOps> Folder for IdAndSpanUpdater<F> {
713 fn new_id(&mut self, id: NodeId) -> NodeId {
714 self.fold_ops.new_id(id)
717 fn new_span(&mut self, span: Span) -> Span {
718 self.fold_ops.new_span(span)
722 /// A Visitor that walks over an AST and collects Node's into an AST Map.
723 struct NodeCollector<'ast> {
724 map: Vec<MapEntry<'ast>>,
728 impl<'ast> NodeCollector<'ast> {
729 fn insert_entry(&mut self, id: NodeId, entry: MapEntry<'ast>) {
730 debug!("ast_map: {:?} => {:?}", id, entry);
731 let len = self.map.len();
732 if id as usize >= len {
733 self.map.extend(repeat(NotPresent).take(id as usize - len + 1));
735 self.map[id as usize] = entry;
738 fn insert(&mut self, id: NodeId, node: Node<'ast>) {
739 let entry = MapEntry::from_node(self.parent_node, node);
740 self.insert_entry(id, entry);
743 fn visit_fn_decl(&mut self, decl: &'ast FnDecl) {
744 for a in &decl.inputs {
745 self.insert(a.id, NodeArg(&*a.pat));
750 impl<'ast> Visitor<'ast> for NodeCollector<'ast> {
751 fn visit_item(&mut self, i: &'ast Item) {
752 self.insert(i.id, NodeItem(i));
754 let parent_node = self.parent_node;
755 self.parent_node = i.id;
758 ItemImpl(_, _, _, _, _, ref impl_items) => {
759 for ii in impl_items {
760 self.insert(ii.id, NodeImplItem(ii));
763 ItemEnum(ref enum_definition, _) => {
764 for v in &enum_definition.variants {
765 self.insert(v.node.id, NodeVariant(&**v));
768 ItemForeignMod(ref nm) => {
769 for nitem in &nm.items {
770 self.insert(nitem.id, NodeForeignItem(&**nitem));
773 ItemStruct(ref struct_def, _) => {
774 // If this is a tuple-like struct, register the constructor.
775 match struct_def.ctor_id {
777 self.insert(ctor_id, NodeStructCtor(&**struct_def));
782 ItemTrait(_, _, ref bounds, ref trait_items) => {
783 for b in bounds.iter() {
784 if let TraitTyParamBound(ref t, TraitBoundModifier::None) = *b {
785 self.insert(t.trait_ref.ref_id, NodeItem(i));
789 for ti in trait_items {
790 self.insert(ti.id, NodeTraitItem(ti));
793 ItemUse(ref view_path) => {
794 match view_path.node {
795 ViewPathList(_, ref paths) => {
797 self.insert(path.node.id(), NodeItem(i));
805 visit::walk_item(self, i);
806 self.parent_node = parent_node;
809 fn visit_trait_item(&mut self, ti: &'ast TraitItem) {
810 let parent_node = self.parent_node;
811 self.parent_node = ti.id;
812 visit::walk_trait_item(self, ti);
813 self.parent_node = parent_node;
816 fn visit_impl_item(&mut self, ii: &'ast ImplItem) {
817 let parent_node = self.parent_node;
818 self.parent_node = ii.id;
820 visit::walk_impl_item(self, ii);
822 self.parent_node = parent_node;
825 fn visit_pat(&mut self, pat: &'ast Pat) {
826 self.insert(pat.id, match pat.node {
827 // Note: this is at least *potentially* a pattern...
828 PatIdent(..) => NodeLocal(pat),
832 let parent_node = self.parent_node;
833 self.parent_node = pat.id;
834 visit::walk_pat(self, pat);
835 self.parent_node = parent_node;
838 fn visit_expr(&mut self, expr: &'ast Expr) {
839 self.insert(expr.id, NodeExpr(expr));
840 let parent_node = self.parent_node;
841 self.parent_node = expr.id;
842 visit::walk_expr(self, expr);
843 self.parent_node = parent_node;
846 fn visit_stmt(&mut self, stmt: &'ast Stmt) {
847 let id = ast_util::stmt_id(stmt);
848 self.insert(id, NodeStmt(stmt));
849 let parent_node = self.parent_node;
850 self.parent_node = id;
851 visit::walk_stmt(self, stmt);
852 self.parent_node = parent_node;
855 fn visit_fn(&mut self, fk: visit::FnKind<'ast>, fd: &'ast FnDecl,
856 b: &'ast Block, s: Span, id: NodeId) {
857 let parent_node = self.parent_node;
858 self.parent_node = id;
859 self.visit_fn_decl(fd);
860 visit::walk_fn(self, fk, fd, b, s);
861 self.parent_node = parent_node;
864 fn visit_ty(&mut self, ty: &'ast Ty) {
865 let parent_node = self.parent_node;
866 self.parent_node = ty.id;
868 TyBareFn(ref fd) => {
869 self.visit_fn_decl(&*fd.decl);
873 visit::walk_ty(self, ty);
874 self.parent_node = parent_node;
877 fn visit_block(&mut self, block: &'ast Block) {
878 self.insert(block.id, NodeBlock(block));
879 let parent_node = self.parent_node;
880 self.parent_node = block.id;
881 visit::walk_block(self, block);
882 self.parent_node = parent_node;
885 fn visit_lifetime_ref(&mut self, lifetime: &'ast Lifetime) {
886 self.insert(lifetime.id, NodeLifetime(lifetime));
889 fn visit_lifetime_def(&mut self, def: &'ast LifetimeDef) {
890 self.visit_lifetime_ref(&def.lifetime);
894 pub fn map_crate<'ast, F: FoldOps>(forest: &'ast mut Forest, fold_ops: F) -> Map<'ast> {
895 // Replace the crate with an empty one to take it out.
896 let krate = mem::replace(&mut forest.krate, Crate {
903 exported_macros: vec![],
906 forest.krate = IdAndSpanUpdater { fold_ops: fold_ops }.fold_crate(krate);
908 let mut collector = NodeCollector {
910 parent_node: CRATE_NODE_ID,
912 collector.insert_entry(CRATE_NODE_ID, RootCrate);
913 visit::walk_crate(&mut collector, &forest.krate);
914 let map = collector.map;
916 if log_enabled!(::log::DEBUG) {
917 // This only makes sense for ordered stores; note the
918 // enumerate to count the number of entries.
919 let (entries_less_1, _) = map.iter().filter(|&x| {
924 }).enumerate().last().expect("AST map was empty after folding?");
926 let entries = entries_less_1 + 1;
927 let vector_length = map.len();
928 debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
929 entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
934 map: RefCell::new(map)
938 /// Used for items loaded from external crate that are being inlined into this
939 /// crate. The `path` should be the path to the item but should not include
941 pub fn map_decoded_item<'ast, F: FoldOps>(map: &Map<'ast>,
945 -> &'ast InlinedItem {
946 let mut fld = IdAndSpanUpdater { fold_ops: fold_ops };
948 IIItem(i) => IIItem(fld.fold_item(i).expect_one("expected one item")),
949 IITraitItem(d, ti) => {
950 IITraitItem(fld.fold_ops.new_def_id(d),
951 fld.fold_trait_item(ti).expect_one("expected one trait item"))
953 IIImplItem(d, ii) => {
954 IIImplItem(fld.fold_ops.new_def_id(d),
955 fld.fold_impl_item(ii).expect_one("expected one impl item"))
957 IIForeign(i) => IIForeign(fld.fold_foreign_item(i))
960 let ii_parent = map.forest.inlined_items.alloc(InlinedParent {
965 let ii_parent_id = fld.new_id(DUMMY_NODE_ID);
966 let mut collector = NodeCollector {
967 map: mem::replace(&mut *map.map.borrow_mut(), vec![]),
968 parent_node: ii_parent_id,
970 collector.insert_entry(ii_parent_id, RootInlinedParent(ii_parent));
971 visit::walk_inlined_item(&mut collector, &ii_parent.ii);
973 // Methods get added to the AST map when their impl is visited. Since we
974 // don't decode and instantiate the impl, but just the method, we have to
975 // add it to the table now. Likewise with foreign items.
978 IITraitItem(_, ref ti) => {
979 collector.insert(ti.id, NodeTraitItem(ti));
981 IIImplItem(_, ref ii) => {
982 collector.insert(ii.id, NodeImplItem(ii));
984 IIForeign(ref i) => {
985 collector.insert(i.id, NodeForeignItem(i));
988 *map.map.borrow_mut() = collector.map;
992 pub trait NodePrinter {
993 fn print_node(&mut self, node: &Node) -> io::Result<()>;
996 impl<'a> NodePrinter for pprust::State<'a> {
997 fn print_node(&mut self, node: &Node) -> io::Result<()> {
999 NodeItem(a) => self.print_item(&*a),
1000 NodeForeignItem(a) => self.print_foreign_item(&*a),
1001 NodeTraitItem(a) => self.print_trait_item(a),
1002 NodeImplItem(a) => self.print_impl_item(a),
1003 NodeVariant(a) => self.print_variant(&*a),
1004 NodeExpr(a) => self.print_expr(&*a),
1005 NodeStmt(a) => self.print_stmt(&*a),
1006 NodePat(a) => self.print_pat(&*a),
1007 NodeBlock(a) => self.print_block(&*a),
1008 NodeLifetime(a) => self.print_lifetime(&*a),
1010 // these cases do not carry enough information in the
1011 // ast_map to reconstruct their full structure for pretty
1013 NodeLocal(_) => panic!("cannot print isolated Local"),
1014 NodeArg(_) => panic!("cannot print isolated Arg"),
1015 NodeStructCtor(_) => panic!("cannot print isolated StructCtor"),
1020 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
1021 let id_str = format!(" (id={})", id);
1022 let id_str = if include_id { &id_str[..] } else { "" };
1024 match map.find(id) {
1025 Some(NodeItem(item)) => {
1026 let path_str = map.path_to_str_with_ident(id, item.ident);
1027 let item_str = match item.node {
1028 ItemExternCrate(..) => "extern crate",
1029 ItemUse(..) => "use",
1030 ItemStatic(..) => "static",
1031 ItemConst(..) => "const",
1033 ItemMod(..) => "mod",
1034 ItemForeignMod(..) => "foreign mod",
1036 ItemEnum(..) => "enum",
1037 ItemStruct(..) => "struct",
1038 ItemTrait(..) => "trait",
1039 ItemImpl(..) => "impl",
1040 ItemDefaultImpl(..) => "default impl",
1041 ItemMac(..) => "macro"
1043 format!("{} {}{}", item_str, path_str, id_str)
1045 Some(NodeForeignItem(item)) => {
1046 let path_str = map.path_to_str_with_ident(id, item.ident);
1047 format!("foreign item {}{}", path_str, id_str)
1049 Some(NodeImplItem(ii)) => {
1051 ConstImplItem(..) => {
1052 format!("assoc const {} in {}{}",
1053 token::get_ident(ii.ident),
1054 map.path_to_string(id),
1057 MethodImplItem(..) => {
1058 format!("method {} in {}{}",
1059 token::get_ident(ii.ident),
1060 map.path_to_string(id), id_str)
1062 TypeImplItem(_) => {
1063 format!("assoc type {} in {}{}",
1064 token::get_ident(ii.ident),
1065 map.path_to_string(id),
1068 MacImplItem(ref mac) => {
1069 format!("method macro {}{}",
1070 pprust::mac_to_string(mac), id_str)
1074 Some(NodeTraitItem(ti)) => {
1075 let kind = match ti.node {
1076 ConstTraitItem(..) => "assoc constant",
1077 MethodTraitItem(..) => "trait method",
1078 TypeTraitItem(..) => "assoc type",
1081 format!("{} {} in {}{}",
1083 token::get_ident(ti.ident),
1084 map.path_to_string(id),
1087 Some(NodeVariant(ref variant)) => {
1088 format!("variant {} in {}{}",
1089 token::get_ident(variant.node.name),
1090 map.path_to_string(id), id_str)
1092 Some(NodeExpr(ref expr)) => {
1093 format!("expr {}{}", pprust::expr_to_string(&**expr), id_str)
1095 Some(NodeStmt(ref stmt)) => {
1096 format!("stmt {}{}", pprust::stmt_to_string(&**stmt), id_str)
1098 Some(NodeArg(ref pat)) => {
1099 format!("arg {}{}", pprust::pat_to_string(&**pat), id_str)
1101 Some(NodeLocal(ref pat)) => {
1102 format!("local {}{}", pprust::pat_to_string(&**pat), id_str)
1104 Some(NodePat(ref pat)) => {
1105 format!("pat {}{}", pprust::pat_to_string(&**pat), id_str)
1107 Some(NodeBlock(ref block)) => {
1108 format!("block {}{}", pprust::block_to_string(&**block), id_str)
1110 Some(NodeStructCtor(_)) => {
1111 format!("struct_ctor {}{}", map.path_to_string(id), id_str)
1113 Some(NodeLifetime(ref l)) => {
1114 format!("lifetime {}{}",
1115 pprust::lifetime_to_string(&**l), id_str)
1118 format!("unknown node{}", id_str)