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 NodeItem(&'ast Item),
101 NodeForeignItem(&'ast ForeignItem),
102 NodeTraitItem(&'ast TraitItem),
103 NodeImplItem(&'ast ImplItem),
104 NodeVariant(&'ast Variant),
105 NodeExpr(&'ast Expr),
106 NodeStmt(&'ast Stmt),
108 NodeLocal(&'ast Pat),
110 NodeBlock(&'ast Block),
112 /// NodeStructCtor represents a tuple struct.
113 NodeStructCtor(&'ast StructDef),
115 NodeLifetime(&'ast Lifetime),
118 /// Represents an entry and its parent Node ID
119 /// The odd layout is to bring down the total size.
121 enum MapEntry<'ast> {
122 /// Placeholder for holes in the map.
125 /// All the node types, with a parent ID.
126 EntryItem(NodeId, &'ast Item),
127 EntryForeignItem(NodeId, &'ast ForeignItem),
128 EntryTraitItem(NodeId, &'ast TraitItem),
129 EntryImplItem(NodeId, &'ast ImplItem),
130 EntryVariant(NodeId, &'ast Variant),
131 EntryExpr(NodeId, &'ast Expr),
132 EntryStmt(NodeId, &'ast Stmt),
133 EntryArg(NodeId, &'ast Pat),
134 EntryLocal(NodeId, &'ast Pat),
135 EntryPat(NodeId, &'ast Pat),
136 EntryBlock(NodeId, &'ast Block),
137 EntryStructCtor(NodeId, &'ast StructDef),
138 EntryLifetime(NodeId, &'ast Lifetime),
140 /// Roots for node trees.
142 RootInlinedParent(&'ast InlinedParent)
145 impl<'ast> Clone for MapEntry<'ast> {
146 fn clone(&self) -> MapEntry<'ast> {
152 struct InlinedParent {
157 impl<'ast> MapEntry<'ast> {
158 fn from_node(p: NodeId, node: Node<'ast>) -> MapEntry<'ast> {
160 NodeItem(n) => EntryItem(p, n),
161 NodeForeignItem(n) => EntryForeignItem(p, n),
162 NodeTraitItem(n) => EntryTraitItem(p, n),
163 NodeImplItem(n) => EntryImplItem(p, n),
164 NodeVariant(n) => EntryVariant(p, n),
165 NodeExpr(n) => EntryExpr(p, n),
166 NodeStmt(n) => EntryStmt(p, n),
167 NodeArg(n) => EntryArg(p, n),
168 NodeLocal(n) => EntryLocal(p, n),
169 NodePat(n) => EntryPat(p, n),
170 NodeBlock(n) => EntryBlock(p, n),
171 NodeStructCtor(n) => EntryStructCtor(p, n),
172 NodeLifetime(n) => EntryLifetime(p, n)
176 fn parent(self) -> Option<NodeId> {
178 EntryItem(id, _) => id,
179 EntryForeignItem(id, _) => id,
180 EntryTraitItem(id, _) => id,
181 EntryImplItem(id, _) => id,
182 EntryVariant(id, _) => id,
183 EntryExpr(id, _) => id,
184 EntryStmt(id, _) => id,
185 EntryArg(id, _) => id,
186 EntryLocal(id, _) => id,
187 EntryPat(id, _) => id,
188 EntryBlock(id, _) => id,
189 EntryStructCtor(id, _) => id,
190 EntryLifetime(id, _) => id,
195 fn to_node(self) -> Option<Node<'ast>> {
197 EntryItem(_, n) => NodeItem(n),
198 EntryForeignItem(_, n) => NodeForeignItem(n),
199 EntryTraitItem(_, n) => NodeTraitItem(n),
200 EntryImplItem(_, n) => NodeImplItem(n),
201 EntryVariant(_, n) => NodeVariant(n),
202 EntryExpr(_, n) => NodeExpr(n),
203 EntryStmt(_, n) => NodeStmt(n),
204 EntryArg(_, n) => NodeArg(n),
205 EntryLocal(_, n) => NodeLocal(n),
206 EntryPat(_, n) => NodePat(n),
207 EntryBlock(_, n) => NodeBlock(n),
208 EntryStructCtor(_, n) => NodeStructCtor(n),
209 EntryLifetime(_, n) => NodeLifetime(n),
215 /// Stores a crate and any number of inlined items from other crates.
218 inlined_items: TypedArena<InlinedParent>
222 pub fn new(krate: Crate) -> Forest {
225 inlined_items: TypedArena::new()
229 pub fn krate<'ast>(&'ast self) -> &'ast Crate {
234 /// Represents a mapping from Node IDs to AST elements and their parent
236 pub struct Map<'ast> {
237 /// The backing storage for all the AST nodes.
238 forest: &'ast Forest,
240 /// NodeIds are sequential integers from 0, so we can be
241 /// super-compact by storing them in a vector. Not everything with
242 /// a NodeId is in the map, but empirically the occupancy is about
243 /// 75-80%, so there's not too much overhead (certainly less than
244 /// a hashmap, since they (at the time of writing) have a maximum
245 /// of 75% occupancy).
247 /// Also, indexing is pretty quick when you've got a vector and
248 /// plain old integers.
249 map: RefCell<Vec<MapEntry<'ast>>>
252 impl<'ast> Map<'ast> {
253 fn entry_count(&self) -> uint {
254 self.map.borrow().len()
257 fn find_entry(&self, id: NodeId) -> Option<MapEntry<'ast>> {
258 self.map.borrow().as_slice().get(id as uint).map(|e| *e)
261 pub fn krate(&self) -> &'ast Crate {
265 /// Retrieve the Node corresponding to `id`, failing if it cannot
267 pub fn get(&self, id: NodeId) -> Node<'ast> {
268 match self.find(id) {
270 None => fail!("couldn't find node id {} in the AST map", id)
274 /// Retrieve the Node corresponding to `id`, returning None if
276 pub fn find(&self, id: NodeId) -> Option<Node<'ast>> {
277 self.find_entry(id).and_then(|x| x.to_node())
280 /// Retrieve the parent NodeId for `id`, or `id` itself if no
281 /// parent is registered in this map.
282 pub fn get_parent(&self, id: NodeId) -> NodeId {
283 self.find_entry(id).and_then(|x| x.parent()).unwrap_or(id)
286 pub fn get_parent_did(&self, id: NodeId) -> DefId {
287 let parent = self.get_parent(id);
288 match self.find_entry(parent) {
289 Some(RootInlinedParent(&InlinedParent {ii: IITraitItem(did, _), ..})) => did,
290 Some(RootInlinedParent(&InlinedParent {ii: IIImplItem(did, _), ..})) => did,
291 _ => ast_util::local_def(parent)
295 pub fn get_foreign_abi(&self, id: NodeId) -> abi::Abi {
296 let parent = self.get_parent(id);
297 let abi = match self.find_entry(parent) {
298 Some(EntryItem(_, i)) => {
300 ItemForeignMod(ref nm) => Some(nm.abi),
304 /// Wrong but OK, because the only inlined foreign items are intrinsics.
305 Some(RootInlinedParent(_)) => Some(abi::RustIntrinsic),
310 None => fail!("expected foreign mod or inlined parent, found {}",
311 self.node_to_string(parent))
315 pub fn get_foreign_vis(&self, id: NodeId) -> Visibility {
316 let vis = self.expect_foreign_item(id).vis;
317 match self.find(self.get_parent(id)) {
318 Some(NodeItem(i)) => vis.inherit_from(i.vis),
323 pub fn expect_item(&self, id: NodeId) -> &'ast Item {
324 match self.find(id) {
325 Some(NodeItem(item)) => item,
326 _ => fail!("expected item, found {}", self.node_to_string(id))
330 pub fn expect_struct(&self, id: NodeId) -> &'ast StructDef {
331 match self.find(id) {
332 Some(NodeItem(i)) => {
334 ItemStruct(ref struct_def, _) => &**struct_def,
335 _ => fail!("struct ID bound to non-struct")
338 Some(NodeVariant(variant)) => {
339 match variant.node.kind {
340 StructVariantKind(ref struct_def) => &**struct_def,
341 _ => fail!("struct ID bound to enum variant that isn't struct-like"),
344 _ => fail!(format!("expected struct, found {}", self.node_to_string(id))),
348 pub fn expect_variant(&self, id: NodeId) -> &'ast Variant {
349 match self.find(id) {
350 Some(NodeVariant(variant)) => variant,
351 _ => fail!(format!("expected variant, found {}", self.node_to_string(id))),
355 pub fn expect_foreign_item(&self, id: NodeId) -> &'ast ForeignItem {
356 match self.find(id) {
357 Some(NodeForeignItem(item)) => item,
358 _ => fail!("expected foreign item, found {}", self.node_to_string(id))
362 pub fn expect_expr(&self, id: NodeId) -> &'ast Expr {
363 match self.find(id) {
364 Some(NodeExpr(expr)) => expr,
365 _ => fail!("expected expr, found {}", self.node_to_string(id))
369 /// returns the name associated with the given NodeId's AST
370 pub fn get_path_elem(&self, id: NodeId) -> PathElem {
371 let node = self.get(id);
375 ItemMod(_) | ItemForeignMod(_) => {
376 PathMod(item.ident.name)
378 _ => PathName(item.ident.name)
381 NodeForeignItem(i) => PathName(i.ident.name),
382 NodeImplItem(ii) => {
384 MethodImplItem(ref m) => {
386 MethDecl(ident, _, _, _, _, _, _, _) => {
390 fail!("no path elem for {:?}", node)
394 TypeImplItem(ref t) => PathName(t.ident.name),
397 NodeTraitItem(tm) => match *tm {
398 RequiredMethod(ref m) => PathName(m.ident.name),
399 ProvidedMethod(ref m) => {
401 MethDecl(ident, _, _, _, _, _, _, _) => {
404 MethMac(_) => fail!("no path elem for {:?}", node),
407 TypeTraitItem(ref m) => PathName(m.ident.name),
409 NodeVariant(v) => PathName(v.node.name.name),
410 _ => fail!("no path elem for {:?}", node)
414 pub fn with_path<T>(&self, id: NodeId, f: |PathElems| -> T) -> T {
415 self.with_path_next(id, None, f)
418 pub fn path_to_string(&self, id: NodeId) -> String {
419 self.with_path(id, |path| path_to_string(path))
422 fn path_to_str_with_ident(&self, id: NodeId, i: Ident) -> String {
423 self.with_path(id, |path| {
424 path_to_string(path.chain(Some(PathName(i.name)).into_iter()))
428 fn with_path_next<T>(&self, id: NodeId, next: LinkedPath, f: |PathElems| -> T) -> T {
429 let parent = self.get_parent(id);
430 let parent = match self.find_entry(id) {
431 Some(EntryForeignItem(..)) | Some(EntryVariant(..)) => {
432 // Anonymous extern items, enum variants and struct ctors
433 // go in the parent scope.
434 self.get_parent(parent)
436 // But tuple struct ctors don't have names, so use the path of its
437 // parent, the struct item. Similarly with closure expressions.
438 Some(EntryStructCtor(..)) | Some(EntryExpr(..)) => {
439 return self.with_path_next(parent, next, f);
444 match self.find_entry(id) {
445 Some(RootInlinedParent(data)) => {
446 f(Values(data.path.iter()).chain(next))
448 _ => f(Values([].iter()).chain(next))
451 self.with_path_next(parent, Some(&LinkedPathNode {
452 node: self.get_path_elem(id),
458 /// Given a node ID and a closure, apply the closure to the array
459 /// of attributes associated with the AST corresponding to the Node ID
460 pub fn with_attrs<T>(&self, id: NodeId, f: |Option<&[Attribute]>| -> T) -> T {
461 let attrs = match self.get(id) {
462 NodeItem(i) => Some(i.attrs.as_slice()),
463 NodeForeignItem(fi) => Some(fi.attrs.as_slice()),
464 NodeTraitItem(ref tm) => match **tm {
465 RequiredMethod(ref type_m) => Some(type_m.attrs.as_slice()),
466 ProvidedMethod(ref m) => Some(m.attrs.as_slice()),
467 TypeTraitItem(ref typ) => Some(typ.attrs.as_slice()),
469 NodeImplItem(ref ii) => {
471 MethodImplItem(ref m) => Some(m.attrs.as_slice()),
472 TypeImplItem(ref t) => Some(t.attrs.as_slice()),
475 NodeVariant(ref v) => Some(v.node.attrs.as_slice()),
476 // unit/tuple structs take the attributes straight from
477 // the struct definition.
478 // FIXME(eddyb) make this work again (requires access to the map).
479 NodeStructCtor(_) => {
480 return self.with_attrs(self.get_parent(id), f);
487 /// Returns an iterator that yields the node id's with paths that
488 /// match `parts`. (Requires `parts` is non-empty.)
490 /// For example, if given `parts` equal to `["bar", "quux"]`, then
491 /// the iterator will produce node id's for items with paths
492 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
493 /// any other such items it can find in the map.
494 pub fn nodes_matching_suffix<'a, S:Str>(&'a self, parts: &'a [S])
495 -> NodesMatchingSuffix<'a, 'ast, S> {
496 NodesMatchingSuffix {
498 item_name: parts.last().unwrap(),
499 in_which: parts.slice_to(parts.len() - 1),
504 pub fn opt_span(&self, id: NodeId) -> Option<Span> {
505 let sp = match self.find(id) {
506 Some(NodeItem(item)) => item.span,
507 Some(NodeForeignItem(foreign_item)) => foreign_item.span,
508 Some(NodeTraitItem(trait_method)) => {
509 match *trait_method {
510 RequiredMethod(ref type_method) => type_method.span,
511 ProvidedMethod(ref method) => method.span,
512 TypeTraitItem(ref typedef) => typedef.span,
515 Some(NodeImplItem(ref impl_item)) => {
517 MethodImplItem(ref method) => method.span,
518 TypeImplItem(ref typedef) => typedef.span,
521 Some(NodeVariant(variant)) => variant.span,
522 Some(NodeExpr(expr)) => expr.span,
523 Some(NodeStmt(stmt)) => stmt.span,
524 Some(NodeArg(pat)) | Some(NodeLocal(pat)) => pat.span,
525 Some(NodePat(pat)) => pat.span,
526 Some(NodeBlock(block)) => block.span,
527 Some(NodeStructCtor(_)) => self.expect_item(self.get_parent(id)).span,
533 pub fn span(&self, id: NodeId) -> Span {
535 .unwrap_or_else(|| fail!("AstMap.span: could not find span for id {}", id))
538 pub fn node_to_string(&self, id: NodeId) -> String {
539 node_id_to_string(self, id)
543 pub struct NodesMatchingSuffix<'a, 'ast:'a, S:'a> {
550 impl<'a, 'ast, S:Str> NodesMatchingSuffix<'a, 'ast, S> {
551 /// Returns true only if some suffix of the module path for parent
552 /// matches `self.in_which`.
554 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
555 /// returns true if parent's path ends with the suffix
556 /// `x_0::x_1::...::x_k`.
557 fn suffix_matches(&self, parent: NodeId) -> bool {
558 let mut cursor = parent;
559 for part in self.in_which.iter().rev() {
560 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
561 None => return false,
562 Some((node_id, name)) => (node_id, name),
564 if part.as_slice() != mod_name.as_str() {
567 cursor = self.map.get_parent(mod_id);
571 // Finds the first mod in parent chain for `id`, along with
574 // If `id` itself is a mod named `m` with parent `p`, then
575 // returns `Some(id, m, p)`. If `id` has no mod in its parent
576 // chain, then returns `None`.
577 fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
581 Some(NodeItem(item)) if item_is_mod(&*item) =>
582 return Some((id, item.ident.name)),
585 let parent = map.get_parent(id);
586 if parent == id { return None }
590 fn item_is_mod(item: &Item) -> bool {
599 // We are looking at some node `n` with a given name and parent
600 // id; do their names match what I am seeking?
601 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
602 name.as_str() == self.item_name.as_slice() &&
603 self.suffix_matches(parent_of_n)
607 impl<'a, 'ast, S:Str> Iterator<NodeId> for NodesMatchingSuffix<'a, 'ast, S> {
608 fn next(&mut self) -> Option<NodeId> {
611 if idx as uint >= self.map.entry_count() {
615 let (p, name) = match self.map.find_entry(idx) {
616 Some(EntryItem(p, n)) => (p, n.name()),
617 Some(EntryForeignItem(p, n))=> (p, n.name()),
618 Some(EntryTraitItem(p, n)) => (p, n.name()),
619 Some(EntryImplItem(p, n)) => (p, n.name()),
620 Some(EntryVariant(p, n)) => (p, n.name()),
623 if self.matches_names(p, name) {
631 fn name(&self) -> Name;
634 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
636 impl Named for Item { fn name(&self) -> Name { self.ident.name } }
637 impl Named for ForeignItem { fn name(&self) -> Name { self.ident.name } }
638 impl Named for Variant_ { fn name(&self) -> Name { self.name.name } }
639 impl Named for TraitItem {
640 fn name(&self) -> Name {
642 RequiredMethod(ref tm) => tm.ident.name,
643 ProvidedMethod(ref m) => m.name(),
644 TypeTraitItem(ref at) => at.ident.name,
648 impl Named for ImplItem {
649 fn name(&self) -> Name {
651 MethodImplItem(ref m) => m.name(),
652 TypeImplItem(ref td) => td.ident.name,
656 impl Named for Method {
657 fn name(&self) -> Name {
659 MethDecl(i, _, _, _, _, _, _, _) => i.name,
660 MethMac(_) => fail!("encountered unexpanded method macro."),
666 fn new_id(&self, id: NodeId) -> NodeId {
669 fn new_def_id(&self, def_id: DefId) -> DefId {
672 fn new_span(&self, span: Span) -> Span {
677 /// A Folder that updates IDs and Span's according to fold_ops.
678 struct IdAndSpanUpdater<F> {
682 impl<F: FoldOps> Folder for IdAndSpanUpdater<F> {
683 fn new_id(&mut self, id: NodeId) -> NodeId {
684 self.fold_ops.new_id(id)
687 fn new_span(&mut self, span: Span) -> Span {
688 self.fold_ops.new_span(span)
692 /// A Visitor that walks over an AST and collects Node's into an AST Map.
693 struct NodeCollector<'ast> {
694 map: Vec<MapEntry<'ast>>,
695 /// The node in which we are currently mapping (an item or a method).
699 impl<'ast> NodeCollector<'ast> {
700 fn insert_entry(&mut self, id: NodeId, entry: MapEntry<'ast>) {
701 self.map.grow_set(id as uint, &NotPresent, entry);
702 debug!("ast_map: {} => {}", id, entry);
705 fn insert(&mut self, id: NodeId, node: Node<'ast>) {
706 let entry = MapEntry::from_node(self.parent, node);
707 self.insert_entry(id, entry);
710 fn visit_fn_decl(&mut self, decl: &'ast FnDecl) {
711 for a in decl.inputs.iter() {
712 self.insert(a.id, NodeArg(&*a.pat));
717 impl<'ast> Visitor<'ast> for NodeCollector<'ast> {
718 fn visit_item(&mut self, i: &'ast Item) {
719 self.insert(i.id, NodeItem(i));
720 let parent = self.parent;
723 ItemImpl(_, _, _, ref impl_items) => {
724 for impl_item in impl_items.iter() {
726 MethodImplItem(ref m) => {
727 self.insert(m.id, NodeImplItem(impl_item));
729 TypeImplItem(ref t) => {
730 self.insert(t.id, NodeImplItem(impl_item));
735 ItemEnum(ref enum_definition, _) => {
736 for v in enum_definition.variants.iter() {
737 self.insert(v.node.id, NodeVariant(&**v));
740 ItemForeignMod(ref nm) => {
741 for nitem in nm.items.iter() {
742 self.insert(nitem.id, NodeForeignItem(&**nitem));
745 ItemStruct(ref struct_def, _) => {
746 // If this is a tuple-like struct, register the constructor.
747 match struct_def.ctor_id {
749 self.insert(ctor_id, NodeStructCtor(&**struct_def));
754 ItemTrait(_, _, ref bounds, ref trait_items) => {
755 for b in bounds.iter() {
757 TraitTyParamBound(ref t) => {
758 self.insert(t.ref_id, NodeItem(i));
764 for tm in trait_items.iter() {
766 RequiredMethod(ref m) => {
767 self.insert(m.id, NodeTraitItem(tm));
769 ProvidedMethod(ref m) => {
770 self.insert(m.id, NodeTraitItem(tm));
772 TypeTraitItem(ref typ) => {
773 self.insert(typ.id, NodeTraitItem(tm));
780 visit::walk_item(self, i);
781 self.parent = parent;
784 fn visit_pat(&mut self, pat: &'ast Pat) {
785 self.insert(pat.id, match pat.node {
786 // Note: this is at least *potentially* a pattern...
787 PatIdent(..) => NodeLocal(pat),
790 visit::walk_pat(self, pat);
793 fn visit_expr(&mut self, expr: &'ast Expr) {
794 self.insert(expr.id, NodeExpr(expr));
795 visit::walk_expr(self, expr);
798 fn visit_stmt(&mut self, stmt: &'ast Stmt) {
799 self.insert(ast_util::stmt_id(stmt), NodeStmt(stmt));
800 visit::walk_stmt(self, stmt);
803 fn visit_ty_method(&mut self, m: &'ast TypeMethod) {
804 let parent = self.parent;
806 self.visit_fn_decl(&*m.decl);
807 visit::walk_ty_method(self, m);
808 self.parent = parent;
811 fn visit_fn(&mut self, fk: visit::FnKind<'ast>, fd: &'ast FnDecl,
812 b: &'ast Block, s: Span, id: NodeId) {
814 visit::FkMethod(..) => {
815 let parent = self.parent;
817 self.visit_fn_decl(fd);
818 visit::walk_fn(self, fk, fd, b, s);
819 self.parent = parent;
822 self.visit_fn_decl(fd);
823 visit::walk_fn(self, fk, fd, b, s);
828 fn visit_ty(&mut self, ty: &'ast Ty) {
830 TyClosure(ref fd) | TyProc(ref fd) => {
831 self.visit_fn_decl(&*fd.decl);
833 TyBareFn(ref fd) => {
834 self.visit_fn_decl(&*fd.decl);
836 TyUnboxedFn(ref fd) => {
837 self.visit_fn_decl(&*fd.decl);
841 visit::walk_ty(self, ty);
844 fn visit_block(&mut self, block: &'ast Block) {
845 self.insert(block.id, NodeBlock(block));
846 visit::walk_block(self, block);
849 fn visit_lifetime_ref(&mut self, lifetime: &'ast Lifetime) {
850 self.insert(lifetime.id, NodeLifetime(lifetime));
853 fn visit_lifetime_decl(&mut self, def: &'ast LifetimeDef) {
854 self.visit_lifetime_ref(&def.lifetime);
858 pub fn map_crate<'ast, F: FoldOps>(forest: &'ast mut Forest, fold_ops: F) -> Map<'ast> {
859 // Replace the crate with an empty one to take it out.
860 let krate = mem::replace(&mut forest.krate, Crate {
868 exported_macros: vec![],
871 forest.krate = IdAndSpanUpdater { fold_ops: fold_ops }.fold_crate(krate);
873 let mut collector = NodeCollector {
875 parent: CRATE_NODE_ID
877 collector.insert_entry(CRATE_NODE_ID, RootCrate);
878 visit::walk_crate(&mut collector, &forest.krate);
879 let map = collector.map;
881 if log_enabled!(::log::DEBUG) {
882 // This only makes sense for ordered stores; note the
883 // enumerate to count the number of entries.
884 let (entries_less_1, _) = map.iter().filter(|&x| {
889 }).enumerate().last().expect("AST map was empty after folding?");
891 let entries = entries_less_1 + 1;
892 let vector_length = map.len();
893 debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
894 entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
899 map: RefCell::new(map)
903 /// Used for items loaded from external crate that are being inlined into this
904 /// crate. The `path` should be the path to the item but should not include
906 pub fn map_decoded_item<'ast, F: FoldOps>(map: &Map<'ast>,
910 -> &'ast InlinedItem {
911 let mut fld = IdAndSpanUpdater { fold_ops: fold_ops };
913 IIItem(i) => IIItem(fld.fold_item(i).expect_one("expected one item")),
914 IITraitItem(d, ti) => match ti {
915 ProvidedMethod(m) => {
916 IITraitItem(fld.fold_ops.new_def_id(d),
917 ProvidedMethod(fld.fold_method(m)
918 .expect_one("expected one method")))
920 RequiredMethod(ty_m) => {
921 IITraitItem(fld.fold_ops.new_def_id(d),
922 RequiredMethod(fld.fold_type_method(ty_m)))
924 TypeTraitItem(at) => {
926 fld.fold_ops.new_def_id(d),
927 TypeTraitItem(P(fld.fold_associated_type((*at).clone()))))
930 IIImplItem(d, m) => match m {
931 MethodImplItem(m) => {
932 IIImplItem(fld.fold_ops.new_def_id(d),
933 MethodImplItem(fld.fold_method(m)
934 .expect_one("expected one method")))
937 IIImplItem(fld.fold_ops.new_def_id(d),
938 TypeImplItem(P(fld.fold_typedef((*t).clone()))))
941 IIForeign(i) => IIForeign(fld.fold_foreign_item(i))
944 let ii_parent = map.forest.inlined_items.alloc(InlinedParent {
949 let mut collector = NodeCollector {
950 map: mem::replace(&mut *map.map.borrow_mut(), vec![]),
951 parent: fld.new_id(DUMMY_NODE_ID)
953 let ii_parent_id = collector.parent;
954 collector.insert_entry(ii_parent_id, RootInlinedParent(ii_parent));
955 visit::walk_inlined_item(&mut collector, &ii_parent.ii);
957 // Methods get added to the AST map when their impl is visited. Since we
958 // don't decode and instantiate the impl, but just the method, we have to
959 // add it to the table now. Likewise with foreign items.
962 IITraitItem(_, ref trait_item) => {
963 let trait_item_id = match *trait_item {
964 ProvidedMethod(ref m) => m.id,
965 RequiredMethod(ref m) => m.id,
966 TypeTraitItem(ref ty) => ty.id,
969 collector.insert(trait_item_id, NodeTraitItem(trait_item));
971 IIImplItem(_, ref impl_item) => {
972 let impl_item_id = match *impl_item {
973 MethodImplItem(ref m) => m.id,
974 TypeImplItem(ref ti) => ti.id,
977 collector.insert(impl_item_id, NodeImplItem(impl_item));
979 IIForeign(ref i) => {
980 collector.insert(i.id, NodeForeignItem(&**i));
983 *map.map.borrow_mut() = collector.map;
987 pub trait NodePrinter {
988 fn print_node(&mut self, node: &Node) -> IoResult<()>;
991 impl<'a> NodePrinter for pprust::State<'a> {
992 fn print_node(&mut self, node: &Node) -> IoResult<()> {
994 NodeItem(a) => self.print_item(&*a),
995 NodeForeignItem(a) => self.print_foreign_item(&*a),
996 NodeTraitItem(a) => self.print_trait_method(&*a),
997 NodeImplItem(a) => self.print_impl_item(&*a),
998 NodeVariant(a) => self.print_variant(&*a),
999 NodeExpr(a) => self.print_expr(&*a),
1000 NodeStmt(a) => self.print_stmt(&*a),
1001 NodePat(a) => self.print_pat(&*a),
1002 NodeBlock(a) => self.print_block(&*a),
1003 NodeLifetime(a) => self.print_lifetime(&*a),
1005 // these cases do not carry enough information in the
1006 // ast_map to reconstruct their full structure for pretty
1008 NodeLocal(_) => fail!("cannot print isolated Local"),
1009 NodeArg(_) => fail!("cannot print isolated Arg"),
1010 NodeStructCtor(_) => fail!("cannot print isolated StructCtor"),
1015 fn node_id_to_string(map: &Map, id: NodeId) -> String {
1016 match map.find(id) {
1017 Some(NodeItem(item)) => {
1018 let path_str = map.path_to_str_with_ident(id, item.ident);
1019 let item_str = match item.node {
1020 ItemStatic(..) => "static",
1022 ItemMod(..) => "mod",
1023 ItemForeignMod(..) => "foreign mod",
1025 ItemEnum(..) => "enum",
1026 ItemStruct(..) => "struct",
1027 ItemTrait(..) => "trait",
1028 ItemImpl(..) => "impl",
1029 ItemMac(..) => "macro"
1031 format!("{} {} (id={})", item_str, path_str, id)
1033 Some(NodeForeignItem(item)) => {
1034 let path_str = map.path_to_str_with_ident(id, item.ident);
1035 format!("foreign item {} (id={})", path_str, id)
1037 Some(NodeImplItem(ref ii)) => {
1039 MethodImplItem(ref m) => {
1041 MethDecl(ident, _, _, _, _, _, _, _) =>
1042 format!("method {} in {} (id={})",
1043 token::get_ident(ident),
1044 map.path_to_string(id), id),
1046 format!("method macro {} (id={})",
1047 pprust::mac_to_string(mac), id)
1050 TypeImplItem(ref t) => {
1051 format!("typedef {} in {} (id={})",
1052 token::get_ident(t.ident),
1053 map.path_to_string(id),
1058 Some(NodeTraitItem(ref tm)) => {
1060 RequiredMethod(_) | ProvidedMethod(_) => {
1061 let m = ast_util::trait_item_to_ty_method(&**tm);
1062 format!("method {} in {} (id={})",
1063 token::get_ident(m.ident),
1064 map.path_to_string(id),
1067 TypeTraitItem(ref t) => {
1068 format!("type item {} in {} (id={})",
1069 token::get_ident(t.ident),
1070 map.path_to_string(id),
1075 Some(NodeVariant(ref variant)) => {
1076 format!("variant {} in {} (id={})",
1077 token::get_ident(variant.node.name),
1078 map.path_to_string(id), id)
1080 Some(NodeExpr(ref expr)) => {
1081 format!("expr {} (id={})", pprust::expr_to_string(&**expr), id)
1083 Some(NodeStmt(ref stmt)) => {
1084 format!("stmt {} (id={})", pprust::stmt_to_string(&**stmt), id)
1086 Some(NodeArg(ref pat)) => {
1087 format!("arg {} (id={})", pprust::pat_to_string(&**pat), id)
1089 Some(NodeLocal(ref pat)) => {
1090 format!("local {} (id={})", pprust::pat_to_string(&**pat), id)
1092 Some(NodePat(ref pat)) => {
1093 format!("pat {} (id={})", pprust::pat_to_string(&**pat), id)
1095 Some(NodeBlock(ref block)) => {
1096 format!("block {} (id={})", pprust::block_to_string(&**block), id)
1098 Some(NodeStructCtor(_)) => {
1099 format!("struct_ctor {} (id={})", map.path_to_string(id), id)
1101 Some(NodeLifetime(ref l)) => {
1102 format!("lifetime {} (id={})",
1103 pprust::lifetime_to_string(&**l), id)
1106 format!("unknown node (id={})", id)