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 ast_util::PostExpansionMethod;
15 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)
396 NodeTraitItem(tm) => match *tm {
397 RequiredMethod(ref m) => PathName(m.ident.name),
398 ProvidedMethod(ref m) => match m.node {
399 MethDecl(ident, _, _, _, _, _, _, _) => {
402 MethMac(_) => fail!("no path elem for {:?}", node),
405 NodeVariant(v) => PathName(v.node.name.name),
406 _ => fail!("no path elem for {:?}", node)
410 pub fn with_path<T>(&self, id: NodeId, f: |PathElems| -> T) -> T {
411 self.with_path_next(id, None, f)
414 pub fn path_to_string(&self, id: NodeId) -> String {
415 self.with_path(id, |path| path_to_string(path))
418 fn path_to_str_with_ident(&self, id: NodeId, i: Ident) -> String {
419 self.with_path(id, |path| {
420 path_to_string(path.chain(Some(PathName(i.name)).move_iter()))
424 fn with_path_next<T>(&self, id: NodeId, next: LinkedPath, f: |PathElems| -> T) -> T {
425 let parent = self.get_parent(id);
426 let parent = match self.find_entry(id) {
427 Some(EntryForeignItem(..)) | Some(EntryVariant(..)) => {
428 // Anonymous extern items, enum variants and struct ctors
429 // go in the parent scope.
430 self.get_parent(parent)
432 // But tuple struct ctors don't have names, so use the path of its
433 // parent, the struct item. Similarly with closure expressions.
434 Some(EntryStructCtor(..)) | Some(EntryExpr(..)) => {
435 return self.with_path_next(parent, next, f);
440 match self.find_entry(id) {
441 Some(RootInlinedParent(data)) => {
442 f(Values(data.path.iter()).chain(next))
444 _ => f(Values([].iter()).chain(next))
447 self.with_path_next(parent, Some(&LinkedPathNode {
448 node: self.get_path_elem(id),
454 /// Given a node ID and a closure, apply the closure to the array
455 /// of attributes associated with the AST corresponding to the Node ID
456 pub fn with_attrs<T>(&self, id: NodeId, f: |Option<&[Attribute]>| -> T) -> T {
457 let attrs = match self.get(id) {
458 NodeItem(i) => Some(i.attrs.as_slice()),
459 NodeForeignItem(fi) => Some(fi.attrs.as_slice()),
460 NodeTraitItem(ref tm) => match **tm {
461 RequiredMethod(ref type_m) => Some(type_m.attrs.as_slice()),
462 ProvidedMethod(ref m) => Some(m.attrs.as_slice())
464 NodeImplItem(ref ii) => {
466 MethodImplItem(ref m) => Some(m.attrs.as_slice()),
469 NodeVariant(ref v) => Some(v.node.attrs.as_slice()),
470 // unit/tuple structs take the attributes straight from
471 // the struct definition.
472 // FIXME(eddyb) make this work again (requires access to the map).
473 NodeStructCtor(_) => {
474 return self.with_attrs(self.get_parent(id), f);
481 /// Returns an iterator that yields the node id's with paths that
482 /// match `parts`. (Requires `parts` is non-empty.)
484 /// For example, if given `parts` equal to `["bar", "quux"]`, then
485 /// the iterator will produce node id's for items with paths
486 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
487 /// any other such items it can find in the map.
488 pub fn nodes_matching_suffix<'a, S:Str>(&'a self, parts: &'a [S])
489 -> NodesMatchingSuffix<'a, 'ast, S> {
490 NodesMatchingSuffix {
492 item_name: parts.last().unwrap(),
493 in_which: parts.slice_to(parts.len() - 1),
498 pub fn opt_span(&self, id: NodeId) -> Option<Span> {
499 let sp = match self.find(id) {
500 Some(NodeItem(item)) => item.span,
501 Some(NodeForeignItem(foreign_item)) => foreign_item.span,
502 Some(NodeTraitItem(trait_method)) => {
503 match *trait_method {
504 RequiredMethod(ref type_method) => type_method.span,
505 ProvidedMethod(ref method) => method.span,
508 Some(NodeImplItem(ref impl_item)) => {
510 MethodImplItem(ref method) => method.span,
513 Some(NodeVariant(variant)) => variant.span,
514 Some(NodeExpr(expr)) => expr.span,
515 Some(NodeStmt(stmt)) => stmt.span,
516 Some(NodeArg(pat)) | Some(NodeLocal(pat)) => pat.span,
517 Some(NodePat(pat)) => pat.span,
518 Some(NodeBlock(block)) => block.span,
519 Some(NodeStructCtor(_)) => self.expect_item(self.get_parent(id)).span,
525 pub fn span(&self, id: NodeId) -> Span {
527 .unwrap_or_else(|| fail!("AstMap.span: could not find span for id {}", id))
530 pub fn node_to_string(&self, id: NodeId) -> String {
531 node_id_to_string(self, id)
535 pub struct NodesMatchingSuffix<'a, 'ast:'a, S:'a> {
542 impl<'a, 'ast, S:Str> NodesMatchingSuffix<'a, 'ast, S> {
543 /// Returns true only if some suffix of the module path for parent
544 /// matches `self.in_which`.
546 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
547 /// returns true if parent's path ends with the suffix
548 /// `x_0::x_1::...::x_k`.
549 fn suffix_matches(&self, parent: NodeId) -> bool {
550 let mut cursor = parent;
551 for part in self.in_which.iter().rev() {
552 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
553 None => return false,
554 Some((node_id, name)) => (node_id, name),
556 if part.as_slice() != mod_name.as_str() {
559 cursor = self.map.get_parent(mod_id);
563 // Finds the first mod in parent chain for `id`, along with
566 // If `id` itself is a mod named `m` with parent `p`, then
567 // returns `Some(id, m, p)`. If `id` has no mod in its parent
568 // chain, then returns `None`.
569 fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
573 Some(NodeItem(item)) if item_is_mod(&*item) =>
574 return Some((id, item.ident.name)),
577 let parent = map.get_parent(id);
578 if parent == id { return None }
582 fn item_is_mod(item: &Item) -> bool {
591 // We are looking at some node `n` with a given name and parent
592 // id; do their names match what I am seeking?
593 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
594 name.as_str() == self.item_name.as_slice() &&
595 self.suffix_matches(parent_of_n)
599 impl<'a, 'ast, S:Str> Iterator<NodeId> for NodesMatchingSuffix<'a, 'ast, S> {
600 fn next(&mut self) -> Option<NodeId> {
603 if idx as uint >= self.map.entry_count() {
607 let (p, name) = match self.map.find_entry(idx) {
608 Some(EntryItem(p, n)) => (p, n.name()),
609 Some(EntryForeignItem(p, n))=> (p, n.name()),
610 Some(EntryTraitItem(p, n)) => (p, n.name()),
611 Some(EntryImplItem(p, n)) => (p, n.name()),
612 Some(EntryVariant(p, n)) => (p, n.name()),
615 if self.matches_names(p, name) {
623 fn name(&self) -> Name;
626 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
628 impl Named for Item { fn name(&self) -> Name { self.ident.name } }
629 impl Named for ForeignItem { fn name(&self) -> Name { self.ident.name } }
630 impl Named for Variant_ { fn name(&self) -> Name { self.name.name } }
631 impl Named for TraitItem {
632 fn name(&self) -> Name {
634 RequiredMethod(ref tm) => tm.ident.name,
635 ProvidedMethod(ref m) => m.name(),
639 impl Named for ImplItem {
640 fn name(&self) -> Name {
642 MethodImplItem(ref m) => m.name(),
646 impl Named for Method {
647 fn name(&self) -> Name {
649 MethDecl(i, _, _, _, _, _, _, _) => i.name,
650 MethMac(_) => fail!("encountered unexpanded method macro."),
656 fn new_id(&self, id: NodeId) -> NodeId {
659 fn new_def_id(&self, def_id: DefId) -> DefId {
662 fn new_span(&self, span: Span) -> Span {
667 /// A Folder that updates IDs and Span's according to fold_ops.
668 struct IdAndSpanUpdater<F> {
672 impl<F: FoldOps> Folder for IdAndSpanUpdater<F> {
673 fn new_id(&mut self, id: NodeId) -> NodeId {
674 self.fold_ops.new_id(id)
677 fn new_span(&mut self, span: Span) -> Span {
678 self.fold_ops.new_span(span)
682 /// A Visitor that walks over an AST and collects Node's into an AST Map.
683 struct NodeCollector<'ast> {
684 map: Vec<MapEntry<'ast>>,
685 /// The node in which we are currently mapping (an item or a method).
689 impl<'ast> NodeCollector<'ast> {
690 fn insert_entry(&mut self, id: NodeId, entry: MapEntry<'ast>) {
691 self.map.grow_set(id as uint, &NotPresent, entry);
692 debug!("ast_map: {} => {}", id, entry);
695 fn insert(&mut self, id: NodeId, node: Node<'ast>) {
696 let entry = MapEntry::from_node(self.parent, node);
697 self.insert_entry(id, entry);
700 fn visit_fn_decl(&mut self, decl: &'ast FnDecl) {
701 for a in decl.inputs.iter() {
702 self.insert(a.id, NodeArg(&*a.pat));
707 impl<'ast> Visitor<'ast> for NodeCollector<'ast> {
708 fn visit_item(&mut self, i: &'ast Item) {
709 self.insert(i.id, NodeItem(i));
710 let parent = self.parent;
713 ItemImpl(_, _, _, ref impl_items) => {
714 for impl_item in impl_items.iter() {
715 let id = match *impl_item {
716 MethodImplItem(ref m) => m.id
718 self.insert(id, NodeImplItem(impl_item));
721 ItemEnum(ref enum_definition, _) => {
722 for v in enum_definition.variants.iter() {
723 self.insert(v.node.id, NodeVariant(&**v));
726 ItemForeignMod(ref nm) => {
727 for nitem in nm.items.iter() {
728 self.insert(nitem.id, NodeForeignItem(&**nitem));
731 ItemStruct(ref struct_def, _) => {
732 // If this is a tuple-like struct, register the constructor.
733 match struct_def.ctor_id {
735 self.insert(ctor_id, NodeStructCtor(&**struct_def));
740 ItemTrait(_, _, _, ref methods) => {
741 for tm in methods.iter() {
743 RequiredMethod(ref m) => m.id,
744 ProvidedMethod(ref m) => m.id
746 self.insert(id, NodeTraitItem(tm));
751 visit::walk_item(self, i);
752 self.parent = parent;
755 fn visit_pat(&mut self, pat: &'ast Pat) {
756 self.insert(pat.id, match pat.node {
757 // Note: this is at least *potentially* a pattern...
758 PatIdent(..) => NodeLocal(pat),
761 visit::walk_pat(self, pat);
764 fn visit_expr(&mut self, expr: &'ast Expr) {
765 self.insert(expr.id, NodeExpr(expr));
766 visit::walk_expr(self, expr);
769 fn visit_stmt(&mut self, stmt: &'ast Stmt) {
770 self.insert(ast_util::stmt_id(stmt), NodeStmt(stmt));
771 visit::walk_stmt(self, stmt);
774 fn visit_ty_method(&mut self, m: &'ast TypeMethod) {
775 let parent = self.parent;
777 self.visit_fn_decl(&*m.decl);
778 visit::walk_ty_method(self, m);
779 self.parent = parent;
782 fn visit_fn(&mut self, fk: visit::FnKind<'ast>, fd: &'ast FnDecl,
783 b: &'ast Block, s: Span, id: NodeId) {
785 visit::FkMethod(..) => {
786 let parent = self.parent;
788 self.visit_fn_decl(fd);
789 visit::walk_fn(self, fk, fd, b, s);
790 self.parent = parent;
793 self.visit_fn_decl(fd);
794 visit::walk_fn(self, fk, fd, b, s);
799 fn visit_ty(&mut self, ty: &'ast Ty) {
801 TyClosure(ref fd) | TyProc(ref fd) => {
802 self.visit_fn_decl(&*fd.decl);
804 TyBareFn(ref fd) => {
805 self.visit_fn_decl(&*fd.decl);
807 TyUnboxedFn(ref fd) => {
808 self.visit_fn_decl(&*fd.decl);
812 visit::walk_ty(self, ty);
815 fn visit_block(&mut self, block: &'ast Block) {
816 self.insert(block.id, NodeBlock(block));
817 visit::walk_block(self, block);
820 fn visit_lifetime_ref(&mut self, lifetime: &'ast Lifetime) {
821 self.insert(lifetime.id, NodeLifetime(lifetime));
824 fn visit_lifetime_decl(&mut self, def: &'ast LifetimeDef) {
825 self.visit_lifetime_ref(&def.lifetime);
829 pub fn map_crate<'ast, F: FoldOps>(forest: &'ast mut Forest, fold_ops: F) -> Map<'ast> {
830 // Replace the crate with an empty one to take it out.
831 let krate = mem::replace(&mut forest.krate, Crate {
839 exported_macros: vec![],
842 forest.krate = IdAndSpanUpdater { fold_ops: fold_ops }.fold_crate(krate);
844 let mut collector = NodeCollector {
846 parent: CRATE_NODE_ID
848 collector.insert_entry(CRATE_NODE_ID, RootCrate);
849 visit::walk_crate(&mut collector, &forest.krate);
850 let map = collector.map;
852 if log_enabled!(::log::DEBUG) {
853 // This only makes sense for ordered stores; note the
854 // enumerate to count the number of entries.
855 let (entries_less_1, _) = map.iter().filter(|&x| {
860 }).enumerate().last().expect("AST map was empty after folding?");
862 let entries = entries_less_1 + 1;
863 let vector_length = map.len();
864 debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
865 entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
870 map: RefCell::new(map)
874 /// Used for items loaded from external crate that are being inlined into this
875 /// crate. The `path` should be the path to the item but should not include
877 pub fn map_decoded_item<'ast, F: FoldOps>(map: &Map<'ast>,
881 -> &'ast InlinedItem {
882 let mut fld = IdAndSpanUpdater { fold_ops: fold_ops };
884 IIItem(i) => IIItem(fld.fold_item(i).expect_one("expected one item")),
885 IITraitItem(d, ti) => match ti {
886 ProvidedMethod(m) => {
887 IITraitItem(fld.fold_ops.new_def_id(d),
888 ProvidedMethod(fld.fold_method(m)
889 .expect_one("expected one method")))
891 RequiredMethod(ty_m) => {
892 IITraitItem(fld.fold_ops.new_def_id(d),
893 RequiredMethod(fld.fold_type_method(ty_m)))
896 IIImplItem(d, m) => match m {
897 MethodImplItem(m) => {
898 IIImplItem(fld.fold_ops.new_def_id(d),
899 MethodImplItem(fld.fold_method(m)
900 .expect_one("expected one method")))
903 IIForeign(i) => IIForeign(fld.fold_foreign_item(i))
906 let ii_parent = map.forest.inlined_items.alloc(InlinedParent {
911 let mut collector = NodeCollector {
912 map: mem::replace(&mut *map.map.borrow_mut(), vec![]),
913 parent: fld.new_id(DUMMY_NODE_ID)
915 let ii_parent_id = collector.parent;
916 collector.insert_entry(ii_parent_id, RootInlinedParent(ii_parent));
917 visit::walk_inlined_item(&mut collector, &ii_parent.ii);
919 // Methods get added to the AST map when their impl is visited. Since we
920 // don't decode and instantiate the impl, but just the method, we have to
921 // add it to the table now. Likewise with foreign items.
924 IITraitItem(_, ref trait_item) => {
925 let trait_item_id = match *trait_item {
926 ProvidedMethod(ref m) => m.id,
927 RequiredMethod(ref m) => m.id
930 collector.insert(trait_item_id, NodeTraitItem(trait_item));
932 IIImplItem(_, ref impl_item) => {
933 let impl_item_id = match *impl_item {
934 MethodImplItem(ref m) => m.id
937 collector.insert(impl_item_id, NodeImplItem(impl_item));
939 IIForeign(ref i) => {
940 collector.insert(i.id, NodeForeignItem(&**i));
943 *map.map.borrow_mut() = collector.map;
947 pub trait NodePrinter {
948 fn print_node(&mut self, node: &Node) -> IoResult<()>;
951 impl<'a> NodePrinter for pprust::State<'a> {
952 fn print_node(&mut self, node: &Node) -> IoResult<()> {
954 NodeItem(a) => self.print_item(&*a),
955 NodeForeignItem(a) => self.print_foreign_item(&*a),
956 NodeTraitItem(a) => self.print_trait_method(&*a),
957 NodeImplItem(a) => self.print_impl_item(&*a),
958 NodeVariant(a) => self.print_variant(&*a),
959 NodeExpr(a) => self.print_expr(&*a),
960 NodeStmt(a) => self.print_stmt(&*a),
961 NodePat(a) => self.print_pat(&*a),
962 NodeBlock(a) => self.print_block(&*a),
963 NodeLifetime(a) => self.print_lifetime(&*a),
965 // these cases do not carry enough information in the
966 // ast_map to reconstruct their full structure for pretty
968 NodeLocal(_) => fail!("cannot print isolated Local"),
969 NodeArg(_) => fail!("cannot print isolated Arg"),
970 NodeStructCtor(_) => fail!("cannot print isolated StructCtor"),
975 fn node_id_to_string(map: &Map, id: NodeId) -> String {
977 Some(NodeItem(item)) => {
978 let path_str = map.path_to_str_with_ident(id, item.ident);
979 let item_str = match item.node {
980 ItemStatic(..) => "static",
982 ItemMod(..) => "mod",
983 ItemForeignMod(..) => "foreign mod",
985 ItemEnum(..) => "enum",
986 ItemStruct(..) => "struct",
987 ItemTrait(..) => "trait",
988 ItemImpl(..) => "impl",
989 ItemMac(..) => "macro"
991 format!("{} {} (id={})", item_str, path_str, id)
993 Some(NodeForeignItem(item)) => {
994 let path_str = map.path_to_str_with_ident(id, item.ident);
995 format!("foreign item {} (id={})", path_str, id)
997 Some(NodeImplItem(ref ii)) => {
999 MethodImplItem(ref m) => {
1001 MethDecl(ident, _, _, _, _, _, _, _) =>
1002 format!("method {} in {} (id={})",
1003 token::get_ident(ident),
1004 map.path_to_string(id), id),
1006 format!("method macro {} (id={})",
1007 pprust::mac_to_string(mac), id)
1012 Some(NodeTraitItem(ref ti)) => {
1013 let ident = match **ti {
1014 ProvidedMethod(ref m) => m.pe_ident(),
1015 RequiredMethod(ref m) => m.ident
1017 format!("method {} in {} (id={})",
1018 token::get_ident(ident),
1019 map.path_to_string(id), id)
1021 Some(NodeVariant(ref variant)) => {
1022 format!("variant {} in {} (id={})",
1023 token::get_ident(variant.node.name),
1024 map.path_to_string(id), id)
1026 Some(NodeExpr(ref expr)) => {
1027 format!("expr {} (id={})", pprust::expr_to_string(&**expr), id)
1029 Some(NodeStmt(ref stmt)) => {
1030 format!("stmt {} (id={})", pprust::stmt_to_string(&**stmt), id)
1032 Some(NodeArg(ref pat)) => {
1033 format!("arg {} (id={})", pprust::pat_to_string(&**pat), id)
1035 Some(NodeLocal(ref pat)) => {
1036 format!("local {} (id={})", pprust::pat_to_string(&**pat), id)
1038 Some(NodePat(ref pat)) => {
1039 format!("pat {} (id={})", pprust::pat_to_string(&**pat), id)
1041 Some(NodeBlock(ref block)) => {
1042 format!("block {} (id={})", pprust::block_to_string(&**block), id)
1044 Some(NodeStructCtor(_)) => {
1045 format!("struct_ctor {} (id={})", map.path_to_string(id), id)
1047 Some(NodeLifetime(ref l)) => {
1048 format!("lifetime {} (id={})",
1049 pprust::lifetime_to_string(&**l), id)
1052 format!("unknown node (id={})", id)