1 // Copyright 2012-2015 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::*;
15 use metadata::inline::InlinedItem;
16 use metadata::inline::InlinedItem as II;
17 use middle::def_id::DefId;
20 use syntax::ast::{Name, NodeId, Ident, CRATE_NODE_ID, DUMMY_NODE_ID};
21 use syntax::codemap::{Span, Spanned};
22 use syntax::parse::token;
24 use rustc_front::hir::*;
25 use rustc_front::fold::Folder;
26 use rustc_front::visit::{self, Visitor};
27 use rustc_front::util;
28 use rustc_front::print::pprust;
30 use arena::TypedArena;
31 use std::cell::RefCell;
34 use std::iter::{self, repeat};
40 #[derive(Clone, Copy, PartialEq, Debug)]
47 pub fn name(&self) -> Name {
49 PathMod(name) | PathName(name) => name
54 impl fmt::Display for PathElem {
55 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
56 write!(f, "{}", self.name())
61 pub struct LinkedPathNode<'a> {
66 #[derive(Copy, Clone)]
67 pub struct LinkedPath<'a>(Option<&'a LinkedPathNode<'a>>);
69 impl<'a> LinkedPath<'a> {
70 pub fn empty() -> LinkedPath<'a> {
74 pub fn from(node: &'a LinkedPathNode) -> LinkedPath<'a> {
75 LinkedPath(Some(node))
79 impl<'a> Iterator for LinkedPath<'a> {
82 fn next(&mut self) -> Option<PathElem> {
93 /// The type of the iterator used by with_path.
94 pub type PathElems<'a, 'b> = iter::Chain<iter::Cloned<slice::Iter<'a, PathElem>>, LinkedPath<'b>>;
96 pub fn path_to_string<PI: Iterator<Item=PathElem>>(path: PI) -> String {
97 let itr = token::get_ident_interner();
99 path.fold(String::new(), |mut s, e| {
100 let e = itr.get(e.name());
109 #[derive(Copy, Clone, Debug)]
110 pub enum Node<'ast> {
111 NodeItem(&'ast Item),
112 NodeForeignItem(&'ast ForeignItem),
113 NodeTraitItem(&'ast TraitItem),
114 NodeImplItem(&'ast ImplItem),
115 NodeVariant(&'ast Variant),
116 NodeExpr(&'ast Expr),
117 NodeStmt(&'ast Stmt),
119 NodeLocal(&'ast Pat),
121 NodeBlock(&'ast Block),
123 /// NodeStructCtor represents a tuple struct.
124 NodeStructCtor(&'ast StructDef),
126 NodeLifetime(&'ast Lifetime),
127 NodeTyParam(&'ast TyParam)
130 /// Represents an entry and its parent NodeID.
131 /// The odd layout is to bring down the total size.
132 #[derive(Copy, Debug)]
133 enum MapEntry<'ast> {
134 /// Placeholder for holes in the map.
137 /// All the node types, with a parent ID.
138 EntryItem(NodeId, &'ast Item),
139 EntryForeignItem(NodeId, &'ast ForeignItem),
140 EntryTraitItem(NodeId, &'ast TraitItem),
141 EntryImplItem(NodeId, &'ast ImplItem),
142 EntryVariant(NodeId, &'ast Variant),
143 EntryExpr(NodeId, &'ast Expr),
144 EntryStmt(NodeId, &'ast Stmt),
145 EntryArg(NodeId, &'ast Pat),
146 EntryLocal(NodeId, &'ast Pat),
147 EntryPat(NodeId, &'ast Pat),
148 EntryBlock(NodeId, &'ast Block),
149 EntryStructCtor(NodeId, &'ast StructDef),
150 EntryLifetime(NodeId, &'ast Lifetime),
151 EntryTyParam(NodeId, &'ast TyParam),
153 /// Roots for node trees.
155 RootInlinedParent(&'ast InlinedParent)
158 impl<'ast> Clone for MapEntry<'ast> {
159 fn clone(&self) -> MapEntry<'ast> {
165 pub struct InlinedParent {
170 impl<'ast> MapEntry<'ast> {
171 fn from_node(p: NodeId, node: Node<'ast>) -> MapEntry<'ast> {
173 NodeItem(n) => EntryItem(p, n),
174 NodeForeignItem(n) => EntryForeignItem(p, n),
175 NodeTraitItem(n) => EntryTraitItem(p, n),
176 NodeImplItem(n) => EntryImplItem(p, n),
177 NodeVariant(n) => EntryVariant(p, n),
178 NodeExpr(n) => EntryExpr(p, n),
179 NodeStmt(n) => EntryStmt(p, n),
180 NodeArg(n) => EntryArg(p, n),
181 NodeLocal(n) => EntryLocal(p, n),
182 NodePat(n) => EntryPat(p, n),
183 NodeBlock(n) => EntryBlock(p, n),
184 NodeStructCtor(n) => EntryStructCtor(p, n),
185 NodeLifetime(n) => EntryLifetime(p, n),
186 NodeTyParam(n) => EntryTyParam(p, n),
190 fn parent_node(self) -> Option<NodeId> {
192 EntryItem(id, _) => id,
193 EntryForeignItem(id, _) => id,
194 EntryTraitItem(id, _) => id,
195 EntryImplItem(id, _) => id,
196 EntryVariant(id, _) => id,
197 EntryExpr(id, _) => id,
198 EntryStmt(id, _) => id,
199 EntryArg(id, _) => id,
200 EntryLocal(id, _) => id,
201 EntryPat(id, _) => id,
202 EntryBlock(id, _) => id,
203 EntryStructCtor(id, _) => id,
204 EntryLifetime(id, _) => id,
205 EntryTyParam(id, _) => id,
210 fn to_node(self) -> Option<Node<'ast>> {
212 EntryItem(_, n) => NodeItem(n),
213 EntryForeignItem(_, n) => NodeForeignItem(n),
214 EntryTraitItem(_, n) => NodeTraitItem(n),
215 EntryImplItem(_, n) => NodeImplItem(n),
216 EntryVariant(_, n) => NodeVariant(n),
217 EntryExpr(_, n) => NodeExpr(n),
218 EntryStmt(_, n) => NodeStmt(n),
219 EntryArg(_, n) => NodeArg(n),
220 EntryLocal(_, n) => NodeLocal(n),
221 EntryPat(_, n) => NodePat(n),
222 EntryBlock(_, n) => NodeBlock(n),
223 EntryStructCtor(_, n) => NodeStructCtor(n),
224 EntryLifetime(_, n) => NodeLifetime(n),
225 EntryTyParam(_, n) => NodeTyParam(n),
231 /// Stores a crate and any number of inlined items from other crates.
234 inlined_items: TypedArena<InlinedParent>
238 pub fn new(krate: Crate) -> Forest {
241 inlined_items: TypedArena::new()
245 pub fn krate<'ast>(&'ast self) -> &'ast Crate {
250 /// Represents a mapping from Node IDs to AST elements and their parent
253 pub struct Map<'ast> {
254 /// The backing storage for all the AST nodes.
255 pub forest: &'ast Forest,
257 /// NodeIds are sequential integers from 0, so we can be
258 /// super-compact by storing them in a vector. Not everything with
259 /// a NodeId is in the map, but empirically the occupancy is about
260 /// 75-80%, so there's not too much overhead (certainly less than
261 /// a hashmap, since they (at the time of writing) have a maximum
262 /// of 75% occupancy).
264 /// Also, indexing is pretty quick when you've got a vector and
265 /// plain old integers.
266 map: RefCell<Vec<MapEntry<'ast>>>
269 impl<'ast> Map<'ast> {
270 fn entry_count(&self) -> usize {
271 self.map.borrow().len()
274 fn find_entry(&self, id: NodeId) -> Option<MapEntry<'ast>> {
275 self.map.borrow().get(id as usize).cloned()
278 pub fn krate(&self) -> &'ast Crate {
282 /// Retrieve the Node corresponding to `id`, panicking if it cannot
284 pub fn get(&self, id: NodeId) -> Node<'ast> {
285 match self.find(id) {
287 None => panic!("couldn't find node id {} in the AST map", id)
291 /// Retrieve the Node corresponding to `id`, returning None if
293 pub fn find(&self, id: NodeId) -> Option<Node<'ast>> {
294 self.find_entry(id).and_then(|x| x.to_node())
297 /// Similar to get_parent, returns the parent node id or id if there is no
299 /// This function returns the immediate parent in the AST, whereas get_parent
300 /// returns the enclosing item. Note that this might not be the actual parent
301 /// node in the AST - some kinds of nodes are not in the map and these will
302 /// never appear as the parent_node. So you can always walk the parent_nodes
303 /// from a node to the root of the ast (unless you get the same id back here
304 /// that can happen if the id is not in the map itself or is just weird).
305 pub fn get_parent_node(&self, id: NodeId) -> NodeId {
306 self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
309 /// If there is some error when walking the parents (e.g., a node does not
310 /// have a parent in the map or a node can't be found), then we return the
311 /// last good node id we found. Note that reaching the crate root (id == 0),
312 /// is not an error, since items in the crate module have the crate root as
314 fn walk_parent_nodes<F>(&self, start_id: NodeId, found: F) -> Result<NodeId, NodeId>
315 where F: Fn(&Node<'ast>) -> bool
317 let mut id = start_id;
319 let parent_node = self.get_parent_node(id);
320 if parent_node == 0 {
323 if parent_node == id {
327 let node = self.find_entry(parent_node);
331 let node = node.unwrap().to_node();
335 return Ok(parent_node);
339 return Err(parent_node);
346 /// Retrieve the NodeId for `id`'s parent item, or `id` itself if no
347 /// parent item is in this map. The "parent item" is the closest parent node
348 /// in the AST which is recorded by the map and is an item, either an item
349 /// in a module, trait, or impl.
350 pub fn get_parent(&self, id: NodeId) -> NodeId {
351 match self.walk_parent_nodes(id, |node| match *node {
355 NodeImplItem(_) => true,
363 /// Returns the nearest enclosing scope. A scope is an item or block.
364 /// FIXME it is not clear to me that all items qualify as scopes - statics
365 /// and associated types probably shouldn't, for example. Behaviour in this
366 /// regard should be expected to be highly unstable.
367 pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
368 match self.walk_parent_nodes(id, |node| match *node {
373 NodeBlock(_) => true,
381 pub fn get_parent_did(&self, id: NodeId) -> DefId {
382 let parent = self.get_parent(id);
383 match self.find_entry(parent) {
384 Some(RootInlinedParent(&InlinedParent {ii: II::TraitItem(did, _), ..})) => did,
385 Some(RootInlinedParent(&InlinedParent {ii: II::ImplItem(did, _), ..})) => did,
386 _ => DefId::local(parent)
390 pub fn get_foreign_abi(&self, id: NodeId) -> abi::Abi {
391 let parent = self.get_parent(id);
392 let abi = match self.find_entry(parent) {
393 Some(EntryItem(_, i)) => {
395 ItemForeignMod(ref nm) => Some(nm.abi),
399 /// Wrong but OK, because the only inlined foreign items are intrinsics.
400 Some(RootInlinedParent(_)) => Some(abi::RustIntrinsic),
405 None => panic!("expected foreign mod or inlined parent, found {}",
406 self.node_to_string(parent))
410 pub fn get_foreign_vis(&self, id: NodeId) -> Visibility {
411 let vis = self.expect_foreign_item(id).vis;
412 match self.find(self.get_parent(id)) {
413 Some(NodeItem(i)) => vis.inherit_from(i.vis),
418 pub fn expect_item(&self, id: NodeId) -> &'ast Item {
419 match self.find(id) {
420 Some(NodeItem(item)) => item,
421 _ => panic!("expected item, found {}", self.node_to_string(id))
425 pub fn expect_trait_item(&self, id: NodeId) -> &'ast TraitItem {
426 match self.find(id) {
427 Some(NodeTraitItem(item)) => item,
428 _ => panic!("expected trait item, found {}", self.node_to_string(id))
432 pub fn expect_struct(&self, id: NodeId) -> &'ast StructDef {
433 match self.find(id) {
434 Some(NodeItem(i)) => {
436 ItemStruct(ref struct_def, _) => &**struct_def,
437 _ => panic!("struct ID bound to non-struct")
440 Some(NodeVariant(variant)) => {
441 match variant.node.kind {
442 StructVariantKind(ref struct_def) => &**struct_def,
443 _ => panic!("struct ID bound to enum variant that isn't struct-like"),
446 _ => panic!(format!("expected struct, found {}", self.node_to_string(id))),
450 pub fn expect_variant(&self, id: NodeId) -> &'ast Variant {
451 match self.find(id) {
452 Some(NodeVariant(variant)) => variant,
453 _ => panic!(format!("expected variant, found {}", self.node_to_string(id))),
457 pub fn expect_foreign_item(&self, id: NodeId) -> &'ast ForeignItem {
458 match self.find(id) {
459 Some(NodeForeignItem(item)) => item,
460 _ => panic!("expected foreign item, found {}", self.node_to_string(id))
464 pub fn expect_expr(&self, id: NodeId) -> &'ast Expr {
465 match self.find(id) {
466 Some(NodeExpr(expr)) => expr,
467 _ => panic!("expected expr, found {}", self.node_to_string(id))
471 /// returns the name associated with the given NodeId's AST
472 pub fn get_path_elem(&self, id: NodeId) -> PathElem {
473 let node = self.get(id);
477 ItemMod(_) | ItemForeignMod(_) => {
478 PathMod(item.ident.name)
480 _ => PathName(item.ident.name)
483 NodeForeignItem(i) => PathName(i.ident.name),
484 NodeImplItem(ii) => PathName(ii.ident.name),
485 NodeTraitItem(ti) => PathName(ti.ident.name),
486 NodeVariant(v) => PathName(v.node.name.name),
487 NodeLifetime(lt) => PathName(lt.name),
488 _ => panic!("no path elem for {:?}", node)
492 pub fn with_path<T, F>(&self, id: NodeId, f: F) -> T where
493 F: FnOnce(PathElems) -> T,
495 self.with_path_next(id, LinkedPath::empty(), f)
498 pub fn path_to_string(&self, id: NodeId) -> String {
499 self.with_path(id, |path| path_to_string(path))
502 fn path_to_str_with_ident(&self, id: NodeId, i: Ident) -> String {
503 self.with_path(id, |path| {
504 path_to_string(path.chain(Some(PathName(i.name))))
508 fn with_path_next<T, F>(&self, id: NodeId, next: LinkedPath, f: F) -> T where
509 F: FnOnce(PathElems) -> T,
511 let parent = self.get_parent(id);
512 let parent = match self.find_entry(id) {
513 Some(EntryForeignItem(..)) => {
514 // Anonymous extern items go in the parent scope.
515 self.get_parent(parent)
517 // But tuple struct ctors don't have names, so use the path of its
518 // parent, the struct item. Similarly with closure expressions.
519 Some(EntryStructCtor(..)) | Some(EntryExpr(..)) => {
520 return self.with_path_next(parent, next, f);
525 match self.find_entry(id) {
526 Some(RootInlinedParent(data)) => {
527 f(data.path.iter().cloned().chain(next))
529 _ => f([].iter().cloned().chain(next))
532 self.with_path_next(parent, LinkedPath::from(&LinkedPathNode {
533 node: self.get_path_elem(id),
539 /// Given a node ID, get a list of of attributes associated with the AST
540 /// corresponding to the Node ID
541 pub fn attrs(&self, id: NodeId) -> &'ast [Attribute] {
542 let attrs = match self.find(id) {
543 Some(NodeItem(i)) => Some(&i.attrs[..]),
544 Some(NodeForeignItem(fi)) => Some(&fi.attrs[..]),
545 Some(NodeTraitItem(ref ti)) => Some(&ti.attrs[..]),
546 Some(NodeImplItem(ref ii)) => Some(&ii.attrs[..]),
547 Some(NodeVariant(ref v)) => Some(&v.node.attrs[..]),
548 // unit/tuple structs take the attributes straight from
549 // the struct definition.
550 Some(NodeStructCtor(_)) => {
551 return self.attrs(self.get_parent(id));
558 /// Returns an iterator that yields the node id's with paths that
559 /// match `parts`. (Requires `parts` is non-empty.)
561 /// For example, if given `parts` equal to `["bar", "quux"]`, then
562 /// the iterator will produce node id's for items with paths
563 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
564 /// any other such items it can find in the map.
565 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
566 -> NodesMatchingSuffix<'a, 'ast> {
567 NodesMatchingSuffix {
569 item_name: parts.last().unwrap(),
570 in_which: &parts[..parts.len() - 1],
575 pub fn opt_span(&self, id: NodeId) -> Option<Span> {
576 let sp = match self.find(id) {
577 Some(NodeItem(item)) => item.span,
578 Some(NodeForeignItem(foreign_item)) => foreign_item.span,
579 Some(NodeTraitItem(trait_method)) => trait_method.span,
580 Some(NodeImplItem(ref impl_item)) => impl_item.span,
581 Some(NodeVariant(variant)) => variant.span,
582 Some(NodeExpr(expr)) => expr.span,
583 Some(NodeStmt(stmt)) => stmt.span,
584 Some(NodeArg(pat)) | Some(NodeLocal(pat)) => pat.span,
585 Some(NodePat(pat)) => pat.span,
586 Some(NodeBlock(block)) => block.span,
587 Some(NodeStructCtor(_)) => self.expect_item(self.get_parent(id)).span,
588 Some(NodeTyParam(ty_param)) => ty_param.span,
594 pub fn span(&self, id: NodeId) -> Span {
596 .unwrap_or_else(|| panic!("AstMap.span: could not find span for id {:?}", id))
599 pub fn def_id_span(&self, def_id: DefId, fallback: Span) -> Span {
600 if def_id.is_local() {
601 self.opt_span(def_id.node).unwrap_or(fallback)
607 pub fn node_to_string(&self, id: NodeId) -> String {
608 node_id_to_string(self, id, true)
611 pub fn node_to_user_string(&self, id: NodeId) -> String {
612 node_id_to_string(self, id, false)
616 pub struct NodesMatchingSuffix<'a, 'ast:'a> {
618 item_name: &'a String,
619 in_which: &'a [String],
623 impl<'a, 'ast> NodesMatchingSuffix<'a, 'ast> {
624 /// Returns true only if some suffix of the module path for parent
625 /// matches `self.in_which`.
627 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
628 /// returns true if parent's path ends with the suffix
629 /// `x_0::x_1::...::x_k`.
630 fn suffix_matches(&self, parent: NodeId) -> bool {
631 let mut cursor = parent;
632 for part in self.in_which.iter().rev() {
633 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
634 None => return false,
635 Some((node_id, name)) => (node_id, name),
637 if &part[..] != mod_name.as_str() {
640 cursor = self.map.get_parent(mod_id);
644 // Finds the first mod in parent chain for `id`, along with
647 // If `id` itself is a mod named `m` with parent `p`, then
648 // returns `Some(id, m, p)`. If `id` has no mod in its parent
649 // chain, then returns `None`.
650 fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
654 Some(NodeItem(item)) if item_is_mod(&*item) =>
655 return Some((id, item.ident.name)),
658 let parent = map.get_parent(id);
659 if parent == id { return None }
663 fn item_is_mod(item: &Item) -> bool {
672 // We are looking at some node `n` with a given name and parent
673 // id; do their names match what I am seeking?
674 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
675 name.as_str() == &self.item_name[..] &&
676 self.suffix_matches(parent_of_n)
680 impl<'a, 'ast> Iterator for NodesMatchingSuffix<'a, 'ast> {
683 fn next(&mut self) -> Option<NodeId> {
686 if idx as usize >= self.map.entry_count() {
690 let name = match self.map.find_entry(idx) {
691 Some(EntryItem(_, n)) => n.name(),
692 Some(EntryForeignItem(_, n))=> n.name(),
693 Some(EntryTraitItem(_, n)) => n.name(),
694 Some(EntryImplItem(_, n)) => n.name(),
695 Some(EntryVariant(_, n)) => n.name(),
698 if self.matches_names(self.map.get_parent(idx), name) {
706 fn name(&self) -> Name;
709 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
711 impl Named for Item { fn name(&self) -> Name { self.ident.name } }
712 impl Named for ForeignItem { fn name(&self) -> Name { self.ident.name } }
713 impl Named for Variant_ { fn name(&self) -> Name { self.name.name } }
714 impl Named for TraitItem { fn name(&self) -> Name { self.ident.name } }
715 impl Named for ImplItem { fn name(&self) -> Name { self.ident.name } }
718 fn new_id(&self, id: NodeId) -> NodeId {
721 fn new_def_id(&self, def_id: DefId) -> DefId {
724 fn new_span(&self, span: Span) -> Span {
729 /// A Folder that updates IDs and Span's according to fold_ops.
730 struct IdAndSpanUpdater<F> {
734 impl<F: FoldOps> Folder for IdAndSpanUpdater<F> {
735 fn new_id(&mut self, id: NodeId) -> NodeId {
736 self.fold_ops.new_id(id)
739 fn new_span(&mut self, span: Span) -> Span {
740 self.fold_ops.new_span(span)
744 /// A Visitor that walks over an AST and collects Node's into an AST Map.
745 struct NodeCollector<'ast> {
746 map: Vec<MapEntry<'ast>>,
750 impl<'ast> NodeCollector<'ast> {
751 fn insert_entry(&mut self, id: NodeId, entry: MapEntry<'ast>) {
752 debug!("ast_map: {:?} => {:?}", id, entry);
753 let len = self.map.len();
754 if id as usize >= len {
755 self.map.extend(repeat(NotPresent).take(id as usize - len + 1));
757 self.map[id as usize] = entry;
760 fn insert(&mut self, id: NodeId, node: Node<'ast>) {
761 let entry = MapEntry::from_node(self.parent_node, node);
762 self.insert_entry(id, entry);
765 fn visit_fn_decl(&mut self, decl: &'ast FnDecl) {
766 for a in &decl.inputs {
767 self.insert(a.id, NodeArg(&*a.pat));
772 impl<'ast> Visitor<'ast> for NodeCollector<'ast> {
773 fn visit_item(&mut self, i: &'ast Item) {
774 self.insert(i.id, NodeItem(i));
776 let parent_node = self.parent_node;
777 self.parent_node = i.id;
780 ItemImpl(_, _, _, _, _, ref impl_items) => {
781 for ii in impl_items {
782 self.insert(ii.id, NodeImplItem(ii));
785 ItemEnum(ref enum_definition, _) => {
786 for v in &enum_definition.variants {
787 self.insert(v.node.id, NodeVariant(&**v));
790 ItemForeignMod(ref nm) => {
791 for nitem in &nm.items {
792 self.insert(nitem.id, NodeForeignItem(&**nitem));
795 ItemStruct(ref struct_def, _) => {
796 // If this is a tuple-like struct, register the constructor.
797 match struct_def.ctor_id {
799 self.insert(ctor_id, NodeStructCtor(&**struct_def));
804 ItemTrait(_, _, ref bounds, ref trait_items) => {
805 for b in bounds.iter() {
806 if let TraitTyParamBound(ref t, TraitBoundModifier::None) = *b {
807 self.insert(t.trait_ref.ref_id, NodeItem(i));
811 for ti in trait_items {
812 self.insert(ti.id, NodeTraitItem(ti));
815 ItemUse(ref view_path) => {
816 match view_path.node {
817 ViewPathList(_, ref paths) => {
819 self.insert(path.node.id(), NodeItem(i));
827 visit::walk_item(self, i);
828 self.parent_node = parent_node;
831 fn visit_generics(&mut self, generics: &'ast Generics) {
832 for ty_param in generics.ty_params.iter() {
833 self.insert(ty_param.id, NodeTyParam(ty_param));
836 visit::walk_generics(self, generics);
839 fn visit_trait_item(&mut self, ti: &'ast TraitItem) {
840 let parent_node = self.parent_node;
841 self.parent_node = ti.id;
842 visit::walk_trait_item(self, ti);
843 self.parent_node = parent_node;
846 fn visit_impl_item(&mut self, ii: &'ast ImplItem) {
847 let parent_node = self.parent_node;
848 self.parent_node = ii.id;
850 visit::walk_impl_item(self, ii);
852 self.parent_node = parent_node;
855 fn visit_pat(&mut self, pat: &'ast Pat) {
856 self.insert(pat.id, match pat.node {
857 // Note: this is at least *potentially* a pattern...
858 PatIdent(..) => NodeLocal(pat),
862 let parent_node = self.parent_node;
863 self.parent_node = pat.id;
864 visit::walk_pat(self, pat);
865 self.parent_node = parent_node;
868 fn visit_expr(&mut self, expr: &'ast Expr) {
869 self.insert(expr.id, NodeExpr(expr));
870 let parent_node = self.parent_node;
871 self.parent_node = expr.id;
872 visit::walk_expr(self, expr);
873 self.parent_node = parent_node;
876 fn visit_stmt(&mut self, stmt: &'ast Stmt) {
877 let id = util::stmt_id(stmt);
878 self.insert(id, NodeStmt(stmt));
879 let parent_node = self.parent_node;
880 self.parent_node = id;
881 visit::walk_stmt(self, stmt);
882 self.parent_node = parent_node;
885 fn visit_fn(&mut self, fk: visit::FnKind<'ast>, fd: &'ast FnDecl,
886 b: &'ast Block, s: Span, id: NodeId) {
887 let parent_node = self.parent_node;
888 self.parent_node = id;
889 self.visit_fn_decl(fd);
890 visit::walk_fn(self, fk, fd, b, s);
891 self.parent_node = parent_node;
894 fn visit_ty(&mut self, ty: &'ast Ty) {
895 let parent_node = self.parent_node;
896 self.parent_node = ty.id;
898 TyBareFn(ref fd) => {
899 self.visit_fn_decl(&*fd.decl);
903 visit::walk_ty(self, ty);
904 self.parent_node = parent_node;
907 fn visit_block(&mut self, block: &'ast Block) {
908 self.insert(block.id, NodeBlock(block));
909 let parent_node = self.parent_node;
910 self.parent_node = block.id;
911 visit::walk_block(self, block);
912 self.parent_node = parent_node;
915 fn visit_lifetime_ref(&mut self, lifetime: &'ast Lifetime) {
916 self.insert(lifetime.id, NodeLifetime(lifetime));
919 fn visit_lifetime_def(&mut self, def: &'ast LifetimeDef) {
920 self.visit_lifetime_ref(&def.lifetime);
924 pub fn map_crate<'ast>(forest: &'ast mut Forest) -> Map<'ast> {
925 let mut collector = NodeCollector {
927 parent_node: CRATE_NODE_ID,
929 collector.insert_entry(CRATE_NODE_ID, RootCrate);
930 visit::walk_crate(&mut collector, &forest.krate);
931 let map = collector.map;
933 if log_enabled!(::log::DEBUG) {
934 // This only makes sense for ordered stores; note the
935 // enumerate to count the number of entries.
936 let (entries_less_1, _) = map.iter().filter(|&x| {
941 }).enumerate().last().expect("AST map was empty after folding?");
943 let entries = entries_less_1 + 1;
944 let vector_length = map.len();
945 debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
946 entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
951 map: RefCell::new(map)
955 /// Used for items loaded from external crate that are being inlined into this
956 /// crate. The `path` should be the path to the item but should not include
958 pub fn map_decoded_item<'ast, F: FoldOps>(map: &Map<'ast>,
962 -> &'ast InlinedItem {
963 let mut fld = IdAndSpanUpdater { fold_ops: fold_ops };
965 II::Item(i) => II::Item(fld.fold_item(i).expect_one("expected one item")),
966 II::TraitItem(d, ti) => {
967 II::TraitItem(fld.fold_ops.new_def_id(d),
968 fld.fold_trait_item(ti).expect_one("expected one trait item"))
970 II::ImplItem(d, ii) => {
971 II::ImplItem(fld.fold_ops.new_def_id(d),
972 fld.fold_impl_item(ii).expect_one("expected one impl item"))
974 II::Foreign(i) => II::Foreign(fld.fold_foreign_item(i))
977 let ii_parent = map.forest.inlined_items.alloc(InlinedParent {
982 let ii_parent_id = fld.new_id(DUMMY_NODE_ID);
983 let mut collector = NodeCollector {
984 map: mem::replace(&mut *map.map.borrow_mut(), vec![]),
985 parent_node: ii_parent_id,
987 collector.insert_entry(ii_parent_id, RootInlinedParent(ii_parent));
988 ii_parent.ii.visit(&mut collector);
990 // Methods get added to the AST map when their impl is visited. Since we
991 // don't decode and instantiate the impl, but just the method, we have to
992 // add it to the table now. Likewise with foreign items.
995 II::TraitItem(_, ref ti) => {
996 collector.insert(ti.id, NodeTraitItem(ti));
998 II::ImplItem(_, ref ii) => {
999 collector.insert(ii.id, NodeImplItem(ii));
1001 II::Foreign(ref i) => {
1002 collector.insert(i.id, NodeForeignItem(i));
1005 *map.map.borrow_mut() = collector.map;
1009 pub trait NodePrinter {
1010 fn print_node(&mut self, node: &Node) -> io::Result<()>;
1013 impl<'a> NodePrinter for pprust::State<'a> {
1014 fn print_node(&mut self, node: &Node) -> io::Result<()> {
1016 NodeItem(a) => self.print_item(&*a),
1017 NodeForeignItem(a) => self.print_foreign_item(&*a),
1018 NodeTraitItem(a) => self.print_trait_item(a),
1019 NodeImplItem(a) => self.print_impl_item(a),
1020 NodeVariant(a) => self.print_variant(&*a),
1021 NodeExpr(a) => self.print_expr(&*a),
1022 NodeStmt(a) => self.print_stmt(&*a),
1023 NodePat(a) => self.print_pat(&*a),
1024 NodeBlock(a) => self.print_block(&*a),
1025 NodeLifetime(a) => self.print_lifetime(&*a),
1026 NodeTyParam(_) => panic!("cannot print TyParam"),
1027 // these cases do not carry enough information in the
1028 // ast_map to reconstruct their full structure for pretty
1030 NodeLocal(_) => panic!("cannot print isolated Local"),
1031 NodeArg(_) => panic!("cannot print isolated Arg"),
1032 NodeStructCtor(_) => panic!("cannot print isolated StructCtor"),
1037 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
1038 let id_str = format!(" (id={})", id);
1039 let id_str = if include_id { &id_str[..] } else { "" };
1041 match map.find(id) {
1042 Some(NodeItem(item)) => {
1043 let path_str = map.path_to_str_with_ident(id, item.ident);
1044 let item_str = match item.node {
1045 ItemExternCrate(..) => "extern crate",
1046 ItemUse(..) => "use",
1047 ItemStatic(..) => "static",
1048 ItemConst(..) => "const",
1050 ItemMod(..) => "mod",
1051 ItemForeignMod(..) => "foreign mod",
1053 ItemEnum(..) => "enum",
1054 ItemStruct(..) => "struct",
1055 ItemTrait(..) => "trait",
1056 ItemImpl(..) => "impl",
1057 ItemDefaultImpl(..) => "default impl",
1059 format!("{} {}{}", item_str, path_str, id_str)
1061 Some(NodeForeignItem(item)) => {
1062 let path_str = map.path_to_str_with_ident(id, item.ident);
1063 format!("foreign item {}{}", path_str, id_str)
1065 Some(NodeImplItem(ii)) => {
1067 ConstImplItem(..) => {
1068 format!("assoc const {} in {}{}",
1070 map.path_to_string(id),
1073 MethodImplItem(..) => {
1074 format!("method {} in {}{}",
1076 map.path_to_string(id), id_str)
1078 TypeImplItem(_) => {
1079 format!("assoc type {} in {}{}",
1081 map.path_to_string(id),
1086 Some(NodeTraitItem(ti)) => {
1087 let kind = match ti.node {
1088 ConstTraitItem(..) => "assoc constant",
1089 MethodTraitItem(..) => "trait method",
1090 TypeTraitItem(..) => "assoc type",
1093 format!("{} {} in {}{}",
1096 map.path_to_string(id),
1099 Some(NodeVariant(ref variant)) => {
1100 format!("variant {} in {}{}",
1102 map.path_to_string(id), id_str)
1104 Some(NodeExpr(ref expr)) => {
1105 format!("expr {}{}", pprust::expr_to_string(&**expr), id_str)
1107 Some(NodeStmt(ref stmt)) => {
1108 format!("stmt {}{}", pprust::stmt_to_string(&**stmt), id_str)
1110 Some(NodeArg(ref pat)) => {
1111 format!("arg {}{}", pprust::pat_to_string(&**pat), id_str)
1113 Some(NodeLocal(ref pat)) => {
1114 format!("local {}{}", pprust::pat_to_string(&**pat), id_str)
1116 Some(NodePat(ref pat)) => {
1117 format!("pat {}{}", pprust::pat_to_string(&**pat), id_str)
1119 Some(NodeBlock(ref block)) => {
1120 format!("block {}{}", pprust::block_to_string(&**block), id_str)
1122 Some(NodeStructCtor(_)) => {
1123 format!("struct_ctor {}{}", map.path_to_string(id), id_str)
1125 Some(NodeLifetime(ref l)) => {
1126 format!("lifetime {}{}",
1127 pprust::lifetime_to_string(&**l), id_str)
1129 Some(NodeTyParam(ref ty_param)) => {
1130 format!("typaram {:?}{}", ty_param, id_str)
1133 format!("unknown node{}", id_str)