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 syntax::codemap::{DUMMY_SP, Span, Spanned};
19 use syntax::fold::Folder;
20 use syntax::parse::token;
21 use syntax::print::pprust;
22 use syntax::visit::{self, Visitor};
24 use arena::TypedArena;
25 use std::cell::RefCell;
28 use std::iter::{self, repeat};
34 #[derive(Clone, Copy, PartialEq, Debug)]
41 pub fn name(&self) -> Name {
43 PathMod(name) | PathName(name) => name
48 impl fmt::Display for PathElem {
49 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
50 write!(f, "{}", self.name())
55 pub struct LinkedPathNode<'a> {
60 #[derive(Copy, Clone)]
61 pub struct LinkedPath<'a>(Option<&'a LinkedPathNode<'a>>);
63 impl<'a> LinkedPath<'a> {
64 pub fn empty() -> LinkedPath<'a> {
68 pub fn from(node: &'a LinkedPathNode) -> LinkedPath<'a> {
69 LinkedPath(Some(node))
73 impl<'a> Iterator for LinkedPath<'a> {
76 fn next(&mut self) -> Option<PathElem> {
87 /// The type of the iterator used by with_path.
88 pub type PathElems<'a, 'b> = iter::Chain<iter::Cloned<slice::Iter<'a, PathElem>>, LinkedPath<'b>>;
90 pub fn path_to_string<PI: Iterator<Item=PathElem>>(path: PI) -> String {
91 let itr = token::get_ident_interner();
93 path.fold(String::new(), |mut s, e| {
94 let e = itr.get(e.name());
103 #[derive(Copy, Clone, Debug)]
104 pub enum Node<'ast> {
105 NodeItem(&'ast Item),
106 NodeForeignItem(&'ast ForeignItem),
107 NodeTraitItem(&'ast TraitItem),
108 NodeImplItem(&'ast ImplItem),
109 NodeVariant(&'ast Variant),
110 NodeExpr(&'ast Expr),
111 NodeStmt(&'ast Stmt),
113 NodeLocal(&'ast Pat),
115 NodeBlock(&'ast Block),
117 /// NodeStructCtor represents a tuple struct.
118 NodeStructCtor(&'ast StructDef),
120 NodeLifetime(&'ast Lifetime),
121 NodeTyParam(&'ast TyParam)
124 /// Represents an entry and its parent NodeID.
125 /// The odd layout is to bring down the total size.
126 #[derive(Copy, Debug)]
127 enum MapEntry<'ast> {
128 /// Placeholder for holes in the map.
131 /// All the node types, with a parent ID.
132 EntryItem(NodeId, &'ast Item),
133 EntryForeignItem(NodeId, &'ast ForeignItem),
134 EntryTraitItem(NodeId, &'ast TraitItem),
135 EntryImplItem(NodeId, &'ast ImplItem),
136 EntryVariant(NodeId, &'ast Variant),
137 EntryExpr(NodeId, &'ast Expr),
138 EntryStmt(NodeId, &'ast Stmt),
139 EntryArg(NodeId, &'ast Pat),
140 EntryLocal(NodeId, &'ast Pat),
141 EntryPat(NodeId, &'ast Pat),
142 EntryBlock(NodeId, &'ast Block),
143 EntryStructCtor(NodeId, &'ast StructDef),
144 EntryLifetime(NodeId, &'ast Lifetime),
145 EntryTyParam(NodeId, &'ast TyParam),
147 /// Roots for node trees.
149 RootInlinedParent(&'ast InlinedParent)
152 impl<'ast> Clone for MapEntry<'ast> {
153 fn clone(&self) -> MapEntry<'ast> {
159 struct InlinedParent {
164 impl<'ast> MapEntry<'ast> {
165 fn from_node(p: NodeId, node: Node<'ast>) -> MapEntry<'ast> {
167 NodeItem(n) => EntryItem(p, n),
168 NodeForeignItem(n) => EntryForeignItem(p, n),
169 NodeTraitItem(n) => EntryTraitItem(p, n),
170 NodeImplItem(n) => EntryImplItem(p, n),
171 NodeVariant(n) => EntryVariant(p, n),
172 NodeExpr(n) => EntryExpr(p, n),
173 NodeStmt(n) => EntryStmt(p, n),
174 NodeArg(n) => EntryArg(p, n),
175 NodeLocal(n) => EntryLocal(p, n),
176 NodePat(n) => EntryPat(p, n),
177 NodeBlock(n) => EntryBlock(p, n),
178 NodeStructCtor(n) => EntryStructCtor(p, n),
179 NodeLifetime(n) => EntryLifetime(p, n),
180 NodeTyParam(n) => EntryTyParam(p, n),
184 fn parent_node(self) -> Option<NodeId> {
186 EntryItem(id, _) => id,
187 EntryForeignItem(id, _) => id,
188 EntryTraitItem(id, _) => id,
189 EntryImplItem(id, _) => id,
190 EntryVariant(id, _) => id,
191 EntryExpr(id, _) => id,
192 EntryStmt(id, _) => id,
193 EntryArg(id, _) => id,
194 EntryLocal(id, _) => id,
195 EntryPat(id, _) => id,
196 EntryBlock(id, _) => id,
197 EntryStructCtor(id, _) => id,
198 EntryLifetime(id, _) => id,
199 EntryTyParam(id, _) => id,
204 fn to_node(self) -> Option<Node<'ast>> {
206 EntryItem(_, n) => NodeItem(n),
207 EntryForeignItem(_, n) => NodeForeignItem(n),
208 EntryTraitItem(_, n) => NodeTraitItem(n),
209 EntryImplItem(_, n) => NodeImplItem(n),
210 EntryVariant(_, n) => NodeVariant(n),
211 EntryExpr(_, n) => NodeExpr(n),
212 EntryStmt(_, n) => NodeStmt(n),
213 EntryArg(_, n) => NodeArg(n),
214 EntryLocal(_, n) => NodeLocal(n),
215 EntryPat(_, n) => NodePat(n),
216 EntryBlock(_, n) => NodeBlock(n),
217 EntryStructCtor(_, n) => NodeStructCtor(n),
218 EntryLifetime(_, n) => NodeLifetime(n),
219 EntryTyParam(_, n) => NodeTyParam(n),
225 /// Stores a crate and any number of inlined items from other crates.
228 inlined_items: TypedArena<InlinedParent>
232 pub fn new(krate: Crate) -> Forest {
235 inlined_items: TypedArena::new()
239 pub fn krate<'ast>(&'ast self) -> &'ast Crate {
244 /// Represents a mapping from Node IDs to AST elements and their parent
246 pub struct Map<'ast> {
247 /// The backing storage for all the AST nodes.
248 forest: &'ast Forest,
250 /// NodeIds are sequential integers from 0, so we can be
251 /// super-compact by storing them in a vector. Not everything with
252 /// a NodeId is in the map, but empirically the occupancy is about
253 /// 75-80%, so there's not too much overhead (certainly less than
254 /// a hashmap, since they (at the time of writing) have a maximum
255 /// of 75% occupancy).
257 /// Also, indexing is pretty quick when you've got a vector and
258 /// plain old integers.
259 map: RefCell<Vec<MapEntry<'ast>>>
262 impl<'ast> Map<'ast> {
263 fn entry_count(&self) -> usize {
264 self.map.borrow().len()
267 fn find_entry(&self, id: NodeId) -> Option<MapEntry<'ast>> {
268 self.map.borrow().get(id as usize).cloned()
271 pub fn krate(&self) -> &'ast Crate {
275 /// Retrieve the Node corresponding to `id`, panicking if it cannot
277 pub fn get(&self, id: NodeId) -> Node<'ast> {
278 match self.find(id) {
280 None => panic!("couldn't find node id {} in the AST map", id)
284 /// Retrieve the Node corresponding to `id`, returning None if
286 pub fn find(&self, id: NodeId) -> Option<Node<'ast>> {
287 self.find_entry(id).and_then(|x| x.to_node())
290 /// Similar to get_parent, returns the parent node id or id if there is no
292 /// This function returns the immediate parent in the AST, whereas get_parent
293 /// returns the enclosing item. Note that this might not be the actual parent
294 /// node in the AST - some kinds of nodes are not in the map and these will
295 /// never appear as the parent_node. So you can always walk the parent_nodes
296 /// from a node to the root of the ast (unless you get the same id back here
297 /// that can happen if the id is not in the map itself or is just weird).
298 pub fn get_parent_node(&self, id: NodeId) -> NodeId {
299 self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
302 /// If there is some error when walking the parents (e.g., a node does not
303 /// have a parent in the map or a node can't be found), then we return the
304 /// last good node id we found. Note that reaching the crate root (id == 0),
305 /// is not an error, since items in the crate module have the crate root as
307 fn walk_parent_nodes<F>(&self, start_id: NodeId, found: F) -> Result<NodeId, NodeId>
308 where F: Fn(&Node<'ast>) -> bool
310 let mut id = start_id;
312 let parent_node = self.get_parent_node(id);
313 if parent_node == 0 {
316 if parent_node == id {
320 let node = self.find_entry(parent_node);
324 let node = node.unwrap().to_node();
328 return Ok(parent_node);
332 return Err(parent_node);
339 /// Retrieve the NodeId for `id`'s parent item, or `id` itself if no
340 /// parent item is in this map. The "parent item" is the closest parent node
341 /// in the AST which is recorded by the map and is an item, either an item
342 /// in a module, trait, or impl.
343 pub fn get_parent(&self, id: NodeId) -> NodeId {
344 match self.walk_parent_nodes(id, |node| match *node {
348 NodeImplItem(_) => true,
356 /// Returns the nearest enclosing scope. A scope is an item or block.
357 /// FIXME it is not clear to me that all items qualify as scopes - statics
358 /// and associated types probably shouldn't, for example. Behaviour in this
359 /// regard should be expected to be highly unstable.
360 pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
361 match self.walk_parent_nodes(id, |node| match *node {
366 NodeBlock(_) => true,
374 pub fn get_parent_did(&self, id: NodeId) -> DefId {
375 let parent = self.get_parent(id);
376 match self.find_entry(parent) {
377 Some(RootInlinedParent(&InlinedParent {ii: IITraitItem(did, _), ..})) => did,
378 Some(RootInlinedParent(&InlinedParent {ii: IIImplItem(did, _), ..})) => did,
379 _ => ast_util::local_def(parent)
383 pub fn get_foreign_abi(&self, id: NodeId) -> abi::Abi {
384 let parent = self.get_parent(id);
385 let abi = match self.find_entry(parent) {
386 Some(EntryItem(_, i)) => {
388 ItemForeignMod(ref nm) => Some(nm.abi),
392 /// Wrong but OK, because the only inlined foreign items are intrinsics.
393 Some(RootInlinedParent(_)) => Some(abi::RustIntrinsic),
398 None => panic!("expected foreign mod or inlined parent, found {}",
399 self.node_to_string(parent))
403 pub fn get_foreign_vis(&self, id: NodeId) -> Visibility {
404 let vis = self.expect_foreign_item(id).vis;
405 match self.find(self.get_parent(id)) {
406 Some(NodeItem(i)) => vis.inherit_from(i.vis),
411 pub fn expect_item(&self, id: NodeId) -> &'ast Item {
412 match self.find(id) {
413 Some(NodeItem(item)) => item,
414 _ => panic!("expected item, found {}", self.node_to_string(id))
418 pub fn expect_trait_item(&self, id: NodeId) -> &'ast TraitItem {
419 match self.find(id) {
420 Some(NodeTraitItem(item)) => item,
421 _ => panic!("expected trait item, found {}", self.node_to_string(id))
425 pub fn expect_struct(&self, id: NodeId) -> &'ast StructDef {
426 match self.find(id) {
427 Some(NodeItem(i)) => {
429 ItemStruct(ref struct_def, _) => &**struct_def,
430 _ => panic!("struct ID bound to non-struct")
433 Some(NodeVariant(variant)) => {
434 match variant.node.kind {
435 StructVariantKind(ref struct_def) => &**struct_def,
436 _ => panic!("struct ID bound to enum variant that isn't struct-like"),
439 _ => panic!(format!("expected struct, found {}", self.node_to_string(id))),
443 pub fn expect_variant(&self, id: NodeId) -> &'ast Variant {
444 match self.find(id) {
445 Some(NodeVariant(variant)) => variant,
446 _ => panic!(format!("expected variant, found {}", self.node_to_string(id))),
450 pub fn expect_foreign_item(&self, id: NodeId) -> &'ast ForeignItem {
451 match self.find(id) {
452 Some(NodeForeignItem(item)) => item,
453 _ => panic!("expected foreign item, found {}", self.node_to_string(id))
457 pub fn expect_expr(&self, id: NodeId) -> &'ast Expr {
458 match self.find(id) {
459 Some(NodeExpr(expr)) => expr,
460 _ => panic!("expected expr, found {}", self.node_to_string(id))
464 /// returns the name associated with the given NodeId's AST
465 pub fn get_path_elem(&self, id: NodeId) -> PathElem {
466 let node = self.get(id);
470 ItemMod(_) | ItemForeignMod(_) => {
471 PathMod(item.ident.name)
473 _ => PathName(item.ident.name)
476 NodeForeignItem(i) => PathName(i.ident.name),
477 NodeImplItem(ii) => PathName(ii.ident.name),
478 NodeTraitItem(ti) => PathName(ti.ident.name),
479 NodeVariant(v) => PathName(v.node.name.name),
480 _ => panic!("no path elem for {:?}", node)
484 pub fn with_path<T, F>(&self, id: NodeId, f: F) -> T where
485 F: FnOnce(PathElems) -> T,
487 self.with_path_next(id, LinkedPath::empty(), f)
490 pub fn path_to_string(&self, id: NodeId) -> String {
491 self.with_path(id, |path| path_to_string(path))
494 fn path_to_str_with_ident(&self, id: NodeId, i: Ident) -> String {
495 self.with_path(id, |path| {
496 path_to_string(path.chain(Some(PathName(i.name))))
500 fn with_path_next<T, F>(&self, id: NodeId, next: LinkedPath, f: F) -> T where
501 F: FnOnce(PathElems) -> T,
503 let parent = self.get_parent(id);
504 let parent = match self.find_entry(id) {
505 Some(EntryForeignItem(..)) => {
506 // Anonymous extern items go in the parent scope.
507 self.get_parent(parent)
509 // But tuple struct ctors don't have names, so use the path of its
510 // parent, the struct item. Similarly with closure expressions.
511 Some(EntryStructCtor(..)) | Some(EntryExpr(..)) => {
512 return self.with_path_next(parent, next, f);
517 match self.find_entry(id) {
518 Some(RootInlinedParent(data)) => {
519 f(data.path.iter().cloned().chain(next))
521 _ => f([].iter().cloned().chain(next))
524 self.with_path_next(parent, LinkedPath::from(&LinkedPathNode {
525 node: self.get_path_elem(id),
531 /// Given a node ID, get a list of of attributes associated with the AST
532 /// corresponding to the Node ID
533 pub fn attrs(&self, id: NodeId) -> &'ast [Attribute] {
534 let attrs = match self.find(id) {
535 Some(NodeItem(i)) => Some(&i.attrs[..]),
536 Some(NodeForeignItem(fi)) => Some(&fi.attrs[..]),
537 Some(NodeTraitItem(ref ti)) => Some(&ti.attrs[..]),
538 Some(NodeImplItem(ref ii)) => Some(&ii.attrs[..]),
539 Some(NodeVariant(ref v)) => Some(&v.node.attrs[..]),
540 // unit/tuple structs take the attributes straight from
541 // the struct definition.
542 Some(NodeStructCtor(_)) => {
543 return self.attrs(self.get_parent(id));
550 /// Returns an iterator that yields the node id's with paths that
551 /// match `parts`. (Requires `parts` is non-empty.)
553 /// For example, if given `parts` equal to `["bar", "quux"]`, then
554 /// the iterator will produce node id's for items with paths
555 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
556 /// any other such items it can find in the map.
557 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
558 -> NodesMatchingSuffix<'a, 'ast> {
559 NodesMatchingSuffix {
561 item_name: parts.last().unwrap(),
562 in_which: &parts[..parts.len() - 1],
567 pub fn opt_span(&self, id: NodeId) -> Option<Span> {
568 let sp = match self.find(id) {
569 Some(NodeItem(item)) => item.span,
570 Some(NodeForeignItem(foreign_item)) => foreign_item.span,
571 Some(NodeTraitItem(trait_method)) => trait_method.span,
572 Some(NodeImplItem(ref impl_item)) => impl_item.span,
573 Some(NodeVariant(variant)) => variant.span,
574 Some(NodeExpr(expr)) => expr.span,
575 Some(NodeStmt(stmt)) => stmt.span,
576 Some(NodeArg(pat)) | Some(NodeLocal(pat)) => pat.span,
577 Some(NodePat(pat)) => pat.span,
578 Some(NodeBlock(block)) => block.span,
579 Some(NodeStructCtor(_)) => self.expect_item(self.get_parent(id)).span,
580 Some(NodeTyParam(ty_param)) => ty_param.span,
586 pub fn span(&self, id: NodeId) -> Span {
588 .unwrap_or_else(|| panic!("AstMap.span: could not find span for id {:?}", id))
591 pub fn def_id_span(&self, def_id: DefId, fallback: Span) -> Span {
592 if def_id.krate == LOCAL_CRATE {
593 self.opt_span(def_id.node).unwrap_or(fallback)
599 pub fn node_to_string(&self, id: NodeId) -> String {
600 node_id_to_string(self, id, true)
603 pub fn node_to_user_string(&self, id: NodeId) -> String {
604 node_id_to_string(self, id, false)
608 pub struct NodesMatchingSuffix<'a, 'ast:'a> {
610 item_name: &'a String,
611 in_which: &'a [String],
615 impl<'a, 'ast> NodesMatchingSuffix<'a, 'ast> {
616 /// Returns true only if some suffix of the module path for parent
617 /// matches `self.in_which`.
619 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
620 /// returns true if parent's path ends with the suffix
621 /// `x_0::x_1::...::x_k`.
622 fn suffix_matches(&self, parent: NodeId) -> bool {
623 let mut cursor = parent;
624 for part in self.in_which.iter().rev() {
625 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
626 None => return false,
627 Some((node_id, name)) => (node_id, name),
629 if &part[..] != mod_name.as_str() {
632 cursor = self.map.get_parent(mod_id);
636 // Finds the first mod in parent chain for `id`, along with
639 // If `id` itself is a mod named `m` with parent `p`, then
640 // returns `Some(id, m, p)`. If `id` has no mod in its parent
641 // chain, then returns `None`.
642 fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
646 Some(NodeItem(item)) if item_is_mod(&*item) =>
647 return Some((id, item.ident.name)),
650 let parent = map.get_parent(id);
651 if parent == id { return None }
655 fn item_is_mod(item: &Item) -> bool {
664 // We are looking at some node `n` with a given name and parent
665 // id; do their names match what I am seeking?
666 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
667 name.as_str() == &self.item_name[..] &&
668 self.suffix_matches(parent_of_n)
672 impl<'a, 'ast> Iterator for NodesMatchingSuffix<'a, 'ast> {
675 fn next(&mut self) -> Option<NodeId> {
678 if idx as usize >= self.map.entry_count() {
682 let name = match self.map.find_entry(idx) {
683 Some(EntryItem(_, n)) => n.name(),
684 Some(EntryForeignItem(_, n))=> n.name(),
685 Some(EntryTraitItem(_, n)) => n.name(),
686 Some(EntryImplItem(_, n)) => n.name(),
687 Some(EntryVariant(_, n)) => n.name(),
690 if self.matches_names(self.map.get_parent(idx), name) {
698 fn name(&self) -> Name;
701 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
703 impl Named for Item { fn name(&self) -> Name { self.ident.name } }
704 impl Named for ForeignItem { fn name(&self) -> Name { self.ident.name } }
705 impl Named for Variant_ { fn name(&self) -> Name { self.name.name } }
706 impl Named for TraitItem { fn name(&self) -> Name { self.ident.name } }
707 impl Named for ImplItem { fn name(&self) -> Name { self.ident.name } }
710 fn new_id(&self, id: NodeId) -> NodeId {
713 fn new_def_id(&self, def_id: DefId) -> DefId {
716 fn new_span(&self, span: Span) -> Span {
721 /// A Folder that updates IDs and Span's according to fold_ops.
722 struct IdAndSpanUpdater<F> {
726 impl<F: FoldOps> Folder for IdAndSpanUpdater<F> {
727 fn new_id(&mut self, id: NodeId) -> NodeId {
728 self.fold_ops.new_id(id)
731 fn new_span(&mut self, span: Span) -> Span {
732 self.fold_ops.new_span(span)
736 /// A Visitor that walks over an AST and collects Node's into an AST Map.
737 struct NodeCollector<'ast> {
738 map: Vec<MapEntry<'ast>>,
742 impl<'ast> NodeCollector<'ast> {
743 fn insert_entry(&mut self, id: NodeId, entry: MapEntry<'ast>) {
744 debug!("ast_map: {:?} => {:?}", id, entry);
745 let len = self.map.len();
746 if id as usize >= len {
747 self.map.extend(repeat(NotPresent).take(id as usize - len + 1));
749 self.map[id as usize] = entry;
752 fn insert(&mut self, id: NodeId, node: Node<'ast>) {
753 let entry = MapEntry::from_node(self.parent_node, node);
754 self.insert_entry(id, entry);
757 fn visit_fn_decl(&mut self, decl: &'ast FnDecl) {
758 for a in &decl.inputs {
759 self.insert(a.id, NodeArg(&*a.pat));
764 impl<'ast> Visitor<'ast> for NodeCollector<'ast> {
765 fn visit_item(&mut self, i: &'ast Item) {
766 self.insert(i.id, NodeItem(i));
768 let parent_node = self.parent_node;
769 self.parent_node = i.id;
772 ItemImpl(_, _, _, _, _, ref impl_items) => {
773 for ii in impl_items {
774 self.insert(ii.id, NodeImplItem(ii));
777 ItemEnum(ref enum_definition, _) => {
778 for v in &enum_definition.variants {
779 self.insert(v.node.id, NodeVariant(&**v));
782 ItemForeignMod(ref nm) => {
783 for nitem in &nm.items {
784 self.insert(nitem.id, NodeForeignItem(&**nitem));
787 ItemStruct(ref struct_def, _) => {
788 // If this is a tuple-like struct, register the constructor.
789 match struct_def.ctor_id {
791 self.insert(ctor_id, NodeStructCtor(&**struct_def));
796 ItemTrait(_, _, ref bounds, ref trait_items) => {
797 for b in bounds.iter() {
798 if let TraitTyParamBound(ref t, TraitBoundModifier::None) = *b {
799 self.insert(t.trait_ref.ref_id, NodeItem(i));
803 for ti in trait_items {
804 self.insert(ti.id, NodeTraitItem(ti));
807 ItemUse(ref view_path) => {
808 match view_path.node {
809 ViewPathList(_, ref paths) => {
811 self.insert(path.node.id(), NodeItem(i));
819 visit::walk_item(self, i);
820 self.parent_node = parent_node;
823 fn visit_generics(&mut self, generics: &'ast Generics) {
824 for ty_param in generics.ty_params.iter() {
825 self.insert(ty_param.id, NodeTyParam(ty_param));
828 visit::walk_generics(self, generics);
831 fn visit_trait_item(&mut self, ti: &'ast TraitItem) {
832 let parent_node = self.parent_node;
833 self.parent_node = ti.id;
834 visit::walk_trait_item(self, ti);
835 self.parent_node = parent_node;
838 fn visit_impl_item(&mut self, ii: &'ast ImplItem) {
839 let parent_node = self.parent_node;
840 self.parent_node = ii.id;
842 visit::walk_impl_item(self, ii);
844 self.parent_node = parent_node;
847 fn visit_pat(&mut self, pat: &'ast Pat) {
848 self.insert(pat.id, match pat.node {
849 // Note: this is at least *potentially* a pattern...
850 PatIdent(..) => NodeLocal(pat),
854 let parent_node = self.parent_node;
855 self.parent_node = pat.id;
856 visit::walk_pat(self, pat);
857 self.parent_node = parent_node;
860 fn visit_expr(&mut self, expr: &'ast Expr) {
861 self.insert(expr.id, NodeExpr(expr));
862 let parent_node = self.parent_node;
863 self.parent_node = expr.id;
864 visit::walk_expr(self, expr);
865 self.parent_node = parent_node;
868 fn visit_stmt(&mut self, stmt: &'ast Stmt) {
869 let id = ast_util::stmt_id(stmt);
870 self.insert(id, NodeStmt(stmt));
871 let parent_node = self.parent_node;
872 self.parent_node = id;
873 visit::walk_stmt(self, stmt);
874 self.parent_node = parent_node;
877 fn visit_fn(&mut self, fk: visit::FnKind<'ast>, fd: &'ast FnDecl,
878 b: &'ast Block, s: Span, id: NodeId) {
879 let parent_node = self.parent_node;
880 self.parent_node = id;
881 self.visit_fn_decl(fd);
882 visit::walk_fn(self, fk, fd, b, s);
883 self.parent_node = parent_node;
886 fn visit_ty(&mut self, ty: &'ast Ty) {
887 let parent_node = self.parent_node;
888 self.parent_node = ty.id;
890 TyBareFn(ref fd) => {
891 self.visit_fn_decl(&*fd.decl);
895 visit::walk_ty(self, ty);
896 self.parent_node = parent_node;
899 fn visit_block(&mut self, block: &'ast Block) {
900 self.insert(block.id, NodeBlock(block));
901 let parent_node = self.parent_node;
902 self.parent_node = block.id;
903 visit::walk_block(self, block);
904 self.parent_node = parent_node;
907 fn visit_lifetime_ref(&mut self, lifetime: &'ast Lifetime) {
908 self.insert(lifetime.id, NodeLifetime(lifetime));
911 fn visit_lifetime_def(&mut self, def: &'ast LifetimeDef) {
912 self.visit_lifetime_ref(&def.lifetime);
916 pub fn map_crate<'ast, F: FoldOps>(forest: &'ast mut Forest, fold_ops: F) -> Map<'ast> {
917 // Replace the crate with an empty one to take it out.
918 let krate = mem::replace(&mut forest.krate, Crate {
925 exported_macros: vec![],
928 forest.krate = IdAndSpanUpdater { fold_ops: fold_ops }.fold_crate(krate);
930 let mut collector = NodeCollector {
932 parent_node: CRATE_NODE_ID,
934 collector.insert_entry(CRATE_NODE_ID, RootCrate);
935 visit::walk_crate(&mut collector, &forest.krate);
936 let map = collector.map;
938 if log_enabled!(::log::DEBUG) {
939 // This only makes sense for ordered stores; note the
940 // enumerate to count the number of entries.
941 let (entries_less_1, _) = map.iter().filter(|&x| {
946 }).enumerate().last().expect("AST map was empty after folding?");
948 let entries = entries_less_1 + 1;
949 let vector_length = map.len();
950 debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
951 entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
956 map: RefCell::new(map)
960 /// Used for items loaded from external crate that are being inlined into this
961 /// crate. The `path` should be the path to the item but should not include
963 pub fn map_decoded_item<'ast, F: FoldOps>(map: &Map<'ast>,
967 -> &'ast InlinedItem {
968 let mut fld = IdAndSpanUpdater { fold_ops: fold_ops };
970 IIItem(i) => IIItem(fld.fold_item(i).expect_one("expected one item")),
971 IITraitItem(d, ti) => {
972 IITraitItem(fld.fold_ops.new_def_id(d),
973 fld.fold_trait_item(ti).expect_one("expected one trait item"))
975 IIImplItem(d, ii) => {
976 IIImplItem(fld.fold_ops.new_def_id(d),
977 fld.fold_impl_item(ii).expect_one("expected one impl item"))
979 IIForeign(i) => IIForeign(fld.fold_foreign_item(i))
982 let ii_parent = map.forest.inlined_items.alloc(InlinedParent {
987 let ii_parent_id = fld.new_id(DUMMY_NODE_ID);
988 let mut collector = NodeCollector {
989 map: mem::replace(&mut *map.map.borrow_mut(), vec![]),
990 parent_node: ii_parent_id,
992 collector.insert_entry(ii_parent_id, RootInlinedParent(ii_parent));
993 visit::walk_inlined_item(&mut collector, &ii_parent.ii);
995 // Methods get added to the AST map when their impl is visited. Since we
996 // don't decode and instantiate the impl, but just the method, we have to
997 // add it to the table now. Likewise with foreign items.
1000 IITraitItem(_, ref ti) => {
1001 collector.insert(ti.id, NodeTraitItem(ti));
1003 IIImplItem(_, ref ii) => {
1004 collector.insert(ii.id, NodeImplItem(ii));
1006 IIForeign(ref i) => {
1007 collector.insert(i.id, NodeForeignItem(i));
1010 *map.map.borrow_mut() = collector.map;
1014 pub trait NodePrinter {
1015 fn print_node(&mut self, node: &Node) -> io::Result<()>;
1018 impl<'a> NodePrinter for pprust::State<'a> {
1019 fn print_node(&mut self, node: &Node) -> io::Result<()> {
1021 NodeItem(a) => self.print_item(&*a),
1022 NodeForeignItem(a) => self.print_foreign_item(&*a),
1023 NodeTraitItem(a) => self.print_trait_item(a),
1024 NodeImplItem(a) => self.print_impl_item(a),
1025 NodeVariant(a) => self.print_variant(&*a),
1026 NodeExpr(a) => self.print_expr(&*a),
1027 NodeStmt(a) => self.print_stmt(&*a),
1028 NodePat(a) => self.print_pat(&*a),
1029 NodeBlock(a) => self.print_block(&*a),
1030 NodeLifetime(a) => self.print_lifetime(&*a),
1031 NodeTyParam(_) => panic!("cannot print TyParam"),
1032 // these cases do not carry enough information in the
1033 // ast_map to reconstruct their full structure for pretty
1035 NodeLocal(_) => panic!("cannot print isolated Local"),
1036 NodeArg(_) => panic!("cannot print isolated Arg"),
1037 NodeStructCtor(_) => panic!("cannot print isolated StructCtor"),
1042 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
1043 let id_str = format!(" (id={})", id);
1044 let id_str = if include_id { &id_str[..] } else { "" };
1046 match map.find(id) {
1047 Some(NodeItem(item)) => {
1048 let path_str = map.path_to_str_with_ident(id, item.ident);
1049 let item_str = match item.node {
1050 ItemExternCrate(..) => "extern crate",
1051 ItemUse(..) => "use",
1052 ItemStatic(..) => "static",
1053 ItemConst(..) => "const",
1055 ItemMod(..) => "mod",
1056 ItemForeignMod(..) => "foreign mod",
1058 ItemEnum(..) => "enum",
1059 ItemStruct(..) => "struct",
1060 ItemTrait(..) => "trait",
1061 ItemImpl(..) => "impl",
1062 ItemDefaultImpl(..) => "default impl",
1063 ItemMac(..) => "macro"
1065 format!("{} {}{}", item_str, path_str, id_str)
1067 Some(NodeForeignItem(item)) => {
1068 let path_str = map.path_to_str_with_ident(id, item.ident);
1069 format!("foreign item {}{}", path_str, id_str)
1071 Some(NodeImplItem(ii)) => {
1073 ConstImplItem(..) => {
1074 format!("assoc const {} in {}{}",
1076 map.path_to_string(id),
1079 MethodImplItem(..) => {
1080 format!("method {} in {}{}",
1082 map.path_to_string(id), id_str)
1084 TypeImplItem(_) => {
1085 format!("assoc type {} in {}{}",
1087 map.path_to_string(id),
1090 MacImplItem(ref mac) => {
1091 format!("method macro {}{}",
1092 pprust::mac_to_string(mac), id_str)
1096 Some(NodeTraitItem(ti)) => {
1097 let kind = match ti.node {
1098 ConstTraitItem(..) => "assoc constant",
1099 MethodTraitItem(..) => "trait method",
1100 TypeTraitItem(..) => "assoc type",
1103 format!("{} {} in {}{}",
1106 map.path_to_string(id),
1109 Some(NodeVariant(ref variant)) => {
1110 format!("variant {} in {}{}",
1112 map.path_to_string(id), id_str)
1114 Some(NodeExpr(ref expr)) => {
1115 format!("expr {}{}", pprust::expr_to_string(&**expr), id_str)
1117 Some(NodeStmt(ref stmt)) => {
1118 format!("stmt {}{}", pprust::stmt_to_string(&**stmt), id_str)
1120 Some(NodeArg(ref pat)) => {
1121 format!("arg {}{}", pprust::pat_to_string(&**pat), id_str)
1123 Some(NodeLocal(ref pat)) => {
1124 format!("local {}{}", pprust::pat_to_string(&**pat), id_str)
1126 Some(NodePat(ref pat)) => {
1127 format!("pat {}{}", pprust::pat_to_string(&**pat), id_str)
1129 Some(NodeBlock(ref block)) => {
1130 format!("block {}{}", pprust::block_to_string(&**block), id_str)
1132 Some(NodeStructCtor(_)) => {
1133 format!("struct_ctor {}{}", map.path_to_string(id), id_str)
1135 Some(NodeLifetime(ref l)) => {
1136 format!("lifetime {}{}",
1137 pprust::lifetime_to_string(&**l), id_str)
1139 Some(NodeTyParam(ref ty_param)) => {
1140 format!("typaram {:?}{}", ty_param, id_str)
1143 format!("unknown node{}", id_str)