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.
14 use codemap::{DUMMY_SP, Span, Spanned};
19 use visit::{mod, Visitor};
21 use arena::TypedArena;
22 use std::cell::RefCell;
24 use std::io::IoResult;
31 #[deriving(Clone, PartialEq)]
38 pub fn name(&self) -> Name {
40 PathMod(name) | PathName(name) => name
45 impl fmt::Show for PathElem {
46 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
47 let slot = token::get_name(self.name());
53 struct LinkedPathNode<'a> {
58 type LinkedPath<'a> = Option<&'a LinkedPathNode<'a>>;
60 impl<'a> Iterator<PathElem> for LinkedPath<'a> {
61 fn next(&mut self) -> Option<PathElem> {
72 // HACK(eddyb) move this into libstd (value wrapper for slice::Items).
74 pub struct Values<'a, T:'a>(pub slice::Items<'a, T>);
76 impl<'a, T: Copy> Iterator<T> for Values<'a, T> {
77 fn next(&mut self) -> Option<T> {
78 let &Values(ref mut items) = self;
79 items.next().map(|&x| x)
83 /// The type of the iterator used by with_path.
84 pub type PathElems<'a, 'b> = iter::Chain<Values<'a, PathElem>, LinkedPath<'b>>;
86 pub fn path_to_string<PI: Iterator<PathElem>>(mut path: PI) -> String {
87 let itr = token::get_ident_interner();
89 path.fold(String::new(), |mut s, e| {
90 let e = itr.get(e.name());
94 s.push_str(e.as_slice());
100 pub enum Node<'ast> {
101 NodeItem(&'ast Item),
102 NodeForeignItem(&'ast ForeignItem),
103 NodeTraitItem(&'ast TraitItem),
104 NodeImplItem(&'ast ImplItem),
105 NodeVariant(&'ast Variant),
106 NodeExpr(&'ast Expr),
107 NodeStmt(&'ast Stmt),
109 NodeLocal(&'ast Pat),
111 NodeBlock(&'ast Block),
113 /// NodeStructCtor represents a tuple struct.
114 NodeStructCtor(&'ast StructDef),
116 NodeLifetime(&'ast Lifetime),
119 /// Represents an entry and its parent Node ID
120 /// The odd layout is to bring down the total size.
122 enum MapEntry<'ast> {
123 /// Placeholder for holes in the map.
126 /// All the node types, with a parent ID.
127 EntryItem(NodeId, &'ast Item),
128 EntryForeignItem(NodeId, &'ast ForeignItem),
129 EntryTraitItem(NodeId, &'ast TraitItem),
130 EntryImplItem(NodeId, &'ast ImplItem),
131 EntryVariant(NodeId, &'ast Variant),
132 EntryExpr(NodeId, &'ast Expr),
133 EntryStmt(NodeId, &'ast Stmt),
134 EntryArg(NodeId, &'ast Pat),
135 EntryLocal(NodeId, &'ast Pat),
136 EntryPat(NodeId, &'ast Pat),
137 EntryBlock(NodeId, &'ast Block),
138 EntryStructCtor(NodeId, &'ast StructDef),
139 EntryLifetime(NodeId, &'ast Lifetime),
141 /// Roots for node trees.
143 RootInlinedParent(&'ast InlinedParent)
146 impl<'ast> Clone for MapEntry<'ast> {
147 fn clone(&self) -> MapEntry<'ast> {
153 struct InlinedParent {
158 impl<'ast> MapEntry<'ast> {
159 fn from_node(p: NodeId, node: Node<'ast>) -> MapEntry<'ast> {
161 NodeItem(n) => EntryItem(p, n),
162 NodeForeignItem(n) => EntryForeignItem(p, n),
163 NodeTraitItem(n) => EntryTraitItem(p, n),
164 NodeImplItem(n) => EntryImplItem(p, n),
165 NodeVariant(n) => EntryVariant(p, n),
166 NodeExpr(n) => EntryExpr(p, n),
167 NodeStmt(n) => EntryStmt(p, n),
168 NodeArg(n) => EntryArg(p, n),
169 NodeLocal(n) => EntryLocal(p, n),
170 NodePat(n) => EntryPat(p, n),
171 NodeBlock(n) => EntryBlock(p, n),
172 NodeStructCtor(n) => EntryStructCtor(p, n),
173 NodeLifetime(n) => EntryLifetime(p, n)
177 fn parent(self) -> Option<NodeId> {
179 EntryItem(id, _) => id,
180 EntryForeignItem(id, _) => id,
181 EntryTraitItem(id, _) => id,
182 EntryImplItem(id, _) => id,
183 EntryVariant(id, _) => id,
184 EntryExpr(id, _) => id,
185 EntryStmt(id, _) => id,
186 EntryArg(id, _) => id,
187 EntryLocal(id, _) => id,
188 EntryPat(id, _) => id,
189 EntryBlock(id, _) => id,
190 EntryStructCtor(id, _) => id,
191 EntryLifetime(id, _) => id,
196 fn to_node(self) -> Option<Node<'ast>> {
198 EntryItem(_, n) => NodeItem(n),
199 EntryForeignItem(_, n) => NodeForeignItem(n),
200 EntryTraitItem(_, n) => NodeTraitItem(n),
201 EntryImplItem(_, n) => NodeImplItem(n),
202 EntryVariant(_, n) => NodeVariant(n),
203 EntryExpr(_, n) => NodeExpr(n),
204 EntryStmt(_, n) => NodeStmt(n),
205 EntryArg(_, n) => NodeArg(n),
206 EntryLocal(_, n) => NodeLocal(n),
207 EntryPat(_, n) => NodePat(n),
208 EntryBlock(_, n) => NodeBlock(n),
209 EntryStructCtor(_, n) => NodeStructCtor(n),
210 EntryLifetime(_, n) => NodeLifetime(n),
216 /// Stores a crate and any number of inlined items from other crates.
219 inlined_items: TypedArena<InlinedParent>
223 pub fn new(krate: Crate) -> Forest {
226 inlined_items: TypedArena::new()
230 pub fn krate<'ast>(&'ast self) -> &'ast Crate {
235 /// Represents a mapping from Node IDs to AST elements and their parent
237 pub struct Map<'ast> {
238 /// The backing storage for all the AST nodes.
239 forest: &'ast Forest,
241 /// NodeIds are sequential integers from 0, so we can be
242 /// super-compact by storing them in a vector. Not everything with
243 /// a NodeId is in the map, but empirically the occupancy is about
244 /// 75-80%, so there's not too much overhead (certainly less than
245 /// a hashmap, since they (at the time of writing) have a maximum
246 /// of 75% occupancy).
248 /// Also, indexing is pretty quick when you've got a vector and
249 /// plain old integers.
250 map: RefCell<Vec<MapEntry<'ast>>>
253 impl<'ast> Map<'ast> {
254 fn entry_count(&self) -> uint {
255 self.map.borrow().len()
258 fn find_entry(&self, id: NodeId) -> Option<MapEntry<'ast>> {
259 self.map.borrow().as_slice().get(id as uint).map(|e| *e)
262 pub fn krate(&self) -> &'ast Crate {
266 /// Retrieve the Node corresponding to `id`, failing if it cannot
268 pub fn get(&self, id: NodeId) -> Node<'ast> {
269 match self.find(id) {
271 None => fail!("couldn't find node id {} in the AST map", id)
275 /// Retrieve the Node corresponding to `id`, returning None if
277 pub fn find(&self, id: NodeId) -> Option<Node<'ast>> {
278 self.find_entry(id).and_then(|x| x.to_node())
281 /// Retrieve the parent NodeId for `id`, or `id` itself if no
282 /// parent is registered in this map.
283 pub fn get_parent(&self, id: NodeId) -> NodeId {
284 self.find_entry(id).and_then(|x| x.parent()).unwrap_or(id)
287 pub fn get_parent_did(&self, id: NodeId) -> DefId {
288 let parent = self.get_parent(id);
289 match self.find_entry(parent) {
290 Some(RootInlinedParent(&InlinedParent {ii: IITraitItem(did, _), ..})) => did,
291 Some(RootInlinedParent(&InlinedParent {ii: IIImplItem(did, _), ..})) => did,
292 _ => ast_util::local_def(parent)
296 pub fn get_foreign_abi(&self, id: NodeId) -> abi::Abi {
297 let parent = self.get_parent(id);
298 let abi = match self.find_entry(parent) {
299 Some(EntryItem(_, i)) => {
301 ItemForeignMod(ref nm) => Some(nm.abi),
305 /// Wrong but OK, because the only inlined foreign items are intrinsics.
306 Some(RootInlinedParent(_)) => Some(abi::RustIntrinsic),
311 None => fail!("expected foreign mod or inlined parent, found {}",
312 self.node_to_string(parent))
316 pub fn get_foreign_vis(&self, id: NodeId) -> Visibility {
317 let vis = self.expect_foreign_item(id).vis;
318 match self.find(self.get_parent(id)) {
319 Some(NodeItem(i)) => vis.inherit_from(i.vis),
324 pub fn expect_item(&self, id: NodeId) -> &'ast Item {
325 match self.find(id) {
326 Some(NodeItem(item)) => item,
327 _ => fail!("expected item, found {}", self.node_to_string(id))
331 pub fn expect_struct(&self, id: NodeId) -> &'ast StructDef {
332 match self.find(id) {
333 Some(NodeItem(i)) => {
335 ItemStruct(ref struct_def, _) => &**struct_def,
336 _ => fail!("struct ID bound to non-struct")
339 Some(NodeVariant(variant)) => {
340 match variant.node.kind {
341 StructVariantKind(ref struct_def) => &**struct_def,
342 _ => fail!("struct ID bound to enum variant that isn't struct-like"),
345 _ => fail!(format!("expected struct, found {}", self.node_to_string(id))),
349 pub fn expect_variant(&self, id: NodeId) -> &'ast Variant {
350 match self.find(id) {
351 Some(NodeVariant(variant)) => variant,
352 _ => fail!(format!("expected variant, found {}", self.node_to_string(id))),
356 pub fn expect_foreign_item(&self, id: NodeId) -> &'ast ForeignItem {
357 match self.find(id) {
358 Some(NodeForeignItem(item)) => item,
359 _ => fail!("expected foreign item, found {}", self.node_to_string(id))
363 pub fn expect_expr(&self, id: NodeId) -> &'ast Expr {
364 match self.find(id) {
365 Some(NodeExpr(expr)) => expr,
366 _ => fail!("expected expr, found {}", self.node_to_string(id))
370 /// returns the name associated with the given NodeId's AST
371 pub fn get_path_elem(&self, id: NodeId) -> PathElem {
372 let node = self.get(id);
376 ItemMod(_) | ItemForeignMod(_) => {
377 PathMod(item.ident.name)
379 _ => PathName(item.ident.name)
382 NodeForeignItem(i) => PathName(i.ident.name),
383 NodeImplItem(ii) => {
385 MethodImplItem(ref m) => {
387 MethDecl(ident, _, _, _, _, _, _, _) => {
391 fail!("no path elem for {}", node)
395 TypeImplItem(ref t) => PathName(t.ident.name),
398 NodeTraitItem(tm) => match *tm {
399 RequiredMethod(ref m) => PathName(m.ident.name),
400 ProvidedMethod(ref m) => {
402 MethDecl(ident, _, _, _, _, _, _, _) => {
405 MethMac(_) => fail!("no path elem for {}", node),
408 TypeTraitItem(ref m) => PathName(m.ident.name),
410 NodeVariant(v) => PathName(v.node.name.name),
411 _ => fail!("no path elem for {}", node)
415 pub fn with_path<T>(&self, id: NodeId, f: |PathElems| -> T) -> T {
416 self.with_path_next(id, None, f)
419 pub fn path_to_string(&self, id: NodeId) -> String {
420 self.with_path(id, |path| path_to_string(path))
423 fn path_to_str_with_ident(&self, id: NodeId, i: Ident) -> String {
424 self.with_path(id, |path| {
425 path_to_string(path.chain(Some(PathName(i.name)).into_iter()))
429 fn with_path_next<T>(&self, id: NodeId, next: LinkedPath, f: |PathElems| -> T) -> T {
430 let parent = self.get_parent(id);
431 let parent = match self.find_entry(id) {
432 Some(EntryForeignItem(..)) | Some(EntryVariant(..)) => {
433 // Anonymous extern items, enum variants and struct ctors
434 // go in the parent scope.
435 self.get_parent(parent)
437 // But tuple struct ctors don't have names, so use the path of its
438 // parent, the struct item. Similarly with closure expressions.
439 Some(EntryStructCtor(..)) | Some(EntryExpr(..)) => {
440 return self.with_path_next(parent, next, f);
445 match self.find_entry(id) {
446 Some(RootInlinedParent(data)) => {
447 f(Values(data.path.iter()).chain(next))
449 _ => f(Values([].iter()).chain(next))
452 self.with_path_next(parent, Some(&LinkedPathNode {
453 node: self.get_path_elem(id),
459 /// Given a node ID and a closure, apply the closure to the array
460 /// of attributes associated with the AST corresponding to the Node ID
461 pub fn with_attrs<T>(&self, id: NodeId, f: |Option<&[Attribute]>| -> T) -> T {
462 let attrs = match self.get(id) {
463 NodeItem(i) => Some(i.attrs.as_slice()),
464 NodeForeignItem(fi) => Some(fi.attrs.as_slice()),
465 NodeTraitItem(ref tm) => match **tm {
466 RequiredMethod(ref type_m) => Some(type_m.attrs.as_slice()),
467 ProvidedMethod(ref m) => Some(m.attrs.as_slice()),
468 TypeTraitItem(ref typ) => Some(typ.attrs.as_slice()),
470 NodeImplItem(ref ii) => {
472 MethodImplItem(ref m) => Some(m.attrs.as_slice()),
473 TypeImplItem(ref t) => Some(t.attrs.as_slice()),
476 NodeVariant(ref v) => Some(v.node.attrs.as_slice()),
477 // unit/tuple structs take the attributes straight from
478 // the struct definition.
479 // FIXME(eddyb) make this work again (requires access to the map).
480 NodeStructCtor(_) => {
481 return self.with_attrs(self.get_parent(id), f);
488 /// Returns an iterator that yields the node id's with paths that
489 /// match `parts`. (Requires `parts` is non-empty.)
491 /// For example, if given `parts` equal to `["bar", "quux"]`, then
492 /// the iterator will produce node id's for items with paths
493 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
494 /// any other such items it can find in the map.
495 pub fn nodes_matching_suffix<'a, S:Str>(&'a self, parts: &'a [S])
496 -> NodesMatchingSuffix<'a, 'ast, S> {
497 NodesMatchingSuffix {
499 item_name: parts.last().unwrap(),
500 in_which: parts[..parts.len() - 1],
505 pub fn opt_span(&self, id: NodeId) -> Option<Span> {
506 let sp = match self.find(id) {
507 Some(NodeItem(item)) => item.span,
508 Some(NodeForeignItem(foreign_item)) => foreign_item.span,
509 Some(NodeTraitItem(trait_method)) => {
510 match *trait_method {
511 RequiredMethod(ref type_method) => type_method.span,
512 ProvidedMethod(ref method) => method.span,
513 TypeTraitItem(ref typedef) => typedef.span,
516 Some(NodeImplItem(ref impl_item)) => {
518 MethodImplItem(ref method) => method.span,
519 TypeImplItem(ref typedef) => typedef.span,
522 Some(NodeVariant(variant)) => variant.span,
523 Some(NodeExpr(expr)) => expr.span,
524 Some(NodeStmt(stmt)) => stmt.span,
525 Some(NodeArg(pat)) | Some(NodeLocal(pat)) => pat.span,
526 Some(NodePat(pat)) => pat.span,
527 Some(NodeBlock(block)) => block.span,
528 Some(NodeStructCtor(_)) => self.expect_item(self.get_parent(id)).span,
534 pub fn span(&self, id: NodeId) -> Span {
536 .unwrap_or_else(|| fail!("AstMap.span: could not find span for id {}", id))
539 pub fn def_id_span(&self, def_id: DefId, fallback: Span) -> Span {
540 if def_id.krate == LOCAL_CRATE {
541 self.span(def_id.node)
547 pub fn node_to_string(&self, id: NodeId) -> String {
548 node_id_to_string(self, id)
552 pub struct NodesMatchingSuffix<'a, 'ast:'a, S:'a> {
559 impl<'a, 'ast, S:Str> NodesMatchingSuffix<'a, 'ast, S> {
560 /// Returns true only if some suffix of the module path for parent
561 /// matches `self.in_which`.
563 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
564 /// returns true if parent's path ends with the suffix
565 /// `x_0::x_1::...::x_k`.
566 fn suffix_matches(&self, parent: NodeId) -> bool {
567 let mut cursor = parent;
568 for part in self.in_which.iter().rev() {
569 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
570 None => return false,
571 Some((node_id, name)) => (node_id, name),
573 if part.as_slice() != mod_name.as_str() {
576 cursor = self.map.get_parent(mod_id);
580 // Finds the first mod in parent chain for `id`, along with
583 // If `id` itself is a mod named `m` with parent `p`, then
584 // returns `Some(id, m, p)`. If `id` has no mod in its parent
585 // chain, then returns `None`.
586 fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
590 Some(NodeItem(item)) if item_is_mod(&*item) =>
591 return Some((id, item.ident.name)),
594 let parent = map.get_parent(id);
595 if parent == id { return None }
599 fn item_is_mod(item: &Item) -> bool {
608 // We are looking at some node `n` with a given name and parent
609 // id; do their names match what I am seeking?
610 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
611 name.as_str() == self.item_name.as_slice() &&
612 self.suffix_matches(parent_of_n)
616 impl<'a, 'ast, S:Str> Iterator<NodeId> for NodesMatchingSuffix<'a, 'ast, S> {
617 fn next(&mut self) -> Option<NodeId> {
620 if idx as uint >= self.map.entry_count() {
624 let (p, name) = match self.map.find_entry(idx) {
625 Some(EntryItem(p, n)) => (p, n.name()),
626 Some(EntryForeignItem(p, n))=> (p, n.name()),
627 Some(EntryTraitItem(p, n)) => (p, n.name()),
628 Some(EntryImplItem(p, n)) => (p, n.name()),
629 Some(EntryVariant(p, n)) => (p, n.name()),
632 if self.matches_names(p, name) {
640 fn name(&self) -> Name;
643 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
645 impl Named for Item { fn name(&self) -> Name { self.ident.name } }
646 impl Named for ForeignItem { fn name(&self) -> Name { self.ident.name } }
647 impl Named for Variant_ { fn name(&self) -> Name { self.name.name } }
648 impl Named for TraitItem {
649 fn name(&self) -> Name {
651 RequiredMethod(ref tm) => tm.ident.name,
652 ProvidedMethod(ref m) => m.name(),
653 TypeTraitItem(ref at) => at.ident.name,
657 impl Named for ImplItem {
658 fn name(&self) -> Name {
660 MethodImplItem(ref m) => m.name(),
661 TypeImplItem(ref td) => td.ident.name,
665 impl Named for Method {
666 fn name(&self) -> Name {
668 MethDecl(i, _, _, _, _, _, _, _) => i.name,
669 MethMac(_) => fail!("encountered unexpanded method macro."),
675 fn new_id(&self, id: NodeId) -> NodeId {
678 fn new_def_id(&self, def_id: DefId) -> DefId {
681 fn new_span(&self, span: Span) -> Span {
686 /// A Folder that updates IDs and Span's according to fold_ops.
687 struct IdAndSpanUpdater<F> {
691 impl<F: FoldOps> Folder for IdAndSpanUpdater<F> {
692 fn new_id(&mut self, id: NodeId) -> NodeId {
693 self.fold_ops.new_id(id)
696 fn new_span(&mut self, span: Span) -> Span {
697 self.fold_ops.new_span(span)
701 /// A Visitor that walks over an AST and collects Node's into an AST Map.
702 struct NodeCollector<'ast> {
703 map: Vec<MapEntry<'ast>>,
704 /// The node in which we are currently mapping (an item or a method).
708 impl<'ast> NodeCollector<'ast> {
709 fn insert_entry(&mut self, id: NodeId, entry: MapEntry<'ast>) {
710 debug!("ast_map: {} => {}", id, entry);
711 let len = self.map.len();
712 if id as uint >= len {
713 self.map.grow(id as uint - len + 1, NotPresent);
715 *self.map.get_mut(id as uint) = entry;
718 fn insert(&mut self, id: NodeId, node: Node<'ast>) {
719 let entry = MapEntry::from_node(self.parent, node);
720 self.insert_entry(id, entry);
723 fn visit_fn_decl(&mut self, decl: &'ast FnDecl) {
724 for a in decl.inputs.iter() {
725 self.insert(a.id, NodeArg(&*a.pat));
730 impl<'ast> Visitor<'ast> for NodeCollector<'ast> {
731 fn visit_item(&mut self, i: &'ast Item) {
732 self.insert(i.id, NodeItem(i));
733 let parent = self.parent;
736 ItemImpl(_, _, _, ref impl_items) => {
737 for impl_item in impl_items.iter() {
739 MethodImplItem(ref m) => {
740 self.insert(m.id, NodeImplItem(impl_item));
742 TypeImplItem(ref t) => {
743 self.insert(t.id, NodeImplItem(impl_item));
748 ItemEnum(ref enum_definition, _) => {
749 for v in enum_definition.variants.iter() {
750 self.insert(v.node.id, NodeVariant(&**v));
753 ItemForeignMod(ref nm) => {
754 for nitem in nm.items.iter() {
755 self.insert(nitem.id, NodeForeignItem(&**nitem));
758 ItemStruct(ref struct_def, _) => {
759 // If this is a tuple-like struct, register the constructor.
760 match struct_def.ctor_id {
762 self.insert(ctor_id, NodeStructCtor(&**struct_def));
767 ItemTrait(_, _, ref bounds, ref trait_items) => {
768 for b in bounds.iter() {
770 TraitTyParamBound(ref t) => {
771 self.insert(t.ref_id, NodeItem(i));
777 for tm in trait_items.iter() {
779 RequiredMethod(ref m) => {
780 self.insert(m.id, NodeTraitItem(tm));
782 ProvidedMethod(ref m) => {
783 self.insert(m.id, NodeTraitItem(tm));
785 TypeTraitItem(ref typ) => {
786 self.insert(typ.id, NodeTraitItem(tm));
793 visit::walk_item(self, i);
794 self.parent = parent;
797 fn visit_pat(&mut self, pat: &'ast Pat) {
798 self.insert(pat.id, match pat.node {
799 // Note: this is at least *potentially* a pattern...
800 PatIdent(..) => NodeLocal(pat),
803 visit::walk_pat(self, pat);
806 fn visit_expr(&mut self, expr: &'ast Expr) {
807 self.insert(expr.id, NodeExpr(expr));
808 visit::walk_expr(self, expr);
811 fn visit_stmt(&mut self, stmt: &'ast Stmt) {
812 self.insert(ast_util::stmt_id(stmt), NodeStmt(stmt));
813 visit::walk_stmt(self, stmt);
816 fn visit_ty_method(&mut self, m: &'ast TypeMethod) {
817 let parent = self.parent;
819 self.visit_fn_decl(&*m.decl);
820 visit::walk_ty_method(self, m);
821 self.parent = parent;
824 fn visit_fn(&mut self, fk: visit::FnKind<'ast>, fd: &'ast FnDecl,
825 b: &'ast Block, s: Span, id: NodeId) {
827 visit::FkMethod(..) => {
828 let parent = self.parent;
830 self.visit_fn_decl(fd);
831 visit::walk_fn(self, fk, fd, b, s);
832 self.parent = parent;
835 self.visit_fn_decl(fd);
836 visit::walk_fn(self, fk, fd, b, s);
841 fn visit_ty(&mut self, ty: &'ast Ty) {
843 TyClosure(ref fd) | TyProc(ref fd) => {
844 self.visit_fn_decl(&*fd.decl);
846 TyBareFn(ref fd) => {
847 self.visit_fn_decl(&*fd.decl);
849 TyUnboxedFn(ref fd) => {
850 self.visit_fn_decl(&*fd.decl);
854 visit::walk_ty(self, ty);
857 fn visit_block(&mut self, block: &'ast Block) {
858 self.insert(block.id, NodeBlock(block));
859 visit::walk_block(self, block);
862 fn visit_lifetime_ref(&mut self, lifetime: &'ast Lifetime) {
863 self.insert(lifetime.id, NodeLifetime(lifetime));
866 fn visit_lifetime_decl(&mut self, def: &'ast LifetimeDef) {
867 self.visit_lifetime_ref(&def.lifetime);
871 pub fn map_crate<'ast, F: FoldOps>(forest: &'ast mut Forest, fold_ops: F) -> Map<'ast> {
872 // Replace the crate with an empty one to take it out.
873 let krate = mem::replace(&mut forest.krate, Crate {
881 exported_macros: vec![],
884 forest.krate = IdAndSpanUpdater { fold_ops: fold_ops }.fold_crate(krate);
886 let mut collector = NodeCollector {
888 parent: CRATE_NODE_ID
890 collector.insert_entry(CRATE_NODE_ID, RootCrate);
891 visit::walk_crate(&mut collector, &forest.krate);
892 let map = collector.map;
894 if log_enabled!(::log::DEBUG) {
895 // This only makes sense for ordered stores; note the
896 // enumerate to count the number of entries.
897 let (entries_less_1, _) = map.iter().filter(|&x| {
902 }).enumerate().last().expect("AST map was empty after folding?");
904 let entries = entries_less_1 + 1;
905 let vector_length = map.len();
906 debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
907 entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
912 map: RefCell::new(map)
916 /// Used for items loaded from external crate that are being inlined into this
917 /// crate. The `path` should be the path to the item but should not include
919 pub fn map_decoded_item<'ast, F: FoldOps>(map: &Map<'ast>,
923 -> &'ast InlinedItem {
924 let mut fld = IdAndSpanUpdater { fold_ops: fold_ops };
926 IIItem(i) => IIItem(fld.fold_item(i).expect_one("expected one item")),
927 IITraitItem(d, ti) => match ti {
928 ProvidedMethod(m) => {
929 IITraitItem(fld.fold_ops.new_def_id(d),
930 ProvidedMethod(fld.fold_method(m)
931 .expect_one("expected one method")))
933 RequiredMethod(ty_m) => {
934 IITraitItem(fld.fold_ops.new_def_id(d),
935 RequiredMethod(fld.fold_type_method(ty_m)))
937 TypeTraitItem(at) => {
939 fld.fold_ops.new_def_id(d),
940 TypeTraitItem(P(fld.fold_associated_type((*at).clone()))))
943 IIImplItem(d, m) => match m {
944 MethodImplItem(m) => {
945 IIImplItem(fld.fold_ops.new_def_id(d),
946 MethodImplItem(fld.fold_method(m)
947 .expect_one("expected one method")))
950 IIImplItem(fld.fold_ops.new_def_id(d),
951 TypeImplItem(P(fld.fold_typedef((*t).clone()))))
954 IIForeign(i) => IIForeign(fld.fold_foreign_item(i))
957 let ii_parent = map.forest.inlined_items.alloc(InlinedParent {
962 let mut collector = NodeCollector {
963 map: mem::replace(&mut *map.map.borrow_mut(), vec![]),
964 parent: fld.new_id(DUMMY_NODE_ID)
966 let ii_parent_id = collector.parent;
967 collector.insert_entry(ii_parent_id, RootInlinedParent(ii_parent));
968 visit::walk_inlined_item(&mut collector, &ii_parent.ii);
970 // Methods get added to the AST map when their impl is visited. Since we
971 // don't decode and instantiate the impl, but just the method, we have to
972 // add it to the table now. Likewise with foreign items.
975 IITraitItem(_, ref trait_item) => {
976 let trait_item_id = match *trait_item {
977 ProvidedMethod(ref m) => m.id,
978 RequiredMethod(ref m) => m.id,
979 TypeTraitItem(ref ty) => ty.id,
982 collector.insert(trait_item_id, NodeTraitItem(trait_item));
984 IIImplItem(_, ref impl_item) => {
985 let impl_item_id = match *impl_item {
986 MethodImplItem(ref m) => m.id,
987 TypeImplItem(ref ti) => ti.id,
990 collector.insert(impl_item_id, NodeImplItem(impl_item));
992 IIForeign(ref i) => {
993 collector.insert(i.id, NodeForeignItem(&**i));
996 *map.map.borrow_mut() = collector.map;
1000 pub trait NodePrinter {
1001 fn print_node(&mut self, node: &Node) -> IoResult<()>;
1004 impl<'a> NodePrinter for pprust::State<'a> {
1005 fn print_node(&mut self, node: &Node) -> IoResult<()> {
1007 NodeItem(a) => self.print_item(&*a),
1008 NodeForeignItem(a) => self.print_foreign_item(&*a),
1009 NodeTraitItem(a) => self.print_trait_method(&*a),
1010 NodeImplItem(a) => self.print_impl_item(&*a),
1011 NodeVariant(a) => self.print_variant(&*a),
1012 NodeExpr(a) => self.print_expr(&*a),
1013 NodeStmt(a) => self.print_stmt(&*a),
1014 NodePat(a) => self.print_pat(&*a),
1015 NodeBlock(a) => self.print_block(&*a),
1016 NodeLifetime(a) => self.print_lifetime(&*a),
1018 // these cases do not carry enough information in the
1019 // ast_map to reconstruct their full structure for pretty
1021 NodeLocal(_) => fail!("cannot print isolated Local"),
1022 NodeArg(_) => fail!("cannot print isolated Arg"),
1023 NodeStructCtor(_) => fail!("cannot print isolated StructCtor"),
1028 fn node_id_to_string(map: &Map, id: NodeId) -> String {
1029 match map.find(id) {
1030 Some(NodeItem(item)) => {
1031 let path_str = map.path_to_str_with_ident(id, item.ident);
1032 let item_str = match item.node {
1033 ItemStatic(..) => "static",
1034 ItemConst(..) => "const",
1036 ItemMod(..) => "mod",
1037 ItemForeignMod(..) => "foreign mod",
1039 ItemEnum(..) => "enum",
1040 ItemStruct(..) => "struct",
1041 ItemTrait(..) => "trait",
1042 ItemImpl(..) => "impl",
1043 ItemMac(..) => "macro"
1045 format!("{} {} (id={})", item_str, path_str, id)
1047 Some(NodeForeignItem(item)) => {
1048 let path_str = map.path_to_str_with_ident(id, item.ident);
1049 format!("foreign item {} (id={})", path_str, id)
1051 Some(NodeImplItem(ref ii)) => {
1053 MethodImplItem(ref m) => {
1055 MethDecl(ident, _, _, _, _, _, _, _) =>
1056 format!("method {} in {} (id={})",
1057 token::get_ident(ident),
1058 map.path_to_string(id), id),
1060 format!("method macro {} (id={})",
1061 pprust::mac_to_string(mac), id)
1064 TypeImplItem(ref t) => {
1065 format!("typedef {} in {} (id={})",
1066 token::get_ident(t.ident),
1067 map.path_to_string(id),
1072 Some(NodeTraitItem(ref tm)) => {
1074 RequiredMethod(_) | ProvidedMethod(_) => {
1075 let m = ast_util::trait_item_to_ty_method(&**tm);
1076 format!("method {} in {} (id={})",
1077 token::get_ident(m.ident),
1078 map.path_to_string(id),
1081 TypeTraitItem(ref t) => {
1082 format!("type item {} in {} (id={})",
1083 token::get_ident(t.ident),
1084 map.path_to_string(id),
1089 Some(NodeVariant(ref variant)) => {
1090 format!("variant {} in {} (id={})",
1091 token::get_ident(variant.node.name),
1092 map.path_to_string(id), id)
1094 Some(NodeExpr(ref expr)) => {
1095 format!("expr {} (id={})", pprust::expr_to_string(&**expr), id)
1097 Some(NodeStmt(ref stmt)) => {
1098 format!("stmt {} (id={})", pprust::stmt_to_string(&**stmt), id)
1100 Some(NodeArg(ref pat)) => {
1101 format!("arg {} (id={})", pprust::pat_to_string(&**pat), id)
1103 Some(NodeLocal(ref pat)) => {
1104 format!("local {} (id={})", pprust::pat_to_string(&**pat), id)
1106 Some(NodePat(ref pat)) => {
1107 format!("pat {} (id={})", pprust::pat_to_string(&**pat), id)
1109 Some(NodeBlock(ref block)) => {
1110 format!("block {} (id={})", pprust::block_to_string(&**block), id)
1112 Some(NodeStructCtor(_)) => {
1113 format!("struct_ctor {} (id={})", map.path_to_string(id), id)
1115 Some(NodeLifetime(ref l)) => {
1116 format!("lifetime {} (id={})",
1117 pprust::lifetime_to_string(&**l), id)
1120 format!("unknown node (id={})", id)