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, NodeId, &'ast Item),
134 EntryForeignItem(NodeId, NodeId, &'ast ForeignItem),
135 EntryTraitItem(NodeId, NodeId, &'ast TraitItem),
136 EntryImplItem(NodeId, NodeId, &'ast ImplItem),
137 EntryVariant(NodeId, NodeId, &'ast Variant),
138 EntryExpr(NodeId, NodeId, &'ast Expr),
139 EntryStmt(NodeId, NodeId, &'ast Stmt),
140 EntryArg(NodeId, NodeId, &'ast Pat),
141 EntryLocal(NodeId, NodeId, &'ast Pat),
142 EntryPat(NodeId, NodeId, &'ast Pat),
143 EntryBlock(NodeId, NodeId, &'ast Block),
144 EntryStructCtor(NodeId, NodeId, &'ast StructDef),
145 EntryLifetime(NodeId, 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(p: NodeId, s: NodeId, node: Node<'ast>) -> MapEntry<'ast> {
167 NodeItem(n) => EntryItem(p, s, n),
168 NodeForeignItem(n) => EntryForeignItem(p, s, n),
169 NodeTraitItem(n) => EntryTraitItem(p, s, n),
170 NodeImplItem(n) => EntryImplItem(p, s, n),
171 NodeVariant(n) => EntryVariant(p, s, n),
172 NodeExpr(n) => EntryExpr(p, s, n),
173 NodeStmt(n) => EntryStmt(p, s, n),
174 NodeArg(n) => EntryArg(p, s, n),
175 NodeLocal(n) => EntryLocal(p, s, n),
176 NodePat(n) => EntryPat(p, s, n),
177 NodeBlock(n) => EntryBlock(p, s, n),
178 NodeStructCtor(n) => EntryStructCtor(p, s, n),
179 NodeLifetime(n) => EntryLifetime(p, s, n)
183 fn parent(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 parent_node(self) -> Option<NodeId> {
204 EntryItem(_, id, _) => id,
205 EntryForeignItem(_, id, _) => id,
206 EntryTraitItem(_, id, _) => id,
207 EntryImplItem(_, id, _) => id,
208 EntryVariant(_, id, _) => id,
209 EntryExpr(_, id, _) => id,
210 EntryStmt(_, id, _) => id,
211 EntryArg(_, id, _) => id,
212 EntryLocal(_, id, _) => id,
213 EntryPat(_, id, _) => id,
214 EntryBlock(_, id, _) => id,
215 EntryStructCtor(_, id, _) => id,
216 EntryLifetime(_, id, _) => id,
221 fn to_node(self) -> Option<Node<'ast>> {
223 EntryItem(_, _, n) => NodeItem(n),
224 EntryForeignItem(_, _, n) => NodeForeignItem(n),
225 EntryTraitItem(_, _, n) => NodeTraitItem(n),
226 EntryImplItem(_, _, n) => NodeImplItem(n),
227 EntryVariant(_, _, n) => NodeVariant(n),
228 EntryExpr(_, _, n) => NodeExpr(n),
229 EntryStmt(_, _, n) => NodeStmt(n),
230 EntryArg(_, _, n) => NodeArg(n),
231 EntryLocal(_, _, n) => NodeLocal(n),
232 EntryPat(_, _, n) => NodePat(n),
233 EntryBlock(_, _, n) => NodeBlock(n),
234 EntryStructCtor(_, _, n) => NodeStructCtor(n),
235 EntryLifetime(_, _, n) => NodeLifetime(n),
241 /// Stores a crate and any number of inlined items from other crates.
244 inlined_items: TypedArena<InlinedParent>
248 pub fn new(krate: Crate) -> Forest {
251 inlined_items: TypedArena::new()
255 pub fn krate<'ast>(&'ast self) -> &'ast Crate {
260 /// Represents a mapping from Node IDs to AST elements and their parent
262 pub struct Map<'ast> {
263 /// The backing storage for all the AST nodes.
264 forest: &'ast Forest,
266 /// NodeIds are sequential integers from 0, so we can be
267 /// super-compact by storing them in a vector. Not everything with
268 /// a NodeId is in the map, but empirically the occupancy is about
269 /// 75-80%, so there's not too much overhead (certainly less than
270 /// a hashmap, since they (at the time of writing) have a maximum
271 /// of 75% occupancy).
273 /// Also, indexing is pretty quick when you've got a vector and
274 /// plain old integers.
275 map: RefCell<Vec<MapEntry<'ast>>>
278 impl<'ast> Map<'ast> {
279 fn entry_count(&self) -> usize {
280 self.map.borrow().len()
283 fn find_entry(&self, id: NodeId) -> Option<MapEntry<'ast>> {
284 self.map.borrow().get(id as usize).cloned()
287 pub fn krate(&self) -> &'ast Crate {
291 /// Retrieve the Node corresponding to `id`, panicking if it cannot
293 pub fn get(&self, id: NodeId) -> Node<'ast> {
294 match self.find(id) {
296 None => panic!("couldn't find node id {} in the AST map", id)
300 /// Retrieve the Node corresponding to `id`, returning None if
302 pub fn find(&self, id: NodeId) -> Option<Node<'ast>> {
303 self.find_entry(id).and_then(|x| x.to_node())
306 /// Retrieve the parent NodeId for `id`, or `id` itself if no
307 /// parent is registered in this map.
308 pub fn get_parent(&self, id: NodeId) -> NodeId {
309 self.find_entry(id).and_then(|x| x.parent()).unwrap_or(id)
312 /// Similar to get_parent, returns the parent node id or id if there is no
314 /// This function returns the most direct parent in the AST, whereas get_parent
315 /// returns the enclosing item. Note that this might not be the actual parent
316 /// node in the AST - some kinds of nodes are not in the map and these will
317 /// never appear as the parent_node. So you can always walk the parent_nodes
318 /// from a node to the root of the ast (unless you get the same id back here
319 /// that can happen if the id is not in the map itself or is just weird).
320 pub fn get_parent_node(&self, id: NodeId) -> NodeId {
321 self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
324 pub fn get_parent_did(&self, id: NodeId) -> DefId {
325 let parent = self.get_parent(id);
326 match self.find_entry(parent) {
327 Some(RootInlinedParent(&InlinedParent {ii: IITraitItem(did, _), ..})) => did,
328 Some(RootInlinedParent(&InlinedParent {ii: IIImplItem(did, _), ..})) => did,
329 _ => ast_util::local_def(parent)
333 pub fn get_foreign_abi(&self, id: NodeId) -> abi::Abi {
334 let parent = self.get_parent(id);
335 let abi = match self.find_entry(parent) {
336 Some(EntryItem(_, _, i)) => {
338 ItemForeignMod(ref nm) => Some(nm.abi),
342 /// Wrong but OK, because the only inlined foreign items are intrinsics.
343 Some(RootInlinedParent(_)) => Some(abi::RustIntrinsic),
348 None => panic!("expected foreign mod or inlined parent, found {}",
349 self.node_to_string(parent))
353 pub fn get_foreign_vis(&self, id: NodeId) -> Visibility {
354 let vis = self.expect_foreign_item(id).vis;
355 match self.find(self.get_parent(id)) {
356 Some(NodeItem(i)) => vis.inherit_from(i.vis),
361 pub fn expect_item(&self, id: NodeId) -> &'ast Item {
362 match self.find(id) {
363 Some(NodeItem(item)) => item,
364 _ => panic!("expected item, found {}", self.node_to_string(id))
368 pub fn expect_struct(&self, id: NodeId) -> &'ast StructDef {
369 match self.find(id) {
370 Some(NodeItem(i)) => {
372 ItemStruct(ref struct_def, _) => &**struct_def,
373 _ => panic!("struct ID bound to non-struct")
376 Some(NodeVariant(variant)) => {
377 match variant.node.kind {
378 StructVariantKind(ref struct_def) => &**struct_def,
379 _ => panic!("struct ID bound to enum variant that isn't struct-like"),
382 _ => panic!(format!("expected struct, found {}", self.node_to_string(id))),
386 pub fn expect_variant(&self, id: NodeId) -> &'ast Variant {
387 match self.find(id) {
388 Some(NodeVariant(variant)) => variant,
389 _ => panic!(format!("expected variant, found {}", self.node_to_string(id))),
393 pub fn expect_foreign_item(&self, id: NodeId) -> &'ast ForeignItem {
394 match self.find(id) {
395 Some(NodeForeignItem(item)) => item,
396 _ => panic!("expected foreign item, found {}", self.node_to_string(id))
400 pub fn expect_expr(&self, id: NodeId) -> &'ast Expr {
401 match self.find(id) {
402 Some(NodeExpr(expr)) => expr,
403 _ => panic!("expected expr, found {}", self.node_to_string(id))
407 /// returns the name associated with the given NodeId's AST
408 pub fn get_path_elem(&self, id: NodeId) -> PathElem {
409 let node = self.get(id);
413 ItemMod(_) | ItemForeignMod(_) => {
414 PathMod(item.ident.name)
416 _ => PathName(item.ident.name)
419 NodeForeignItem(i) => PathName(i.ident.name),
420 NodeImplItem(ii) => PathName(ii.ident.name),
421 NodeTraitItem(ti) => PathName(ti.ident.name),
422 NodeVariant(v) => PathName(v.node.name.name),
423 _ => panic!("no path elem for {:?}", node)
427 pub fn with_path<T, F>(&self, id: NodeId, f: F) -> T where
428 F: FnOnce(PathElems) -> T,
430 self.with_path_next(id, LinkedPath::empty(), f)
433 pub fn path_to_string(&self, id: NodeId) -> String {
434 self.with_path(id, |path| path_to_string(path))
437 fn path_to_str_with_ident(&self, id: NodeId, i: Ident) -> String {
438 self.with_path(id, |path| {
439 path_to_string(path.chain(Some(PathName(i.name))))
443 fn with_path_next<T, F>(&self, id: NodeId, next: LinkedPath, f: F) -> T where
444 F: FnOnce(PathElems) -> T,
446 let parent = self.get_parent(id);
447 let parent = match self.find_entry(id) {
448 Some(EntryForeignItem(..)) | Some(EntryVariant(..)) => {
449 // Anonymous extern items, enum variants and struct ctors
450 // go in the parent scope.
451 self.get_parent(parent)
453 // But tuple struct ctors don't have names, so use the path of its
454 // parent, the struct item. Similarly with closure expressions.
455 Some(EntryStructCtor(..)) | Some(EntryExpr(..)) => {
456 return self.with_path_next(parent, next, f);
461 match self.find_entry(id) {
462 Some(RootInlinedParent(data)) => {
463 f(data.path.iter().cloned().chain(next))
465 _ => f([].iter().cloned().chain(next))
468 self.with_path_next(parent, LinkedPath::from(&LinkedPathNode {
469 node: self.get_path_elem(id),
475 /// Given a node ID, get a list of of attributes associated with the AST
476 /// corresponding to the Node ID
477 pub fn attrs(&self, id: NodeId) -> &'ast [Attribute] {
478 let attrs = match self.find(id) {
479 Some(NodeItem(i)) => Some(&i.attrs[..]),
480 Some(NodeForeignItem(fi)) => Some(&fi.attrs[..]),
481 Some(NodeTraitItem(ref ti)) => Some(&ti.attrs[..]),
482 Some(NodeImplItem(ref ii)) => Some(&ii.attrs[..]),
483 Some(NodeVariant(ref v)) => Some(&v.node.attrs[..]),
484 // unit/tuple structs take the attributes straight from
485 // the struct definition.
486 Some(NodeStructCtor(_)) => {
487 return self.attrs(self.get_parent(id));
494 /// Returns an iterator that yields the node id's with paths that
495 /// match `parts`. (Requires `parts` is non-empty.)
497 /// For example, if given `parts` equal to `["bar", "quux"]`, then
498 /// the iterator will produce node id's for items with paths
499 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
500 /// any other such items it can find in the map.
501 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
502 -> NodesMatchingSuffix<'a, 'ast> {
503 NodesMatchingSuffix {
505 item_name: parts.last().unwrap(),
506 in_which: &parts[..parts.len() - 1],
511 pub fn opt_span(&self, id: NodeId) -> Option<Span> {
512 let sp = match self.find(id) {
513 Some(NodeItem(item)) => item.span,
514 Some(NodeForeignItem(foreign_item)) => foreign_item.span,
515 Some(NodeTraitItem(trait_method)) => trait_method.span,
516 Some(NodeImplItem(ref impl_item)) => impl_item.span,
517 Some(NodeVariant(variant)) => variant.span,
518 Some(NodeExpr(expr)) => expr.span,
519 Some(NodeStmt(stmt)) => stmt.span,
520 Some(NodeArg(pat)) | Some(NodeLocal(pat)) => pat.span,
521 Some(NodePat(pat)) => pat.span,
522 Some(NodeBlock(block)) => block.span,
523 Some(NodeStructCtor(_)) => self.expect_item(self.get_parent(id)).span,
529 pub fn span(&self, id: NodeId) -> Span {
531 .unwrap_or_else(|| panic!("AstMap.span: could not find span for id {:?}", id))
534 pub fn def_id_span(&self, def_id: DefId, fallback: Span) -> Span {
535 if def_id.krate == LOCAL_CRATE {
536 self.opt_span(def_id.node).unwrap_or(fallback)
542 pub fn node_to_string(&self, id: NodeId) -> String {
543 node_id_to_string(self, id, true)
546 pub fn node_to_user_string(&self, id: NodeId) -> String {
547 node_id_to_string(self, id, false)
551 pub struct NodesMatchingSuffix<'a, 'ast:'a> {
553 item_name: &'a String,
554 in_which: &'a [String],
558 impl<'a, 'ast> NodesMatchingSuffix<'a, 'ast> {
559 /// Returns true only if some suffix of the module path for parent
560 /// matches `self.in_which`.
562 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
563 /// returns true if parent's path ends with the suffix
564 /// `x_0::x_1::...::x_k`.
565 fn suffix_matches(&self, parent: NodeId) -> bool {
566 let mut cursor = parent;
567 for part in self.in_which.iter().rev() {
568 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
569 None => return false,
570 Some((node_id, name)) => (node_id, name),
572 if &part[..] != mod_name.as_str() {
575 cursor = self.map.get_parent(mod_id);
579 // Finds the first mod in parent chain for `id`, along with
582 // If `id` itself is a mod named `m` with parent `p`, then
583 // returns `Some(id, m, p)`. If `id` has no mod in its parent
584 // chain, then returns `None`.
585 fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
589 Some(NodeItem(item)) if item_is_mod(&*item) =>
590 return Some((id, item.ident.name)),
593 let parent = map.get_parent(id);
594 if parent == id { return None }
598 fn item_is_mod(item: &Item) -> bool {
607 // We are looking at some node `n` with a given name and parent
608 // id; do their names match what I am seeking?
609 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
610 name.as_str() == &self.item_name[..] &&
611 self.suffix_matches(parent_of_n)
615 impl<'a, 'ast> Iterator for NodesMatchingSuffix<'a, 'ast> {
618 fn next(&mut self) -> Option<NodeId> {
621 if idx as usize >= self.map.entry_count() {
625 let (p, name) = match self.map.find_entry(idx) {
626 Some(EntryItem(p, _, n)) => (p, n.name()),
627 Some(EntryForeignItem(p, _, n))=> (p, n.name()),
628 Some(EntryTraitItem(p, _, n)) => (p, n.name()),
629 Some(EntryImplItem(p, _, n)) => (p, n.name()),
630 Some(EntryVariant(p, _, n)) => (p, n.name()),
633 if self.matches_names(p, name) {
641 fn name(&self) -> Name;
644 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
646 impl Named for Item { fn name(&self) -> Name { self.ident.name } }
647 impl Named for ForeignItem { fn name(&self) -> Name { self.ident.name } }
648 impl Named for Variant_ { fn name(&self) -> Name { self.name.name } }
649 impl Named for TraitItem { fn name(&self) -> Name { self.ident.name } }
650 impl Named for ImplItem { fn name(&self) -> Name { self.ident.name } }
653 fn new_id(&self, id: NodeId) -> NodeId {
656 fn new_def_id(&self, def_id: DefId) -> DefId {
659 fn new_span(&self, span: Span) -> Span {
664 /// A Folder that updates IDs and Span's according to fold_ops.
665 struct IdAndSpanUpdater<F> {
669 impl<F: FoldOps> Folder for IdAndSpanUpdater<F> {
670 fn new_id(&mut self, id: NodeId) -> NodeId {
671 self.fold_ops.new_id(id)
674 fn new_span(&mut self, span: Span) -> Span {
675 self.fold_ops.new_span(span)
679 /// A Visitor that walks over an AST and collects Node's into an AST Map.
680 struct NodeCollector<'ast> {
681 map: Vec<MapEntry<'ast>>,
682 /// The node in which we are currently mapping (an item or a method).
687 impl<'ast> NodeCollector<'ast> {
688 fn insert_entry(&mut self, id: NodeId, entry: MapEntry<'ast>) {
689 debug!("ast_map: {:?} => {:?}", id, entry);
690 let len = self.map.len();
691 if id as usize >= len {
692 self.map.extend(repeat(NotPresent).take(id as usize - len + 1));
694 self.map[id as usize] = entry;
697 fn insert(&mut self, id: NodeId, node: Node<'ast>) {
698 let entry = MapEntry::from_node(self.parent, self.parent_node, node);
699 self.insert_entry(id, entry);
702 fn visit_fn_decl(&mut self, decl: &'ast FnDecl) {
703 for a in &decl.inputs {
704 self.insert(a.id, NodeArg(&*a.pat));
709 impl<'ast> Visitor<'ast> for NodeCollector<'ast> {
710 fn visit_item(&mut self, i: &'ast Item) {
711 self.insert(i.id, NodeItem(i));
712 let parent = self.parent;
714 let parent_node = self.parent_node;
715 self.parent_node = i.id;
717 ItemImpl(_, _, _, _, _, ref impl_items) => {
718 for ii in impl_items {
719 self.insert(ii.id, NodeImplItem(ii));
722 ItemEnum(ref enum_definition, _) => {
723 for v in &enum_definition.variants {
724 self.insert(v.node.id, NodeVariant(&**v));
727 ItemForeignMod(ref nm) => {
728 for nitem in &nm.items {
729 self.insert(nitem.id, NodeForeignItem(&**nitem));
732 ItemStruct(ref struct_def, _) => {
733 // If this is a tuple-like struct, register the constructor.
734 match struct_def.ctor_id {
736 self.insert(ctor_id, NodeStructCtor(&**struct_def));
741 ItemTrait(_, _, ref bounds, ref trait_items) => {
742 for b in bounds.iter() {
743 if let TraitTyParamBound(ref t, TraitBoundModifier::None) = *b {
744 self.insert(t.trait_ref.ref_id, NodeItem(i));
748 for ti in trait_items {
749 self.insert(ti.id, NodeTraitItem(ti));
752 ItemUse(ref view_path) => {
753 match view_path.node {
754 ViewPathList(_, ref paths) => {
756 self.insert(path.node.id(), NodeItem(i));
764 visit::walk_item(self, i);
765 self.parent = parent;
766 self.parent_node = parent_node;
769 fn visit_trait_item(&mut self, ti: &'ast TraitItem) {
770 let parent = self.parent;
772 let parent_node = self.parent_node;
773 self.parent_node = ti.id;
774 visit::walk_trait_item(self, ti);
775 self.parent = parent;
776 self.parent_node = parent_node;
779 fn visit_impl_item(&mut self, ii: &'ast ImplItem) {
780 let parent = self.parent;
782 let parent_node = self.parent_node;
783 self.parent_node = ii.id;
784 visit::walk_impl_item(self, ii);
785 self.parent = parent;
786 self.parent_node = parent_node;
789 fn visit_pat(&mut self, pat: &'ast Pat) {
790 let parent_node = self.parent_node;
791 self.parent_node = pat.id;
792 self.insert(pat.id, match pat.node {
793 // Note: this is at least *potentially* a pattern...
794 PatIdent(..) => NodeLocal(pat),
797 visit::walk_pat(self, pat);
798 self.parent_node = parent_node;
801 fn visit_expr(&mut self, expr: &'ast Expr) {
802 let parent_node = self.parent_node;
803 self.parent_node = expr.id;
804 self.insert(expr.id, NodeExpr(expr));
805 visit::walk_expr(self, expr);
806 self.parent_node = parent_node;
809 fn visit_stmt(&mut self, stmt: &'ast Stmt) {
810 let id = ast_util::stmt_id(stmt);
811 let parent_node = self.parent_node;
812 self.parent_node = id;
813 self.insert(id, NodeStmt(stmt));
814 visit::walk_stmt(self, stmt);
815 self.parent_node = parent_node;
818 fn visit_fn(&mut self, fk: visit::FnKind<'ast>, fd: &'ast FnDecl,
819 b: &'ast Block, s: Span, id: NodeId) {
820 let parent_node = self.parent_node;
821 self.parent_node = id;
822 self.visit_fn_decl(fd);
823 visit::walk_fn(self, fk, fd, b, s);
824 self.parent_node = parent_node;
827 fn visit_ty(&mut self, ty: &'ast Ty) {
828 let parent_node = self.parent_node;
829 self.parent_node = ty.id;
831 TyBareFn(ref fd) => {
832 self.visit_fn_decl(&*fd.decl);
836 visit::walk_ty(self, ty);
837 self.parent_node = parent_node;
840 fn visit_block(&mut self, block: &'ast Block) {
841 let parent_node = self.parent_node;
842 self.parent_node = block.id;
843 self.insert(block.id, NodeBlock(block));
844 visit::walk_block(self, block);
845 self.parent_node = parent_node;
848 fn visit_lifetime_ref(&mut self, lifetime: &'ast Lifetime) {
849 let parent_node = self.parent_node;
850 self.parent_node = lifetime.id;
851 self.insert(lifetime.id, NodeLifetime(lifetime));
852 self.parent_node = parent_node;
855 fn visit_lifetime_def(&mut self, def: &'ast LifetimeDef) {
856 self.visit_lifetime_ref(&def.lifetime);
860 pub fn map_crate<'ast, F: FoldOps>(forest: &'ast mut Forest, fold_ops: F) -> Map<'ast> {
861 // Replace the crate with an empty one to take it out.
862 let krate = mem::replace(&mut forest.krate, Crate {
869 exported_macros: vec![],
872 forest.krate = IdAndSpanUpdater { fold_ops: fold_ops }.fold_crate(krate);
874 let mut collector = NodeCollector {
876 parent: CRATE_NODE_ID,
877 parent_node: CRATE_NODE_ID,
879 collector.insert_entry(CRATE_NODE_ID, RootCrate);
880 visit::walk_crate(&mut collector, &forest.krate);
881 let map = collector.map;
883 if log_enabled!(::log::DEBUG) {
884 // This only makes sense for ordered stores; note the
885 // enumerate to count the number of entries.
886 let (entries_less_1, _) = map.iter().filter(|&x| {
891 }).enumerate().last().expect("AST map was empty after folding?");
893 let entries = entries_less_1 + 1;
894 let vector_length = map.len();
895 debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
896 entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
901 map: RefCell::new(map)
905 /// Used for items loaded from external crate that are being inlined into this
906 /// crate. The `path` should be the path to the item but should not include
908 pub fn map_decoded_item<'ast, F: FoldOps>(map: &Map<'ast>,
912 -> &'ast InlinedItem {
913 let mut fld = IdAndSpanUpdater { fold_ops: fold_ops };
915 IIItem(i) => IIItem(fld.fold_item(i).expect_one("expected one item")),
916 IITraitItem(d, ti) => {
917 IITraitItem(fld.fold_ops.new_def_id(d),
918 fld.fold_trait_item(ti).expect_one("expected one trait item"))
920 IIImplItem(d, ii) => {
921 IIImplItem(fld.fold_ops.new_def_id(d),
922 fld.fold_impl_item(ii).expect_one("expected one impl item"))
924 IIForeign(i) => IIForeign(fld.fold_foreign_item(i))
927 let ii_parent = map.forest.inlined_items.alloc(InlinedParent {
932 let mut collector = NodeCollector {
933 map: mem::replace(&mut *map.map.borrow_mut(), vec![]),
934 parent: fld.new_id(DUMMY_NODE_ID),
935 parent_node: fld.new_id(DUMMY_NODE_ID),
937 let ii_parent_id = collector.parent;
938 collector.insert_entry(ii_parent_id, RootInlinedParent(ii_parent));
939 visit::walk_inlined_item(&mut collector, &ii_parent.ii);
941 // Methods get added to the AST map when their impl is visited. Since we
942 // don't decode and instantiate the impl, but just the method, we have to
943 // add it to the table now. Likewise with foreign items.
946 IITraitItem(_, ref ti) => {
947 collector.insert(ti.id, NodeTraitItem(ti));
949 IIImplItem(_, ref ii) => {
950 collector.insert(ii.id, NodeImplItem(ii));
952 IIForeign(ref i) => {
953 collector.insert(i.id, NodeForeignItem(i));
956 *map.map.borrow_mut() = collector.map;
960 pub trait NodePrinter {
961 fn print_node(&mut self, node: &Node) -> io::Result<()>;
964 impl<'a> NodePrinter for pprust::State<'a> {
965 fn print_node(&mut self, node: &Node) -> io::Result<()> {
967 NodeItem(a) => self.print_item(&*a),
968 NodeForeignItem(a) => self.print_foreign_item(&*a),
969 NodeTraitItem(a) => self.print_trait_item(a),
970 NodeImplItem(a) => self.print_impl_item(a),
971 NodeVariant(a) => self.print_variant(&*a),
972 NodeExpr(a) => self.print_expr(&*a),
973 NodeStmt(a) => self.print_stmt(&*a),
974 NodePat(a) => self.print_pat(&*a),
975 NodeBlock(a) => self.print_block(&*a),
976 NodeLifetime(a) => self.print_lifetime(&*a),
978 // these cases do not carry enough information in the
979 // ast_map to reconstruct their full structure for pretty
981 NodeLocal(_) => panic!("cannot print isolated Local"),
982 NodeArg(_) => panic!("cannot print isolated Arg"),
983 NodeStructCtor(_) => panic!("cannot print isolated StructCtor"),
988 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
989 let id_str = format!(" (id={})", id);
990 let id_str = if include_id { &id_str[..] } else { "" };
993 Some(NodeItem(item)) => {
994 let path_str = map.path_to_str_with_ident(id, item.ident);
995 let item_str = match item.node {
996 ItemExternCrate(..) => "extern crate",
997 ItemUse(..) => "use",
998 ItemStatic(..) => "static",
999 ItemConst(..) => "const",
1001 ItemMod(..) => "mod",
1002 ItemForeignMod(..) => "foreign mod",
1004 ItemEnum(..) => "enum",
1005 ItemStruct(..) => "struct",
1006 ItemTrait(..) => "trait",
1007 ItemImpl(..) => "impl",
1008 ItemDefaultImpl(..) => "default impl",
1009 ItemMac(..) => "macro"
1011 format!("{} {}{}", item_str, path_str, id_str)
1013 Some(NodeForeignItem(item)) => {
1014 let path_str = map.path_to_str_with_ident(id, item.ident);
1015 format!("foreign item {}{}", path_str, id_str)
1017 Some(NodeImplItem(ii)) => {
1019 ConstImplItem(..) => {
1020 format!("assoc const {} in {}{}",
1021 token::get_ident(ii.ident),
1022 map.path_to_string(id),
1025 MethodImplItem(..) => {
1026 format!("method {} in {}{}",
1027 token::get_ident(ii.ident),
1028 map.path_to_string(id), id_str)
1030 TypeImplItem(_) => {
1031 format!("assoc type {} in {}{}",
1032 token::get_ident(ii.ident),
1033 map.path_to_string(id),
1036 MacImplItem(ref mac) => {
1037 format!("method macro {}{}",
1038 pprust::mac_to_string(mac), id_str)
1042 Some(NodeTraitItem(ti)) => {
1043 let kind = match ti.node {
1044 ConstTraitItem(..) => "assoc constant",
1045 MethodTraitItem(..) => "trait method",
1046 TypeTraitItem(..) => "assoc type",
1049 format!("{} {} in {}{}",
1051 token::get_ident(ti.ident),
1052 map.path_to_string(id),
1055 Some(NodeVariant(ref variant)) => {
1056 format!("variant {} in {}{}",
1057 token::get_ident(variant.node.name),
1058 map.path_to_string(id), id_str)
1060 Some(NodeExpr(ref expr)) => {
1061 format!("expr {}{}", pprust::expr_to_string(&**expr), id_str)
1063 Some(NodeStmt(ref stmt)) => {
1064 format!("stmt {}{}", pprust::stmt_to_string(&**stmt), id_str)
1066 Some(NodeArg(ref pat)) => {
1067 format!("arg {}{}", pprust::pat_to_string(&**pat), id_str)
1069 Some(NodeLocal(ref pat)) => {
1070 format!("local {}{}", pprust::pat_to_string(&**pat), id_str)
1072 Some(NodePat(ref pat)) => {
1073 format!("pat {}{}", pprust::pat_to_string(&**pat), id_str)
1075 Some(NodeBlock(ref block)) => {
1076 format!("block {}{}", pprust::block_to_string(&**block), id_str)
1078 Some(NodeStructCtor(_)) => {
1079 format!("struct_ctor {}{}", map.path_to_string(id), id_str)
1081 Some(NodeLifetime(ref l)) => {
1082 format!("lifetime {}{}",
1083 pprust::lifetime_to_string(&**l), id_str)
1086 format!("unknown node{}", id_str)