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::{self, Visitor};
25 use arena::TypedArena;
26 use std::cell::RefCell;
28 use std::old_io::IoResult;
29 use std::iter::{self, repeat};
35 #[derive(Clone, Copy, PartialEq, Debug)]
42 pub fn name(&self) -> Name {
44 PathMod(name) | PathName(name) => name
49 impl fmt::Display 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 /// The type of the iterator used by with_path.
79 pub type PathElems<'a, 'b> = iter::Chain<iter::Cloned<slice::Iter<'a, PathElem>>, LinkedPath<'b>>;
81 pub fn path_to_string<PI: Iterator<Item=PathElem>>(path: PI) -> String {
82 let itr = token::get_ident_interner();
84 path.fold(String::new(), |mut s, e| {
85 let e = itr.get(e.name());
94 #[derive(Copy, Debug)]
97 NodeForeignItem(&'ast ForeignItem),
98 NodeTraitItem(&'ast TraitItem),
99 NodeImplItem(&'ast ImplItem),
100 NodeVariant(&'ast Variant),
101 NodeExpr(&'ast Expr),
102 NodeStmt(&'ast Stmt),
104 NodeLocal(&'ast Pat),
106 NodeBlock(&'ast Block),
108 /// NodeStructCtor represents a tuple struct.
109 NodeStructCtor(&'ast StructDef),
111 NodeLifetime(&'ast Lifetime),
114 /// Represents an entry and its parent Node ID
115 /// The odd layout is to bring down the total size.
116 #[derive(Copy, Debug)]
117 enum MapEntry<'ast> {
118 /// Placeholder for holes in the map.
121 /// All the node types, with a parent ID.
122 EntryItem(NodeId, &'ast Item),
123 EntryForeignItem(NodeId, &'ast ForeignItem),
124 EntryTraitItem(NodeId, &'ast TraitItem),
125 EntryImplItem(NodeId, &'ast ImplItem),
126 EntryVariant(NodeId, &'ast Variant),
127 EntryExpr(NodeId, &'ast Expr),
128 EntryStmt(NodeId, &'ast Stmt),
129 EntryArg(NodeId, &'ast Pat),
130 EntryLocal(NodeId, &'ast Pat),
131 EntryPat(NodeId, &'ast Pat),
132 EntryBlock(NodeId, &'ast Block),
133 EntryStructCtor(NodeId, &'ast StructDef),
134 EntryLifetime(NodeId, &'ast Lifetime),
136 /// Roots for node trees.
138 RootInlinedParent(&'ast InlinedParent)
141 impl<'ast> Clone for MapEntry<'ast> {
142 fn clone(&self) -> MapEntry<'ast> {
148 struct InlinedParent {
153 impl<'ast> MapEntry<'ast> {
154 fn from_node(p: NodeId, node: Node<'ast>) -> MapEntry<'ast> {
156 NodeItem(n) => EntryItem(p, n),
157 NodeForeignItem(n) => EntryForeignItem(p, n),
158 NodeTraitItem(n) => EntryTraitItem(p, n),
159 NodeImplItem(n) => EntryImplItem(p, n),
160 NodeVariant(n) => EntryVariant(p, n),
161 NodeExpr(n) => EntryExpr(p, n),
162 NodeStmt(n) => EntryStmt(p, n),
163 NodeArg(n) => EntryArg(p, n),
164 NodeLocal(n) => EntryLocal(p, n),
165 NodePat(n) => EntryPat(p, n),
166 NodeBlock(n) => EntryBlock(p, n),
167 NodeStructCtor(n) => EntryStructCtor(p, n),
168 NodeLifetime(n) => EntryLifetime(p, n)
172 fn parent(self) -> Option<NodeId> {
174 EntryItem(id, _) => id,
175 EntryForeignItem(id, _) => id,
176 EntryTraitItem(id, _) => id,
177 EntryImplItem(id, _) => id,
178 EntryVariant(id, _) => id,
179 EntryExpr(id, _) => id,
180 EntryStmt(id, _) => id,
181 EntryArg(id, _) => id,
182 EntryLocal(id, _) => id,
183 EntryPat(id, _) => id,
184 EntryBlock(id, _) => id,
185 EntryStructCtor(id, _) => id,
186 EntryLifetime(id, _) => id,
191 fn to_node(self) -> Option<Node<'ast>> {
193 EntryItem(_, n) => NodeItem(n),
194 EntryForeignItem(_, n) => NodeForeignItem(n),
195 EntryTraitItem(_, n) => NodeTraitItem(n),
196 EntryImplItem(_, n) => NodeImplItem(n),
197 EntryVariant(_, n) => NodeVariant(n),
198 EntryExpr(_, n) => NodeExpr(n),
199 EntryStmt(_, n) => NodeStmt(n),
200 EntryArg(_, n) => NodeArg(n),
201 EntryLocal(_, n) => NodeLocal(n),
202 EntryPat(_, n) => NodePat(n),
203 EntryBlock(_, n) => NodeBlock(n),
204 EntryStructCtor(_, n) => NodeStructCtor(n),
205 EntryLifetime(_, n) => NodeLifetime(n),
211 /// Stores a crate and any number of inlined items from other crates.
214 inlined_items: TypedArena<InlinedParent>
218 pub fn new(krate: Crate) -> Forest {
221 inlined_items: TypedArena::new()
225 pub fn krate<'ast>(&'ast self) -> &'ast Crate {
230 /// Represents a mapping from Node IDs to AST elements and their parent
232 pub struct Map<'ast> {
233 /// The backing storage for all the AST nodes.
234 forest: &'ast Forest,
236 /// NodeIds are sequential integers from 0, so we can be
237 /// super-compact by storing them in a vector. Not everything with
238 /// a NodeId is in the map, but empirically the occupancy is about
239 /// 75-80%, so there's not too much overhead (certainly less than
240 /// a hashmap, since they (at the time of writing) have a maximum
241 /// of 75% occupancy).
243 /// Also, indexing is pretty quick when you've got a vector and
244 /// plain old integers.
245 map: RefCell<Vec<MapEntry<'ast>>>
248 impl<'ast> Map<'ast> {
249 fn entry_count(&self) -> usize {
250 self.map.borrow().len()
253 fn find_entry(&self, id: NodeId) -> Option<MapEntry<'ast>> {
254 self.map.borrow().get(id as usize).cloned()
257 pub fn krate(&self) -> &'ast Crate {
261 /// Retrieve the Node corresponding to `id`, panicking if it cannot
263 pub fn get(&self, id: NodeId) -> Node<'ast> {
264 match self.find(id) {
266 None => panic!("couldn't find node id {} in the AST map", id)
270 /// Retrieve the Node corresponding to `id`, returning None if
272 pub fn find(&self, id: NodeId) -> Option<Node<'ast>> {
273 self.find_entry(id).and_then(|x| x.to_node())
276 /// Retrieve the parent NodeId for `id`, or `id` itself if no
277 /// parent is registered in this map.
278 pub fn get_parent(&self, id: NodeId) -> NodeId {
279 self.find_entry(id).and_then(|x| x.parent()).unwrap_or(id)
282 pub fn get_parent_did(&self, id: NodeId) -> DefId {
283 let parent = self.get_parent(id);
284 match self.find_entry(parent) {
285 Some(RootInlinedParent(&InlinedParent {ii: IITraitItem(did, _), ..})) => did,
286 Some(RootInlinedParent(&InlinedParent {ii: IIImplItem(did, _), ..})) => did,
287 _ => ast_util::local_def(parent)
291 pub fn get_foreign_abi(&self, id: NodeId) -> abi::Abi {
292 let parent = self.get_parent(id);
293 let abi = match self.find_entry(parent) {
294 Some(EntryItem(_, i)) => {
296 ItemForeignMod(ref nm) => Some(nm.abi),
300 /// Wrong but OK, because the only inlined foreign items are intrinsics.
301 Some(RootInlinedParent(_)) => Some(abi::RustIntrinsic),
306 None => panic!("expected foreign mod or inlined parent, found {}",
307 self.node_to_string(parent))
311 pub fn get_foreign_vis(&self, id: NodeId) -> Visibility {
312 let vis = self.expect_foreign_item(id).vis;
313 match self.find(self.get_parent(id)) {
314 Some(NodeItem(i)) => vis.inherit_from(i.vis),
319 pub fn expect_item(&self, id: NodeId) -> &'ast Item {
320 match self.find(id) {
321 Some(NodeItem(item)) => item,
322 _ => panic!("expected item, found {}", self.node_to_string(id))
326 pub fn expect_struct(&self, id: NodeId) -> &'ast StructDef {
327 match self.find(id) {
328 Some(NodeItem(i)) => {
330 ItemStruct(ref struct_def, _) => &**struct_def,
331 _ => panic!("struct ID bound to non-struct")
334 Some(NodeVariant(variant)) => {
335 match variant.node.kind {
336 StructVariantKind(ref struct_def) => &**struct_def,
337 _ => panic!("struct ID bound to enum variant that isn't struct-like"),
340 _ => panic!(format!("expected struct, found {}", self.node_to_string(id))),
344 pub fn expect_variant(&self, id: NodeId) -> &'ast Variant {
345 match self.find(id) {
346 Some(NodeVariant(variant)) => variant,
347 _ => panic!(format!("expected variant, found {}", self.node_to_string(id))),
351 pub fn expect_foreign_item(&self, id: NodeId) -> &'ast ForeignItem {
352 match self.find(id) {
353 Some(NodeForeignItem(item)) => item,
354 _ => panic!("expected foreign item, found {}", self.node_to_string(id))
358 pub fn expect_expr(&self, id: NodeId) -> &'ast Expr {
359 match self.find(id) {
360 Some(NodeExpr(expr)) => expr,
361 _ => panic!("expected expr, found {}", self.node_to_string(id))
365 /// returns the name associated with the given NodeId's AST
366 pub fn get_path_elem(&self, id: NodeId) -> PathElem {
367 let node = self.get(id);
371 ItemMod(_) | ItemForeignMod(_) => {
372 PathMod(item.ident.name)
374 _ => PathName(item.ident.name)
377 NodeForeignItem(i) => PathName(i.ident.name),
378 NodeImplItem(ii) => {
380 MethodImplItem(ref m) => {
382 MethDecl(ident, _, _, _, _, _, _, _) => {
386 panic!("no path elem for {:?}", node)
390 TypeImplItem(ref t) => PathName(t.ident.name),
393 NodeTraitItem(tm) => match *tm {
394 RequiredMethod(ref m) => PathName(m.ident.name),
395 ProvidedMethod(ref m) => {
397 MethDecl(ident, _, _, _, _, _, _, _) => {
400 MethMac(_) => panic!("no path elem for {:?}", node),
403 TypeTraitItem(ref m) => {
404 PathName(m.ty_param.ident.name)
407 NodeVariant(v) => PathName(v.node.name.name),
408 _ => panic!("no path elem for {:?}", node)
412 pub fn with_path<T, F>(&self, id: NodeId, f: F) -> T where
413 F: FnOnce(PathElems) -> 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, F>(&self, id: NodeId, next: LinkedPath, f: F) -> T where
429 F: FnOnce(PathElems) -> T,
431 let parent = self.get_parent(id);
432 let parent = match self.find_entry(id) {
433 Some(EntryForeignItem(..)) | Some(EntryVariant(..)) => {
434 // Anonymous extern items, enum variants and struct ctors
435 // go in the parent scope.
436 self.get_parent(parent)
438 // But tuple struct ctors don't have names, so use the path of its
439 // parent, the struct item. Similarly with closure expressions.
440 Some(EntryStructCtor(..)) | Some(EntryExpr(..)) => {
441 return self.with_path_next(parent, next, f);
446 match self.find_entry(id) {
447 Some(RootInlinedParent(data)) => {
448 f(data.path.iter().cloned().chain(next))
450 _ => f([].iter().cloned().chain(next))
453 self.with_path_next(parent, Some(&LinkedPathNode {
454 node: self.get_path_elem(id),
460 /// Given a node ID and a closure, apply the closure to the array
461 /// of attributes associated with the AST corresponding to the Node ID
462 pub fn with_attrs<T, F>(&self, id: NodeId, f: F) -> T where
463 F: FnOnce(Option<&[Attribute]>) -> T,
465 let attrs = match self.get(id) {
466 NodeItem(i) => Some(&i.attrs[..]),
467 NodeForeignItem(fi) => Some(&fi.attrs[..]),
468 NodeTraitItem(ref tm) => match **tm {
469 RequiredMethod(ref type_m) => Some(&type_m.attrs[..]),
470 ProvidedMethod(ref m) => Some(&m.attrs[..]),
471 TypeTraitItem(ref typ) => Some(&typ.attrs[..]),
473 NodeImplItem(ref ii) => {
475 MethodImplItem(ref m) => Some(&m.attrs[..]),
476 TypeImplItem(ref t) => Some(&t.attrs[..]),
479 NodeVariant(ref v) => Some(&v.node.attrs[..]),
480 // unit/tuple structs take the attributes straight from
481 // the struct definition.
482 // FIXME(eddyb) make this work again (requires access to the map).
483 NodeStructCtor(_) => {
484 return self.with_attrs(self.get_parent(id), f);
491 /// Returns an iterator that yields the node id's with paths that
492 /// match `parts`. (Requires `parts` is non-empty.)
494 /// For example, if given `parts` equal to `["bar", "quux"]`, then
495 /// the iterator will produce node id's for items with paths
496 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
497 /// any other such items it can find in the map.
498 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
499 -> NodesMatchingSuffix<'a, 'ast> {
500 NodesMatchingSuffix {
502 item_name: parts.last().unwrap(),
503 in_which: &parts[..parts.len() - 1],
508 pub fn opt_span(&self, id: NodeId) -> Option<Span> {
509 let sp = match self.find(id) {
510 Some(NodeItem(item)) => item.span,
511 Some(NodeForeignItem(foreign_item)) => foreign_item.span,
512 Some(NodeTraitItem(trait_method)) => {
513 match *trait_method {
514 RequiredMethod(ref type_method) => type_method.span,
515 ProvidedMethod(ref method) => method.span,
516 TypeTraitItem(ref typedef) => typedef.ty_param.span,
519 Some(NodeImplItem(ref impl_item)) => {
521 MethodImplItem(ref method) => method.span,
522 TypeImplItem(ref typedef) => typedef.span,
525 Some(NodeVariant(variant)) => variant.span,
526 Some(NodeExpr(expr)) => expr.span,
527 Some(NodeStmt(stmt)) => stmt.span,
528 Some(NodeArg(pat)) | Some(NodeLocal(pat)) => pat.span,
529 Some(NodePat(pat)) => pat.span,
530 Some(NodeBlock(block)) => block.span,
531 Some(NodeStructCtor(_)) => self.expect_item(self.get_parent(id)).span,
537 pub fn span(&self, id: NodeId) -> Span {
539 .unwrap_or_else(|| panic!("AstMap.span: could not find span for id {:?}", id))
542 pub fn def_id_span(&self, def_id: DefId, fallback: Span) -> Span {
543 if def_id.krate == LOCAL_CRATE {
544 self.opt_span(def_id.node).unwrap_or(fallback)
550 pub fn node_to_string(&self, id: NodeId) -> String {
551 node_id_to_string(self, id, true)
554 pub fn node_to_user_string(&self, id: NodeId) -> String {
555 node_id_to_string(self, id, false)
559 pub struct NodesMatchingSuffix<'a, 'ast:'a> {
561 item_name: &'a String,
562 in_which: &'a [String],
566 impl<'a, 'ast> NodesMatchingSuffix<'a, 'ast> {
567 /// Returns true only if some suffix of the module path for parent
568 /// matches `self.in_which`.
570 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
571 /// returns true if parent's path ends with the suffix
572 /// `x_0::x_1::...::x_k`.
573 fn suffix_matches(&self, parent: NodeId) -> bool {
574 let mut cursor = parent;
575 for part in self.in_which.iter().rev() {
576 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
577 None => return false,
578 Some((node_id, name)) => (node_id, name),
580 if &part[..] != mod_name.as_str() {
583 cursor = self.map.get_parent(mod_id);
587 // Finds the first mod in parent chain for `id`, along with
590 // If `id` itself is a mod named `m` with parent `p`, then
591 // returns `Some(id, m, p)`. If `id` has no mod in its parent
592 // chain, then returns `None`.
593 fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
597 Some(NodeItem(item)) if item_is_mod(&*item) =>
598 return Some((id, item.ident.name)),
601 let parent = map.get_parent(id);
602 if parent == id { return None }
606 fn item_is_mod(item: &Item) -> bool {
615 // We are looking at some node `n` with a given name and parent
616 // id; do their names match what I am seeking?
617 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
618 name.as_str() == &self.item_name[..] &&
619 self.suffix_matches(parent_of_n)
623 impl<'a, 'ast> Iterator for NodesMatchingSuffix<'a, 'ast> {
626 fn next(&mut self) -> Option<NodeId> {
629 if idx as usize >= self.map.entry_count() {
633 let (p, name) = match self.map.find_entry(idx) {
634 Some(EntryItem(p, n)) => (p, n.name()),
635 Some(EntryForeignItem(p, n))=> (p, n.name()),
636 Some(EntryTraitItem(p, n)) => (p, n.name()),
637 Some(EntryImplItem(p, n)) => (p, n.name()),
638 Some(EntryVariant(p, n)) => (p, n.name()),
641 if self.matches_names(p, name) {
649 fn name(&self) -> Name;
652 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
654 impl Named for Item { fn name(&self) -> Name { self.ident.name } }
655 impl Named for ForeignItem { fn name(&self) -> Name { self.ident.name } }
656 impl Named for Variant_ { fn name(&self) -> Name { self.name.name } }
657 impl Named for TraitItem {
658 fn name(&self) -> Name {
660 RequiredMethod(ref tm) => tm.ident.name,
661 ProvidedMethod(ref m) => m.name(),
662 TypeTraitItem(ref at) => at.ty_param.ident.name,
666 impl Named for ImplItem {
667 fn name(&self) -> Name {
669 MethodImplItem(ref m) => m.name(),
670 TypeImplItem(ref td) => td.ident.name,
674 impl Named for Method {
675 fn name(&self) -> Name {
677 MethDecl(i, _, _, _, _, _, _, _) => i.name,
678 MethMac(_) => panic!("encountered unexpanded method macro."),
684 fn new_id(&self, id: NodeId) -> NodeId {
687 fn new_def_id(&self, def_id: DefId) -> DefId {
690 fn new_span(&self, span: Span) -> Span {
695 /// A Folder that updates IDs and Span's according to fold_ops.
696 struct IdAndSpanUpdater<F> {
700 impl<F: FoldOps> Folder for IdAndSpanUpdater<F> {
701 fn new_id(&mut self, id: NodeId) -> NodeId {
702 self.fold_ops.new_id(id)
705 fn new_span(&mut self, span: Span) -> Span {
706 self.fold_ops.new_span(span)
710 /// A Visitor that walks over an AST and collects Node's into an AST Map.
711 struct NodeCollector<'ast> {
712 map: Vec<MapEntry<'ast>>,
713 /// The node in which we are currently mapping (an item or a method).
717 impl<'ast> NodeCollector<'ast> {
718 fn insert_entry(&mut self, id: NodeId, entry: MapEntry<'ast>) {
719 debug!("ast_map: {:?} => {:?}", id, entry);
720 let len = self.map.len();
721 if id as usize >= len {
722 self.map.extend(repeat(NotPresent).take(id as usize - len + 1));
724 self.map[id as usize] = entry;
727 fn insert(&mut self, id: NodeId, node: Node<'ast>) {
728 let entry = MapEntry::from_node(self.parent, node);
729 self.insert_entry(id, entry);
732 fn visit_fn_decl(&mut self, decl: &'ast FnDecl) {
733 for a in &decl.inputs {
734 self.insert(a.id, NodeArg(&*a.pat));
739 impl<'ast> Visitor<'ast> for NodeCollector<'ast> {
740 fn visit_item(&mut self, i: &'ast Item) {
741 self.insert(i.id, NodeItem(i));
742 let parent = self.parent;
745 ItemImpl(_, _, _, _, _, ref impl_items) => {
746 for impl_item in impl_items {
748 MethodImplItem(ref m) => {
749 self.insert(m.id, NodeImplItem(impl_item));
751 TypeImplItem(ref t) => {
752 self.insert(t.id, NodeImplItem(impl_item));
757 ItemEnum(ref enum_definition, _) => {
758 for v in &enum_definition.variants {
759 self.insert(v.node.id, NodeVariant(&**v));
762 ItemForeignMod(ref nm) => {
763 for nitem in &nm.items {
764 self.insert(nitem.id, NodeForeignItem(&**nitem));
767 ItemStruct(ref struct_def, _) => {
768 // If this is a tuple-like struct, register the constructor.
769 match struct_def.ctor_id {
771 self.insert(ctor_id, NodeStructCtor(&**struct_def));
776 ItemTrait(_, _, ref bounds, ref trait_items) => {
778 if let TraitTyParamBound(ref t, TraitBoundModifier::None) = *b {
779 self.insert(t.trait_ref.ref_id, NodeItem(i));
783 for tm in trait_items {
785 RequiredMethod(ref m) => {
786 self.insert(m.id, NodeTraitItem(tm));
788 ProvidedMethod(ref m) => {
789 self.insert(m.id, NodeTraitItem(tm));
791 TypeTraitItem(ref typ) => {
792 self.insert(typ.ty_param.id, NodeTraitItem(tm));
799 visit::walk_item(self, i);
800 self.parent = parent;
803 fn visit_pat(&mut self, pat: &'ast Pat) {
804 self.insert(pat.id, match pat.node {
805 // Note: this is at least *potentially* a pattern...
806 PatIdent(..) => NodeLocal(pat),
809 visit::walk_pat(self, pat);
812 fn visit_expr(&mut self, expr: &'ast Expr) {
813 self.insert(expr.id, NodeExpr(expr));
814 visit::walk_expr(self, expr);
817 fn visit_stmt(&mut self, stmt: &'ast Stmt) {
818 self.insert(ast_util::stmt_id(stmt), NodeStmt(stmt));
819 visit::walk_stmt(self, stmt);
822 fn visit_ty_method(&mut self, m: &'ast TypeMethod) {
823 let parent = self.parent;
825 self.visit_fn_decl(&*m.decl);
826 visit::walk_ty_method(self, m);
827 self.parent = parent;
830 fn visit_fn(&mut self, fk: visit::FnKind<'ast>, fd: &'ast FnDecl,
831 b: &'ast Block, s: Span, id: NodeId) {
833 visit::FkMethod(..) => {
834 let parent = self.parent;
836 self.visit_fn_decl(fd);
837 visit::walk_fn(self, fk, fd, b, s);
838 self.parent = parent;
841 self.visit_fn_decl(fd);
842 visit::walk_fn(self, fk, fd, b, s);
847 fn visit_ty(&mut self, ty: &'ast Ty) {
849 TyBareFn(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_def(&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 {
880 exported_macros: vec![],
883 forest.krate = IdAndSpanUpdater { fold_ops: fold_ops }.fold_crate(krate);
885 let mut collector = NodeCollector {
887 parent: CRATE_NODE_ID
889 collector.insert_entry(CRATE_NODE_ID, RootCrate);
890 visit::walk_crate(&mut collector, &forest.krate);
891 let map = collector.map;
893 if log_enabled!(::log::DEBUG) {
894 // This only makes sense for ordered stores; note the
895 // enumerate to count the number of entries.
896 let (entries_less_1, _) = map.iter().filter(|&x| {
901 }).enumerate().last().expect("AST map was empty after folding?");
903 let entries = entries_less_1 + 1;
904 let vector_length = map.len();
905 debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
906 entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
911 map: RefCell::new(map)
915 /// Used for items loaded from external crate that are being inlined into this
916 /// crate. The `path` should be the path to the item but should not include
918 pub fn map_decoded_item<'ast, F: FoldOps>(map: &Map<'ast>,
922 -> &'ast InlinedItem {
923 let mut fld = IdAndSpanUpdater { fold_ops: fold_ops };
925 IIItem(i) => IIItem(fld.fold_item(i).expect_one("expected one item")),
926 IITraitItem(d, ti) => match ti {
927 ProvidedMethod(m) => {
928 IITraitItem(fld.fold_ops.new_def_id(d),
929 ProvidedMethod(fld.fold_method(m)
930 .expect_one("expected one method")))
932 RequiredMethod(ty_m) => {
933 IITraitItem(fld.fold_ops.new_def_id(d),
934 RequiredMethod(fld.fold_type_method(ty_m)))
936 TypeTraitItem(at) => {
938 fld.fold_ops.new_def_id(d),
939 TypeTraitItem(P(fld.fold_associated_type((*at).clone()))))
942 IIImplItem(d, m) => match m {
943 MethodImplItem(m) => {
944 IIImplItem(fld.fold_ops.new_def_id(d),
945 MethodImplItem(fld.fold_method(m)
946 .expect_one("expected one method")))
949 IIImplItem(fld.fold_ops.new_def_id(d),
950 TypeImplItem(P(fld.fold_typedef((*t).clone()))))
953 IIForeign(i) => IIForeign(fld.fold_foreign_item(i))
956 let ii_parent = map.forest.inlined_items.alloc(InlinedParent {
961 let mut collector = NodeCollector {
962 map: mem::replace(&mut *map.map.borrow_mut(), vec![]),
963 parent: fld.new_id(DUMMY_NODE_ID)
965 let ii_parent_id = collector.parent;
966 collector.insert_entry(ii_parent_id, RootInlinedParent(ii_parent));
967 visit::walk_inlined_item(&mut collector, &ii_parent.ii);
969 // Methods get added to the AST map when their impl is visited. Since we
970 // don't decode and instantiate the impl, but just the method, we have to
971 // add it to the table now. Likewise with foreign items.
974 IITraitItem(_, ref trait_item) => {
975 let trait_item_id = match *trait_item {
976 ProvidedMethod(ref m) => m.id,
977 RequiredMethod(ref m) => m.id,
978 TypeTraitItem(ref ty) => ty.ty_param.id,
981 collector.insert(trait_item_id, NodeTraitItem(trait_item));
983 IIImplItem(_, ref impl_item) => {
984 let impl_item_id = match *impl_item {
985 MethodImplItem(ref m) => m.id,
986 TypeImplItem(ref ti) => ti.id,
989 collector.insert(impl_item_id, NodeImplItem(impl_item));
991 IIForeign(ref i) => {
992 collector.insert(i.id, NodeForeignItem(&**i));
995 *map.map.borrow_mut() = collector.map;
999 pub trait NodePrinter {
1000 fn print_node(&mut self, node: &Node) -> IoResult<()>;
1003 impl<'a> NodePrinter for pprust::State<'a> {
1004 fn print_node(&mut self, node: &Node) -> IoResult<()> {
1006 NodeItem(a) => self.print_item(&*a),
1007 NodeForeignItem(a) => self.print_foreign_item(&*a),
1008 NodeTraitItem(a) => self.print_trait_method(&*a),
1009 NodeImplItem(a) => self.print_impl_item(&*a),
1010 NodeVariant(a) => self.print_variant(&*a),
1011 NodeExpr(a) => self.print_expr(&*a),
1012 NodeStmt(a) => self.print_stmt(&*a),
1013 NodePat(a) => self.print_pat(&*a),
1014 NodeBlock(a) => self.print_block(&*a),
1015 NodeLifetime(a) => self.print_lifetime(&*a),
1017 // these cases do not carry enough information in the
1018 // ast_map to reconstruct their full structure for pretty
1020 NodeLocal(_) => panic!("cannot print isolated Local"),
1021 NodeArg(_) => panic!("cannot print isolated Arg"),
1022 NodeStructCtor(_) => panic!("cannot print isolated StructCtor"),
1027 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
1028 let id_str = format!(" (id={})", id);
1029 let id_str = if include_id { &id_str[..] } else { "" };
1031 match map.find(id) {
1032 Some(NodeItem(item)) => {
1033 let path_str = map.path_to_str_with_ident(id, item.ident);
1034 let item_str = match item.node {
1035 ItemExternCrate(..) => "extern crate",
1036 ItemUse(..) => "use",
1037 ItemStatic(..) => "static",
1038 ItemConst(..) => "const",
1040 ItemMod(..) => "mod",
1041 ItemForeignMod(..) => "foreign mod",
1043 ItemEnum(..) => "enum",
1044 ItemStruct(..) => "struct",
1045 ItemTrait(..) => "trait",
1046 ItemImpl(..) => "impl",
1047 ItemMac(..) => "macro"
1049 format!("{} {}{}", item_str, path_str, id_str)
1051 Some(NodeForeignItem(item)) => {
1052 let path_str = map.path_to_str_with_ident(id, item.ident);
1053 format!("foreign item {}{}", path_str, id_str)
1055 Some(NodeImplItem(ref ii)) => {
1057 MethodImplItem(ref m) => {
1059 MethDecl(ident, _, _, _, _, _, _, _) =>
1060 format!("method {} in {}{}",
1061 token::get_ident(ident),
1062 map.path_to_string(id), id_str),
1064 format!("method macro {}{}",
1065 pprust::mac_to_string(mac), id_str)
1068 TypeImplItem(ref t) => {
1069 format!("typedef {} in {}{}",
1070 token::get_ident(t.ident),
1071 map.path_to_string(id),
1076 Some(NodeTraitItem(ref tm)) => {
1078 RequiredMethod(_) | ProvidedMethod(_) => {
1079 let m = ast_util::trait_item_to_ty_method(&**tm);
1080 format!("method {} in {}{}",
1081 token::get_ident(m.ident),
1082 map.path_to_string(id),
1085 TypeTraitItem(ref t) => {
1086 format!("type item {} in {}{}",
1087 token::get_ident(t.ty_param.ident),
1088 map.path_to_string(id),
1093 Some(NodeVariant(ref variant)) => {
1094 format!("variant {} in {}{}",
1095 token::get_ident(variant.node.name),
1096 map.path_to_string(id), id_str)
1098 Some(NodeExpr(ref expr)) => {
1099 format!("expr {}{}", pprust::expr_to_string(&**expr), id_str)
1101 Some(NodeStmt(ref stmt)) => {
1102 format!("stmt {}{}", pprust::stmt_to_string(&**stmt), id_str)
1104 Some(NodeArg(ref pat)) => {
1105 format!("arg {}{}", pprust::pat_to_string(&**pat), id_str)
1107 Some(NodeLocal(ref pat)) => {
1108 format!("local {}{}", pprust::pat_to_string(&**pat), id_str)
1110 Some(NodePat(ref pat)) => {
1111 format!("pat {}{}", pprust::pat_to_string(&**pat), id_str)
1113 Some(NodeBlock(ref block)) => {
1114 format!("block {}{}", pprust::block_to_string(&**block), id_str)
1116 Some(NodeStructCtor(_)) => {
1117 format!("struct_ctor {}{}", map.path_to_string(id), id_str)
1119 Some(NodeLifetime(ref l)) => {
1120 format!("lifetime {}{}",
1121 pprust::lifetime_to_string(&**l), id_str)
1124 format!("unknown node{}", id_str)