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 codemap::{DUMMY_SP, Span, Spanned};
23 use visit::{mod, Visitor};
25 use arena::TypedArena;
26 use std::cell::RefCell;
28 use std::io::IoResult;
29 use std::iter::{mod, repeat};
35 #[deriving(Clone, Copy, PartialEq)]
42 pub fn name(&self) -> Name {
44 PathMod(name) | PathName(name) => name
49 impl fmt::Show for PathElem {
50 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
51 let slot = token::get_name(self.name());
57 struct LinkedPathNode<'a> {
62 type LinkedPath<'a> = Option<&'a LinkedPathNode<'a>>;
64 impl<'a> Iterator for LinkedPath<'a> {
67 fn next(&mut self) -> Option<PathElem> {
78 // HACK(eddyb) move this into libstd (value wrapper for slice::Iter).
80 pub struct Values<'a, T:'a>(pub slice::Iter<'a, T>);
82 impl<'a, T: Copy> Iterator for Values<'a, T> {
85 fn next(&mut self) -> Option<T> {
86 let &Values(ref mut items) = self;
87 items.next().map(|&x| x)
91 /// The type of the iterator used by with_path.
92 pub type PathElems<'a, 'b> = iter::Chain<Values<'a, PathElem>, LinkedPath<'b>>;
94 pub fn path_to_string<PI: Iterator<Item=PathElem>>(path: PI) -> String {
95 let itr = token::get_ident_interner();
97 path.fold(String::new(), |mut s, e| {
98 let e = itr.get(e.name());
107 #[deriving(Copy, Show)]
108 pub enum Node<'ast> {
109 NodeItem(&'ast Item),
110 NodeForeignItem(&'ast ForeignItem),
111 NodeTraitItem(&'ast TraitItem),
112 NodeImplItem(&'ast ImplItem),
113 NodeVariant(&'ast Variant),
114 NodeExpr(&'ast Expr),
115 NodeStmt(&'ast Stmt),
117 NodeLocal(&'ast Pat),
119 NodeBlock(&'ast Block),
121 /// NodeStructCtor represents a tuple struct.
122 NodeStructCtor(&'ast StructDef),
124 NodeLifetime(&'ast Lifetime),
127 /// Represents an entry and its parent Node ID
128 /// The odd layout is to bring down the total size.
129 #[deriving(Copy, Show)]
130 enum MapEntry<'ast> {
131 /// Placeholder for holes in the map.
134 /// All the node types, with a parent ID.
135 EntryItem(NodeId, &'ast Item),
136 EntryForeignItem(NodeId, &'ast ForeignItem),
137 EntryTraitItem(NodeId, &'ast TraitItem),
138 EntryImplItem(NodeId, &'ast ImplItem),
139 EntryVariant(NodeId, &'ast Variant),
140 EntryExpr(NodeId, &'ast Expr),
141 EntryStmt(NodeId, &'ast Stmt),
142 EntryArg(NodeId, &'ast Pat),
143 EntryLocal(NodeId, &'ast Pat),
144 EntryPat(NodeId, &'ast Pat),
145 EntryBlock(NodeId, &'ast Block),
146 EntryStructCtor(NodeId, &'ast StructDef),
147 EntryLifetime(NodeId, &'ast Lifetime),
149 /// Roots for node trees.
151 RootInlinedParent(&'ast InlinedParent)
154 impl<'ast> Clone for MapEntry<'ast> {
155 fn clone(&self) -> MapEntry<'ast> {
161 struct InlinedParent {
166 impl<'ast> MapEntry<'ast> {
167 fn from_node(p: NodeId, node: Node<'ast>) -> MapEntry<'ast> {
169 NodeItem(n) => EntryItem(p, n),
170 NodeForeignItem(n) => EntryForeignItem(p, n),
171 NodeTraitItem(n) => EntryTraitItem(p, n),
172 NodeImplItem(n) => EntryImplItem(p, n),
173 NodeVariant(n) => EntryVariant(p, n),
174 NodeExpr(n) => EntryExpr(p, n),
175 NodeStmt(n) => EntryStmt(p, n),
176 NodeArg(n) => EntryArg(p, n),
177 NodeLocal(n) => EntryLocal(p, n),
178 NodePat(n) => EntryPat(p, n),
179 NodeBlock(n) => EntryBlock(p, n),
180 NodeStructCtor(n) => EntryStructCtor(p, n),
181 NodeLifetime(n) => EntryLifetime(p, n)
185 fn parent(self) -> Option<NodeId> {
187 EntryItem(id, _) => id,
188 EntryForeignItem(id, _) => id,
189 EntryTraitItem(id, _) => id,
190 EntryImplItem(id, _) => id,
191 EntryVariant(id, _) => id,
192 EntryExpr(id, _) => id,
193 EntryStmt(id, _) => id,
194 EntryArg(id, _) => id,
195 EntryLocal(id, _) => id,
196 EntryPat(id, _) => id,
197 EntryBlock(id, _) => id,
198 EntryStructCtor(id, _) => id,
199 EntryLifetime(id, _) => id,
204 fn to_node(self) -> Option<Node<'ast>> {
206 EntryItem(_, n) => NodeItem(n),
207 EntryForeignItem(_, n) => NodeForeignItem(n),
208 EntryTraitItem(_, n) => NodeTraitItem(n),
209 EntryImplItem(_, n) => NodeImplItem(n),
210 EntryVariant(_, n) => NodeVariant(n),
211 EntryExpr(_, n) => NodeExpr(n),
212 EntryStmt(_, n) => NodeStmt(n),
213 EntryArg(_, n) => NodeArg(n),
214 EntryLocal(_, n) => NodeLocal(n),
215 EntryPat(_, n) => NodePat(n),
216 EntryBlock(_, n) => NodeBlock(n),
217 EntryStructCtor(_, n) => NodeStructCtor(n),
218 EntryLifetime(_, n) => NodeLifetime(n),
224 /// Stores a crate and any number of inlined items from other crates.
227 inlined_items: TypedArena<InlinedParent>
231 pub fn new(krate: Crate) -> Forest {
234 inlined_items: TypedArena::new()
238 pub fn krate<'ast>(&'ast self) -> &'ast Crate {
243 /// Represents a mapping from Node IDs to AST elements and their parent
245 pub struct Map<'ast> {
246 /// The backing storage for all the AST nodes.
247 forest: &'ast Forest,
249 /// NodeIds are sequential integers from 0, so we can be
250 /// super-compact by storing them in a vector. Not everything with
251 /// a NodeId is in the map, but empirically the occupancy is about
252 /// 75-80%, so there's not too much overhead (certainly less than
253 /// a hashmap, since they (at the time of writing) have a maximum
254 /// of 75% occupancy).
256 /// Also, indexing is pretty quick when you've got a vector and
257 /// plain old integers.
258 map: RefCell<Vec<MapEntry<'ast>>>
261 impl<'ast> Map<'ast> {
262 fn entry_count(&self) -> uint {
263 self.map.borrow().len()
266 fn find_entry(&self, id: NodeId) -> Option<MapEntry<'ast>> {
267 self.map.borrow().get(id as uint).map(|e| *e)
270 pub fn krate(&self) -> &'ast Crate {
274 /// Retrieve the Node corresponding to `id`, panicking if it cannot
276 pub fn get(&self, id: NodeId) -> Node<'ast> {
277 match self.find(id) {
279 None => panic!("couldn't find node id {} in the AST map", id)
283 /// Retrieve the Node corresponding to `id`, returning None if
285 pub fn find(&self, id: NodeId) -> Option<Node<'ast>> {
286 self.find_entry(id).and_then(|x| x.to_node())
289 /// Retrieve the parent NodeId for `id`, or `id` itself if no
290 /// parent is registered in this map.
291 pub fn get_parent(&self, id: NodeId) -> NodeId {
292 self.find_entry(id).and_then(|x| x.parent()).unwrap_or(id)
295 pub fn get_parent_did(&self, id: NodeId) -> DefId {
296 let parent = self.get_parent(id);
297 match self.find_entry(parent) {
298 Some(RootInlinedParent(&InlinedParent {ii: IITraitItem(did, _), ..})) => did,
299 Some(RootInlinedParent(&InlinedParent {ii: IIImplItem(did, _), ..})) => did,
300 _ => ast_util::local_def(parent)
304 pub fn get_foreign_abi(&self, id: NodeId) -> abi::Abi {
305 let parent = self.get_parent(id);
306 let abi = match self.find_entry(parent) {
307 Some(EntryItem(_, i)) => {
309 ItemForeignMod(ref nm) => Some(nm.abi),
313 /// Wrong but OK, because the only inlined foreign items are intrinsics.
314 Some(RootInlinedParent(_)) => Some(abi::RustIntrinsic),
319 None => panic!("expected foreign mod or inlined parent, found {}",
320 self.node_to_string(parent))
324 pub fn get_foreign_vis(&self, id: NodeId) -> Visibility {
325 let vis = self.expect_foreign_item(id).vis;
326 match self.find(self.get_parent(id)) {
327 Some(NodeItem(i)) => vis.inherit_from(i.vis),
332 pub fn expect_item(&self, id: NodeId) -> &'ast Item {
333 match self.find(id) {
334 Some(NodeItem(item)) => item,
335 _ => panic!("expected item, found {}", self.node_to_string(id))
339 pub fn expect_struct(&self, id: NodeId) -> &'ast StructDef {
340 match self.find(id) {
341 Some(NodeItem(i)) => {
343 ItemStruct(ref struct_def, _) => &**struct_def,
344 _ => panic!("struct ID bound to non-struct")
347 Some(NodeVariant(variant)) => {
348 match variant.node.kind {
349 StructVariantKind(ref struct_def) => &**struct_def,
350 _ => panic!("struct ID bound to enum variant that isn't struct-like"),
353 _ => panic!(format!("expected struct, found {}", self.node_to_string(id))),
357 pub fn expect_variant(&self, id: NodeId) -> &'ast Variant {
358 match self.find(id) {
359 Some(NodeVariant(variant)) => variant,
360 _ => panic!(format!("expected variant, found {}", self.node_to_string(id))),
364 pub fn expect_foreign_item(&self, id: NodeId) -> &'ast ForeignItem {
365 match self.find(id) {
366 Some(NodeForeignItem(item)) => item,
367 _ => panic!("expected foreign item, found {}", self.node_to_string(id))
371 pub fn expect_expr(&self, id: NodeId) -> &'ast Expr {
372 match self.find(id) {
373 Some(NodeExpr(expr)) => expr,
374 _ => panic!("expected expr, found {}", self.node_to_string(id))
378 /// returns the name associated with the given NodeId's AST
379 pub fn get_path_elem(&self, id: NodeId) -> PathElem {
380 let node = self.get(id);
384 ItemMod(_) | ItemForeignMod(_) => {
385 PathMod(item.ident.name)
387 _ => PathName(item.ident.name)
390 NodeForeignItem(i) => PathName(i.ident.name),
391 NodeImplItem(ii) => {
393 MethodImplItem(ref m) => {
395 MethDecl(ident, _, _, _, _, _, _, _) => {
399 panic!("no path elem for {}", node)
403 TypeImplItem(ref t) => PathName(t.ident.name),
406 NodeTraitItem(tm) => match *tm {
407 RequiredMethod(ref m) => PathName(m.ident.name),
408 ProvidedMethod(ref m) => {
410 MethDecl(ident, _, _, _, _, _, _, _) => {
413 MethMac(_) => panic!("no path elem for {}", node),
416 TypeTraitItem(ref m) => {
417 PathName(m.ty_param.ident.name)
420 NodeVariant(v) => PathName(v.node.name.name),
421 _ => panic!("no path elem for {}", node)
425 pub fn with_path<T, F>(&self, id: NodeId, f: F) -> T where
426 F: FnOnce(PathElems) -> T,
428 self.with_path_next(id, None, f)
431 pub fn path_to_string(&self, id: NodeId) -> String {
432 self.with_path(id, |path| path_to_string(path))
435 fn path_to_str_with_ident(&self, id: NodeId, i: Ident) -> String {
436 self.with_path(id, |path| {
437 path_to_string(path.chain(Some(PathName(i.name)).into_iter()))
441 fn with_path_next<T, F>(&self, id: NodeId, next: LinkedPath, f: F) -> T where
442 F: FnOnce(PathElems) -> T,
444 let parent = self.get_parent(id);
445 let parent = match self.find_entry(id) {
446 Some(EntryForeignItem(..)) | Some(EntryVariant(..)) => {
447 // Anonymous extern items, enum variants and struct ctors
448 // go in the parent scope.
449 self.get_parent(parent)
451 // But tuple struct ctors don't have names, so use the path of its
452 // parent, the struct item. Similarly with closure expressions.
453 Some(EntryStructCtor(..)) | Some(EntryExpr(..)) => {
454 return self.with_path_next(parent, next, f);
459 match self.find_entry(id) {
460 Some(RootInlinedParent(data)) => {
461 f(Values(data.path.iter()).chain(next))
463 _ => f(Values([].iter()).chain(next))
466 self.with_path_next(parent, Some(&LinkedPathNode {
467 node: self.get_path_elem(id),
473 /// Given a node ID and a closure, apply the closure to the array
474 /// of attributes associated with the AST corresponding to the Node ID
475 pub fn with_attrs<T, F>(&self, id: NodeId, f: F) -> T where
476 F: FnOnce(Option<&[Attribute]>) -> T,
478 let attrs = match self.get(id) {
479 NodeItem(i) => Some(i.attrs[]),
480 NodeForeignItem(fi) => Some(fi.attrs[]),
481 NodeTraitItem(ref tm) => match **tm {
482 RequiredMethod(ref type_m) => Some(type_m.attrs[]),
483 ProvidedMethod(ref m) => Some(m.attrs[]),
484 TypeTraitItem(ref typ) => Some(typ.attrs[]),
486 NodeImplItem(ref ii) => {
488 MethodImplItem(ref m) => Some(m.attrs[]),
489 TypeImplItem(ref t) => Some(t.attrs[]),
492 NodeVariant(ref v) => Some(v.node.attrs[]),
493 // unit/tuple structs take the attributes straight from
494 // the struct definition.
495 // FIXME(eddyb) make this work again (requires access to the map).
496 NodeStructCtor(_) => {
497 return self.with_attrs(self.get_parent(id), f);
504 /// Returns an iterator that yields the node id's with paths that
505 /// match `parts`. (Requires `parts` is non-empty.)
507 /// For example, if given `parts` equal to `["bar", "quux"]`, then
508 /// the iterator will produce node id's for items with paths
509 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
510 /// any other such items it can find in the map.
511 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
512 -> NodesMatchingSuffix<'a, 'ast> {
513 NodesMatchingSuffix {
515 item_name: parts.last().unwrap(),
516 in_which: parts[..parts.len() - 1],
521 pub fn opt_span(&self, id: NodeId) -> Option<Span> {
522 let sp = match self.find(id) {
523 Some(NodeItem(item)) => item.span,
524 Some(NodeForeignItem(foreign_item)) => foreign_item.span,
525 Some(NodeTraitItem(trait_method)) => {
526 match *trait_method {
527 RequiredMethod(ref type_method) => type_method.span,
528 ProvidedMethod(ref method) => method.span,
529 TypeTraitItem(ref typedef) => typedef.ty_param.span,
532 Some(NodeImplItem(ref impl_item)) => {
534 MethodImplItem(ref method) => method.span,
535 TypeImplItem(ref typedef) => typedef.span,
538 Some(NodeVariant(variant)) => variant.span,
539 Some(NodeExpr(expr)) => expr.span,
540 Some(NodeStmt(stmt)) => stmt.span,
541 Some(NodeArg(pat)) | Some(NodeLocal(pat)) => pat.span,
542 Some(NodePat(pat)) => pat.span,
543 Some(NodeBlock(block)) => block.span,
544 Some(NodeStructCtor(_)) => self.expect_item(self.get_parent(id)).span,
550 pub fn span(&self, id: NodeId) -> Span {
552 .unwrap_or_else(|| panic!("AstMap.span: could not find span for id {}", id))
555 pub fn def_id_span(&self, def_id: DefId, fallback: Span) -> Span {
556 if def_id.krate == LOCAL_CRATE {
557 self.opt_span(def_id.node).unwrap_or(fallback)
563 pub fn node_to_string(&self, id: NodeId) -> String {
564 node_id_to_string(self, id, true)
567 pub fn node_to_user_string(&self, id: NodeId) -> String {
568 node_id_to_string(self, id, false)
572 pub struct NodesMatchingSuffix<'a, 'ast:'a> {
574 item_name: &'a String,
575 in_which: &'a [String],
579 impl<'a, 'ast> NodesMatchingSuffix<'a, 'ast> {
580 /// Returns true only if some suffix of the module path for parent
581 /// matches `self.in_which`.
583 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
584 /// returns true if parent's path ends with the suffix
585 /// `x_0::x_1::...::x_k`.
586 fn suffix_matches(&self, parent: NodeId) -> bool {
587 let mut cursor = parent;
588 for part in self.in_which.iter().rev() {
589 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
590 None => return false,
591 Some((node_id, name)) => (node_id, name),
593 if part[] != mod_name.as_str() {
596 cursor = self.map.get_parent(mod_id);
600 // Finds the first mod in parent chain for `id`, along with
603 // If `id` itself is a mod named `m` with parent `p`, then
604 // returns `Some(id, m, p)`. If `id` has no mod in its parent
605 // chain, then returns `None`.
606 fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
610 Some(NodeItem(item)) if item_is_mod(&*item) =>
611 return Some((id, item.ident.name)),
614 let parent = map.get_parent(id);
615 if parent == id { return None }
619 fn item_is_mod(item: &Item) -> bool {
628 // We are looking at some node `n` with a given name and parent
629 // id; do their names match what I am seeking?
630 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
631 name.as_str() == self.item_name[] &&
632 self.suffix_matches(parent_of_n)
636 impl<'a, 'ast> Iterator for NodesMatchingSuffix<'a, 'ast> {
639 fn next(&mut self) -> Option<NodeId> {
642 if idx as uint >= self.map.entry_count() {
646 let (p, name) = match self.map.find_entry(idx) {
647 Some(EntryItem(p, n)) => (p, n.name()),
648 Some(EntryForeignItem(p, n))=> (p, n.name()),
649 Some(EntryTraitItem(p, n)) => (p, n.name()),
650 Some(EntryImplItem(p, n)) => (p, n.name()),
651 Some(EntryVariant(p, n)) => (p, n.name()),
654 if self.matches_names(p, name) {
662 fn name(&self) -> Name;
665 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
667 impl Named for Item { fn name(&self) -> Name { self.ident.name } }
668 impl Named for ForeignItem { fn name(&self) -> Name { self.ident.name } }
669 impl Named for Variant_ { fn name(&self) -> Name { self.name.name } }
670 impl Named for TraitItem {
671 fn name(&self) -> Name {
673 RequiredMethod(ref tm) => tm.ident.name,
674 ProvidedMethod(ref m) => m.name(),
675 TypeTraitItem(ref at) => at.ty_param.ident.name,
679 impl Named for ImplItem {
680 fn name(&self) -> Name {
682 MethodImplItem(ref m) => m.name(),
683 TypeImplItem(ref td) => td.ident.name,
687 impl Named for Method {
688 fn name(&self) -> Name {
690 MethDecl(i, _, _, _, _, _, _, _) => i.name,
691 MethMac(_) => panic!("encountered unexpanded method macro."),
697 fn new_id(&self, id: NodeId) -> NodeId {
700 fn new_def_id(&self, def_id: DefId) -> DefId {
703 fn new_span(&self, span: Span) -> Span {
708 /// A Folder that updates IDs and Span's according to fold_ops.
709 struct IdAndSpanUpdater<F> {
713 impl<F: FoldOps> Folder for IdAndSpanUpdater<F> {
714 fn new_id(&mut self, id: NodeId) -> NodeId {
715 self.fold_ops.new_id(id)
718 fn new_span(&mut self, span: Span) -> Span {
719 self.fold_ops.new_span(span)
723 /// A Visitor that walks over an AST and collects Node's into an AST Map.
724 struct NodeCollector<'ast> {
725 map: Vec<MapEntry<'ast>>,
726 /// The node in which we are currently mapping (an item or a method).
730 impl<'ast> NodeCollector<'ast> {
731 fn insert_entry(&mut self, id: NodeId, entry: MapEntry<'ast>) {
732 debug!("ast_map: {} => {}", id, entry);
733 let len = self.map.len();
734 if id as uint >= len {
735 self.map.extend(repeat(NotPresent).take(id as uint - len + 1));
737 self.map[id as uint] = entry;
740 fn insert(&mut self, id: NodeId, node: Node<'ast>) {
741 let entry = MapEntry::from_node(self.parent, node);
742 self.insert_entry(id, entry);
745 fn visit_fn_decl(&mut self, decl: &'ast FnDecl) {
746 for a in decl.inputs.iter() {
747 self.insert(a.id, NodeArg(&*a.pat));
752 impl<'ast> Visitor<'ast> for NodeCollector<'ast> {
753 fn visit_item(&mut self, i: &'ast Item) {
754 self.insert(i.id, NodeItem(i));
755 let parent = self.parent;
758 ItemImpl(_, _, _, _, ref impl_items) => {
759 for impl_item in impl_items.iter() {
761 MethodImplItem(ref m) => {
762 self.insert(m.id, NodeImplItem(impl_item));
764 TypeImplItem(ref t) => {
765 self.insert(t.id, NodeImplItem(impl_item));
770 ItemEnum(ref enum_definition, _) => {
771 for v in enum_definition.variants.iter() {
772 self.insert(v.node.id, NodeVariant(&**v));
775 ItemForeignMod(ref nm) => {
776 for nitem in nm.items.iter() {
777 self.insert(nitem.id, NodeForeignItem(&**nitem));
780 ItemStruct(ref struct_def, _) => {
781 // If this is a tuple-like struct, register the constructor.
782 match struct_def.ctor_id {
784 self.insert(ctor_id, NodeStructCtor(&**struct_def));
789 ItemTrait(_, _, ref bounds, ref trait_items) => {
790 for b in bounds.iter() {
791 if let TraitTyParamBound(ref t, TraitBoundModifier::None) = *b {
792 self.insert(t.trait_ref.ref_id, NodeItem(i));
796 for tm in trait_items.iter() {
798 RequiredMethod(ref m) => {
799 self.insert(m.id, NodeTraitItem(tm));
801 ProvidedMethod(ref m) => {
802 self.insert(m.id, NodeTraitItem(tm));
804 TypeTraitItem(ref typ) => {
805 self.insert(typ.ty_param.id, NodeTraitItem(tm));
812 visit::walk_item(self, i);
813 self.parent = parent;
816 fn visit_pat(&mut self, pat: &'ast Pat) {
817 self.insert(pat.id, match pat.node {
818 // Note: this is at least *potentially* a pattern...
819 PatIdent(..) => NodeLocal(pat),
822 visit::walk_pat(self, pat);
825 fn visit_expr(&mut self, expr: &'ast Expr) {
826 self.insert(expr.id, NodeExpr(expr));
827 visit::walk_expr(self, expr);
830 fn visit_stmt(&mut self, stmt: &'ast Stmt) {
831 self.insert(ast_util::stmt_id(stmt), NodeStmt(stmt));
832 visit::walk_stmt(self, stmt);
835 fn visit_ty_method(&mut self, m: &'ast TypeMethod) {
836 let parent = self.parent;
838 self.visit_fn_decl(&*m.decl);
839 visit::walk_ty_method(self, m);
840 self.parent = parent;
843 fn visit_fn(&mut self, fk: visit::FnKind<'ast>, fd: &'ast FnDecl,
844 b: &'ast Block, s: Span, id: NodeId) {
846 visit::FkMethod(..) => {
847 let parent = self.parent;
849 self.visit_fn_decl(fd);
850 visit::walk_fn(self, fk, fd, b, s);
851 self.parent = parent;
854 self.visit_fn_decl(fd);
855 visit::walk_fn(self, fk, fd, b, s);
860 fn visit_ty(&mut self, ty: &'ast Ty) {
862 TyClosure(ref fd) => {
863 self.visit_fn_decl(&*fd.decl);
865 TyBareFn(ref fd) => {
866 self.visit_fn_decl(&*fd.decl);
870 visit::walk_ty(self, ty);
873 fn visit_block(&mut self, block: &'ast Block) {
874 self.insert(block.id, NodeBlock(block));
875 visit::walk_block(self, block);
878 fn visit_lifetime_ref(&mut self, lifetime: &'ast Lifetime) {
879 self.insert(lifetime.id, NodeLifetime(lifetime));
882 fn visit_lifetime_def(&mut self, def: &'ast LifetimeDef) {
883 self.visit_lifetime_ref(&def.lifetime);
887 pub fn map_crate<'ast, F: FoldOps>(forest: &'ast mut Forest, fold_ops: F) -> Map<'ast> {
888 // Replace the crate with an empty one to take it out.
889 let krate = mem::replace(&mut forest.krate, Crate {
897 exported_macros: vec![],
900 forest.krate = IdAndSpanUpdater { fold_ops: fold_ops }.fold_crate(krate);
902 let mut collector = NodeCollector {
904 parent: CRATE_NODE_ID
906 collector.insert_entry(CRATE_NODE_ID, RootCrate);
907 visit::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.);
928 map: RefCell::new(map)
932 /// Used for items loaded from external crate that are being inlined into this
933 /// crate. The `path` should be the path to the item but should not include
935 pub fn map_decoded_item<'ast, F: FoldOps>(map: &Map<'ast>,
939 -> &'ast InlinedItem {
940 let mut fld = IdAndSpanUpdater { fold_ops: fold_ops };
942 IIItem(i) => IIItem(fld.fold_item(i).expect_one("expected one item")),
943 IITraitItem(d, ti) => match ti {
944 ProvidedMethod(m) => {
945 IITraitItem(fld.fold_ops.new_def_id(d),
946 ProvidedMethod(fld.fold_method(m)
947 .expect_one("expected one method")))
949 RequiredMethod(ty_m) => {
950 IITraitItem(fld.fold_ops.new_def_id(d),
951 RequiredMethod(fld.fold_type_method(ty_m)))
953 TypeTraitItem(at) => {
955 fld.fold_ops.new_def_id(d),
956 TypeTraitItem(P(fld.fold_associated_type((*at).clone()))))
959 IIImplItem(d, m) => match m {
960 MethodImplItem(m) => {
961 IIImplItem(fld.fold_ops.new_def_id(d),
962 MethodImplItem(fld.fold_method(m)
963 .expect_one("expected one method")))
966 IIImplItem(fld.fold_ops.new_def_id(d),
967 TypeImplItem(P(fld.fold_typedef((*t).clone()))))
970 IIForeign(i) => IIForeign(fld.fold_foreign_item(i))
973 let ii_parent = map.forest.inlined_items.alloc(InlinedParent {
978 let mut collector = NodeCollector {
979 map: mem::replace(&mut *map.map.borrow_mut(), vec![]),
980 parent: fld.new_id(DUMMY_NODE_ID)
982 let ii_parent_id = collector.parent;
983 collector.insert_entry(ii_parent_id, RootInlinedParent(ii_parent));
984 visit::walk_inlined_item(&mut collector, &ii_parent.ii);
986 // Methods get added to the AST map when their impl is visited. Since we
987 // don't decode and instantiate the impl, but just the method, we have to
988 // add it to the table now. Likewise with foreign items.
991 IITraitItem(_, ref trait_item) => {
992 let trait_item_id = match *trait_item {
993 ProvidedMethod(ref m) => m.id,
994 RequiredMethod(ref m) => m.id,
995 TypeTraitItem(ref ty) => ty.ty_param.id,
998 collector.insert(trait_item_id, NodeTraitItem(trait_item));
1000 IIImplItem(_, ref impl_item) => {
1001 let impl_item_id = match *impl_item {
1002 MethodImplItem(ref m) => m.id,
1003 TypeImplItem(ref ti) => ti.id,
1006 collector.insert(impl_item_id, NodeImplItem(impl_item));
1008 IIForeign(ref i) => {
1009 collector.insert(i.id, NodeForeignItem(&**i));
1012 *map.map.borrow_mut() = collector.map;
1016 pub trait NodePrinter {
1017 fn print_node(&mut self, node: &Node) -> IoResult<()>;
1020 impl<'a> NodePrinter for pprust::State<'a> {
1021 fn print_node(&mut self, node: &Node) -> IoResult<()> {
1023 NodeItem(a) => self.print_item(&*a),
1024 NodeForeignItem(a) => self.print_foreign_item(&*a),
1025 NodeTraitItem(a) => self.print_trait_method(&*a),
1026 NodeImplItem(a) => self.print_impl_item(&*a),
1027 NodeVariant(a) => self.print_variant(&*a),
1028 NodeExpr(a) => self.print_expr(&*a),
1029 NodeStmt(a) => self.print_stmt(&*a),
1030 NodePat(a) => self.print_pat(&*a),
1031 NodeBlock(a) => self.print_block(&*a),
1032 NodeLifetime(a) => self.print_lifetime(&*a),
1034 // these cases do not carry enough information in the
1035 // ast_map to reconstruct their full structure for pretty
1037 NodeLocal(_) => panic!("cannot print isolated Local"),
1038 NodeArg(_) => panic!("cannot print isolated Arg"),
1039 NodeStructCtor(_) => panic!("cannot print isolated StructCtor"),
1044 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
1045 let id_str = format!(" (id={})", id);
1046 let id_str = if include_id { id_str[] } else { "" };
1048 match map.find(id) {
1049 Some(NodeItem(item)) => {
1050 let path_str = map.path_to_str_with_ident(id, item.ident);
1051 let item_str = match item.node {
1052 ItemStatic(..) => "static",
1053 ItemConst(..) => "const",
1055 ItemMod(..) => "mod",
1056 ItemForeignMod(..) => "foreign mod",
1058 ItemEnum(..) => "enum",
1059 ItemStruct(..) => "struct",
1060 ItemTrait(..) => "trait",
1061 ItemImpl(..) => "impl",
1062 ItemMac(..) => "macro"
1064 format!("{} {}{}", item_str, path_str, id_str)
1066 Some(NodeForeignItem(item)) => {
1067 let path_str = map.path_to_str_with_ident(id, item.ident);
1068 format!("foreign item {}{}", path_str, id_str)
1070 Some(NodeImplItem(ref ii)) => {
1072 MethodImplItem(ref m) => {
1074 MethDecl(ident, _, _, _, _, _, _, _) =>
1075 format!("method {} in {}{}",
1076 token::get_ident(ident),
1077 map.path_to_string(id), id_str),
1079 format!("method macro {}{}",
1080 pprust::mac_to_string(mac), id_str)
1083 TypeImplItem(ref t) => {
1084 format!("typedef {} in {}{}",
1085 token::get_ident(t.ident),
1086 map.path_to_string(id),
1091 Some(NodeTraitItem(ref tm)) => {
1093 RequiredMethod(_) | ProvidedMethod(_) => {
1094 let m = ast_util::trait_item_to_ty_method(&**tm);
1095 format!("method {} in {}{}",
1096 token::get_ident(m.ident),
1097 map.path_to_string(id),
1100 TypeTraitItem(ref t) => {
1101 format!("type item {} in {}{}",
1102 token::get_ident(t.ty_param.ident),
1103 map.path_to_string(id),
1108 Some(NodeVariant(ref variant)) => {
1109 format!("variant {} in {}{}",
1110 token::get_ident(variant.node.name),
1111 map.path_to_string(id), id_str)
1113 Some(NodeExpr(ref expr)) => {
1114 format!("expr {}{}", pprust::expr_to_string(&**expr), id_str)
1116 Some(NodeStmt(ref stmt)) => {
1117 format!("stmt {}{}", pprust::stmt_to_string(&**stmt), id_str)
1119 Some(NodeArg(ref pat)) => {
1120 format!("arg {}{}", pprust::pat_to_string(&**pat), id_str)
1122 Some(NodeLocal(ref pat)) => {
1123 format!("local {}{}", pprust::pat_to_string(&**pat), id_str)
1125 Some(NodePat(ref pat)) => {
1126 format!("pat {}{}", pprust::pat_to_string(&**pat), id_str)
1128 Some(NodeBlock(ref block)) => {
1129 format!("block {}{}", pprust::block_to_string(&**block), id_str)
1131 Some(NodeStructCtor(_)) => {
1132 format!("struct_ctor {}{}", map.path_to_string(id), id_str)
1134 Some(NodeLifetime(ref l)) => {
1135 format!("lifetime {}{}",
1136 pprust::lifetime_to_string(&**l), id_str)
1139 format!("unknown node{}", id_str)