]> git.lizzy.rs Git - rust.git/blob - src/librustc/ast_map/mod.rs
remove `get_ident` and `get_name`, make `as_str` sound
[rust.git] / src / librustc / ast_map / mod.rs
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.
4 //
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.
10
11 pub use self::Node::*;
12 pub use self::PathElem::*;
13 use self::MapEntry::*;
14
15 use syntax::abi;
16 use syntax::ast::*;
17 use syntax::ast_util;
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};
23
24 use arena::TypedArena;
25 use std::cell::RefCell;
26 use std::fmt;
27 use std::io;
28 use std::iter::{self, repeat};
29 use std::mem;
30 use std::slice;
31
32 pub mod blocks;
33
34 #[derive(Clone, Copy, PartialEq, Debug)]
35 pub enum PathElem {
36     PathMod(Name),
37     PathName(Name)
38 }
39
40 impl PathElem {
41     pub fn name(&self) -> Name {
42         match *self {
43             PathMod(name) | PathName(name) => name
44         }
45     }
46 }
47
48 impl fmt::Display for PathElem {
49     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
50         write!(f, "{}", self.name())
51     }
52 }
53
54 #[derive(Clone)]
55 pub struct LinkedPathNode<'a> {
56     node: PathElem,
57     next: LinkedPath<'a>,
58 }
59
60 #[derive(Copy, Clone)]
61 pub struct LinkedPath<'a>(Option<&'a LinkedPathNode<'a>>);
62
63 impl<'a> LinkedPath<'a> {
64     pub fn empty() -> LinkedPath<'a> {
65         LinkedPath(None)
66     }
67
68     pub fn from(node: &'a LinkedPathNode) -> LinkedPath<'a> {
69         LinkedPath(Some(node))
70     }
71 }
72
73 impl<'a> Iterator for LinkedPath<'a> {
74     type Item = PathElem;
75
76     fn next(&mut self) -> Option<PathElem> {
77         match self.0 {
78             Some(node) => {
79                 *self = node.next;
80                 Some(node.node)
81             }
82             None => None
83         }
84     }
85 }
86
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>>;
89
90 pub fn path_to_string<PI: Iterator<Item=PathElem>>(path: PI) -> String {
91     let itr = token::get_ident_interner();
92
93     path.fold(String::new(), |mut s, e| {
94         let e = itr.get(e.name());
95         if !s.is_empty() {
96             s.push_str("::");
97         }
98         s.push_str(&e[..]);
99         s
100     })
101 }
102
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),
112     NodeArg(&'ast Pat),
113     NodeLocal(&'ast Pat),
114     NodePat(&'ast Pat),
115     NodeBlock(&'ast Block),
116
117     /// NodeStructCtor represents a tuple struct.
118     NodeStructCtor(&'ast StructDef),
119
120     NodeLifetime(&'ast Lifetime),
121     NodeTyParam(&'ast TyParam)
122 }
123
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.
129     NotPresent,
130
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),
146
147     /// Roots for node trees.
148     RootCrate,
149     RootInlinedParent(&'ast InlinedParent)
150 }
151
152 impl<'ast> Clone for MapEntry<'ast> {
153     fn clone(&self) -> MapEntry<'ast> {
154         *self
155     }
156 }
157
158 #[derive(Debug)]
159 struct InlinedParent {
160     path: Vec<PathElem>,
161     ii: InlinedItem
162 }
163
164 impl<'ast> MapEntry<'ast> {
165     fn from_node(p: NodeId, node: Node<'ast>) -> MapEntry<'ast> {
166         match node {
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),
181         }
182     }
183
184     fn parent_node(self) -> Option<NodeId> {
185         Some(match self {
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,
200             _ => return None
201         })
202     }
203
204     fn to_node(self) -> Option<Node<'ast>> {
205         Some(match self {
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),
220             _ => return None
221         })
222     }
223 }
224
225 /// Stores a crate and any number of inlined items from other crates.
226 pub struct Forest {
227     krate: Crate,
228     inlined_items: TypedArena<InlinedParent>
229 }
230
231 impl Forest {
232     pub fn new(krate: Crate) -> Forest {
233         Forest {
234             krate: krate,
235             inlined_items: TypedArena::new()
236         }
237     }
238
239     pub fn krate<'ast>(&'ast self) -> &'ast Crate {
240         &self.krate
241     }
242 }
243
244 /// Represents a mapping from Node IDs to AST elements and their parent
245 /// Node IDs
246 pub struct Map<'ast> {
247     /// The backing storage for all the AST nodes.
248     forest: &'ast Forest,
249
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).
256     ///
257     /// Also, indexing is pretty quick when you've got a vector and
258     /// plain old integers.
259     map: RefCell<Vec<MapEntry<'ast>>>
260 }
261
262 impl<'ast> Map<'ast> {
263     fn entry_count(&self) -> usize {
264         self.map.borrow().len()
265     }
266
267     fn find_entry(&self, id: NodeId) -> Option<MapEntry<'ast>> {
268         self.map.borrow().get(id as usize).cloned()
269     }
270
271     pub fn krate(&self) -> &'ast Crate {
272         &self.forest.krate
273     }
274
275     /// Retrieve the Node corresponding to `id`, panicking if it cannot
276     /// be found.
277     pub fn get(&self, id: NodeId) -> Node<'ast> {
278         match self.find(id) {
279             Some(node) => node,
280             None => panic!("couldn't find node id {} in the AST map", id)
281         }
282     }
283
284     /// Retrieve the Node corresponding to `id`, returning None if
285     /// cannot be found.
286     pub fn find(&self, id: NodeId) -> Option<Node<'ast>> {
287         self.find_entry(id).and_then(|x| x.to_node())
288     }
289
290     /// Similar to get_parent, returns the parent node id or id if there is no
291     /// parent.
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)
300     }
301
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
306     /// parent.
307     fn walk_parent_nodes<F>(&self, start_id: NodeId, found: F) -> Result<NodeId, NodeId>
308         where F: Fn(&Node<'ast>) -> bool
309     {
310         let mut id = start_id;
311         loop {
312             let parent_node = self.get_parent_node(id);
313             if parent_node == 0 {
314                 return Ok(0);
315             }
316             if parent_node == id {
317                 return Err(id);
318             }
319
320             let node = self.find_entry(parent_node);
321             if node.is_none() {
322                 return Err(id);
323             }
324             let node = node.unwrap().to_node();
325             match node {
326                 Some(ref node) => {
327                     if found(node) {
328                         return Ok(parent_node);
329                     }
330                 }
331                 None => {
332                     return Err(parent_node);
333                 }
334             }
335             id = parent_node;
336         }
337     }
338
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 {
345             NodeItem(_) |
346             NodeForeignItem(_) |
347             NodeTraitItem(_) |
348             NodeImplItem(_) => true,
349             _ => false,
350         }) {
351             Ok(id) => id,
352             Err(id) => id,
353         }
354     }
355
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 {
362             NodeItem(_) |
363             NodeForeignItem(_) |
364             NodeTraitItem(_) |
365             NodeImplItem(_) |
366             NodeBlock(_) => true,
367             _ => false,
368         }) {
369             Ok(id) => Some(id),
370             Err(_) => None,
371         }
372     }
373
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)
380         }
381     }
382
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)) => {
387                 match i.node {
388                     ItemForeignMod(ref nm) => Some(nm.abi),
389                     _ => None
390                 }
391             }
392             /// Wrong but OK, because the only inlined foreign items are intrinsics.
393             Some(RootInlinedParent(_)) => Some(abi::RustIntrinsic),
394             _ => None
395         };
396         match abi {
397             Some(abi) => abi,
398             None => panic!("expected foreign mod or inlined parent, found {}",
399                           self.node_to_string(parent))
400         }
401     }
402
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),
407             _ => vis
408         }
409     }
410
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))
415         }
416     }
417
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))
422         }
423     }
424
425     pub fn expect_struct(&self, id: NodeId) -> &'ast StructDef {
426         match self.find(id) {
427             Some(NodeItem(i)) => {
428                 match i.node {
429                     ItemStruct(ref struct_def, _) => &**struct_def,
430                     _ => panic!("struct ID bound to non-struct")
431                 }
432             }
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"),
437                 }
438             }
439             _ => panic!(format!("expected struct, found {}", self.node_to_string(id))),
440         }
441     }
442
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))),
447         }
448     }
449
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))
454         }
455     }
456
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))
461         }
462     }
463
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);
467         match node {
468             NodeItem(item) => {
469                 match item.node {
470                     ItemMod(_) | ItemForeignMod(_) => {
471                         PathMod(item.ident.name)
472                     }
473                     _ => PathName(item.ident.name)
474                 }
475             }
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)
481         }
482     }
483
484     pub fn with_path<T, F>(&self, id: NodeId, f: F) -> T where
485         F: FnOnce(PathElems) -> T,
486     {
487         self.with_path_next(id, LinkedPath::empty(), f)
488     }
489
490     pub fn path_to_string(&self, id: NodeId) -> String {
491         self.with_path(id, |path| path_to_string(path))
492     }
493
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))))
497         })
498     }
499
500     fn with_path_next<T, F>(&self, id: NodeId, next: LinkedPath, f: F) -> T where
501         F: FnOnce(PathElems) -> T,
502     {
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)
508             }
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);
513             }
514             _ => parent
515         };
516         if parent == id {
517             match self.find_entry(id) {
518                 Some(RootInlinedParent(data)) => {
519                     f(data.path.iter().cloned().chain(next))
520                 }
521                 _ => f([].iter().cloned().chain(next))
522             }
523         } else {
524             self.with_path_next(parent, LinkedPath::from(&LinkedPathNode {
525                 node: self.get_path_elem(id),
526                 next: next
527             }), f)
528         }
529     }
530
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));
544             }
545             _ => None
546         };
547         attrs.unwrap_or(&[])
548     }
549
550     /// Returns an iterator that yields the node id's with paths that
551     /// match `parts`.  (Requires `parts` is non-empty.)
552     ///
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 {
560             map: self,
561             item_name: parts.last().unwrap(),
562             in_which: &parts[..parts.len() - 1],
563             idx: 0,
564         }
565     }
566
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,
581             _ => return None,
582         };
583         Some(sp)
584     }
585
586     pub fn span(&self, id: NodeId) -> Span {
587         self.opt_span(id)
588             .unwrap_or_else(|| panic!("AstMap.span: could not find span for id {:?}", id))
589     }
590
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)
594         } else {
595             fallback
596         }
597     }
598
599     pub fn node_to_string(&self, id: NodeId) -> String {
600         node_id_to_string(self, id, true)
601     }
602
603     pub fn node_to_user_string(&self, id: NodeId) -> String {
604         node_id_to_string(self, id, false)
605     }
606 }
607
608 pub struct NodesMatchingSuffix<'a, 'ast:'a> {
609     map: &'a Map<'ast>,
610     item_name: &'a String,
611     in_which: &'a [String],
612     idx: NodeId,
613 }
614
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`.
618     ///
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),
628             };
629             if &part[..] != mod_name.as_str() {
630                 return false;
631             }
632             cursor = self.map.get_parent(mod_id);
633         }
634         return true;
635
636         // Finds the first mod in parent chain for `id`, along with
637         // that mod's name.
638         //
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)> {
643             loop {
644                 match map.find(id) {
645                     None => return None,
646                     Some(NodeItem(item)) if item_is_mod(&*item) =>
647                         return Some((id, item.ident.name)),
648                     _ => {}
649                 }
650                 let parent = map.get_parent(id);
651                 if parent == id { return None }
652                 id = parent;
653             }
654
655             fn item_is_mod(item: &Item) -> bool {
656                 match item.node {
657                     ItemMod(_) => true,
658                     _ => false,
659                 }
660             }
661         }
662     }
663
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)
669     }
670 }
671
672 impl<'a, 'ast> Iterator for NodesMatchingSuffix<'a, 'ast> {
673     type Item = NodeId;
674
675     fn next(&mut self) -> Option<NodeId> {
676         loop {
677             let idx = self.idx;
678             if idx as usize >= self.map.entry_count() {
679                 return None;
680             }
681             self.idx += 1;
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(),
688                 _ => continue,
689             };
690             if self.matches_names(self.map.get_parent(idx), name) {
691                 return Some(idx)
692             }
693         }
694     }
695 }
696
697 trait Named {
698     fn name(&self) -> Name;
699 }
700
701 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
702
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 } }
708
709 pub trait FoldOps {
710     fn new_id(&self, id: NodeId) -> NodeId {
711         id
712     }
713     fn new_def_id(&self, def_id: DefId) -> DefId {
714         def_id
715     }
716     fn new_span(&self, span: Span) -> Span {
717         span
718     }
719 }
720
721 /// A Folder that updates IDs and Span's according to fold_ops.
722 struct IdAndSpanUpdater<F> {
723     fold_ops: F
724 }
725
726 impl<F: FoldOps> Folder for IdAndSpanUpdater<F> {
727     fn new_id(&mut self, id: NodeId) -> NodeId {
728         self.fold_ops.new_id(id)
729     }
730
731     fn new_span(&mut self, span: Span) -> Span {
732         self.fold_ops.new_span(span)
733     }
734 }
735
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>>,
739     parent_node: NodeId,
740 }
741
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));
748         }
749         self.map[id as usize] = entry;
750     }
751
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);
755     }
756
757     fn visit_fn_decl(&mut self, decl: &'ast FnDecl) {
758         for a in &decl.inputs {
759             self.insert(a.id, NodeArg(&*a.pat));
760         }
761     }
762 }
763
764 impl<'ast> Visitor<'ast> for NodeCollector<'ast> {
765     fn visit_item(&mut self, i: &'ast Item) {
766         self.insert(i.id, NodeItem(i));
767
768         let parent_node = self.parent_node;
769         self.parent_node = i.id;
770
771         match i.node {
772             ItemImpl(_, _, _, _, _, ref impl_items) => {
773                 for ii in impl_items {
774                     self.insert(ii.id, NodeImplItem(ii));
775                 }
776             }
777             ItemEnum(ref enum_definition, _) => {
778                 for v in &enum_definition.variants {
779                     self.insert(v.node.id, NodeVariant(&**v));
780                 }
781             }
782             ItemForeignMod(ref nm) => {
783                 for nitem in &nm.items {
784                     self.insert(nitem.id, NodeForeignItem(&**nitem));
785                 }
786             }
787             ItemStruct(ref struct_def, _) => {
788                 // If this is a tuple-like struct, register the constructor.
789                 match struct_def.ctor_id {
790                     Some(ctor_id) => {
791                         self.insert(ctor_id, NodeStructCtor(&**struct_def));
792                     }
793                     None => {}
794                 }
795             }
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));
800                     }
801                 }
802
803                 for ti in trait_items {
804                     self.insert(ti.id, NodeTraitItem(ti));
805                 }
806             }
807             ItemUse(ref view_path) => {
808                 match view_path.node {
809                     ViewPathList(_, ref paths) => {
810                         for path in paths {
811                             self.insert(path.node.id(), NodeItem(i));
812                         }
813                     }
814                     _ => ()
815                 }
816             }
817             _ => {}
818         }
819         visit::walk_item(self, i);
820         self.parent_node = parent_node;
821     }
822
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));
826         }
827
828         visit::walk_generics(self, generics);
829     }
830
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;
836     }
837
838     fn visit_impl_item(&mut self, ii: &'ast ImplItem) {
839         let parent_node = self.parent_node;
840         self.parent_node = ii.id;
841
842         visit::walk_impl_item(self, ii);
843
844         self.parent_node = parent_node;
845     }
846
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),
851             _ => NodePat(pat)
852         });
853
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;
858     }
859
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;
866     }
867
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;
875     }
876
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;
884     }
885
886     fn visit_ty(&mut self, ty: &'ast Ty) {
887         let parent_node = self.parent_node;
888         self.parent_node = ty.id;
889         match ty.node {
890             TyBareFn(ref fd) => {
891                 self.visit_fn_decl(&*fd.decl);
892             }
893             _ => {}
894         }
895         visit::walk_ty(self, ty);
896         self.parent_node = parent_node;
897     }
898
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;
905     }
906
907     fn visit_lifetime_ref(&mut self, lifetime: &'ast Lifetime) {
908         self.insert(lifetime.id, NodeLifetime(lifetime));
909     }
910
911     fn visit_lifetime_def(&mut self, def: &'ast LifetimeDef) {
912         self.visit_lifetime_ref(&def.lifetime);
913     }
914 }
915
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 {
919         module: Mod {
920             inner: DUMMY_SP,
921             items: vec![],
922         },
923         attrs: vec![],
924         config: vec![],
925         exported_macros: vec![],
926         span: DUMMY_SP
927     });
928     forest.krate = IdAndSpanUpdater { fold_ops: fold_ops }.fold_crate(krate);
929
930     let mut collector = NodeCollector {
931         map: vec![],
932         parent_node: CRATE_NODE_ID,
933     };
934     collector.insert_entry(CRATE_NODE_ID, RootCrate);
935     visit::walk_crate(&mut collector, &forest.krate);
936     let map = collector.map;
937
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| {
942             match *x {
943                 NotPresent => false,
944                 _ => true
945             }
946         }).enumerate().last().expect("AST map was empty after folding?");
947
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.);
952     }
953
954     Map {
955         forest: forest,
956         map: RefCell::new(map)
957     }
958 }
959
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
962 /// the item itself.
963 pub fn map_decoded_item<'ast, F: FoldOps>(map: &Map<'ast>,
964                                           path: Vec<PathElem>,
965                                           ii: InlinedItem,
966                                           fold_ops: F)
967                                           -> &'ast InlinedItem {
968     let mut fld = IdAndSpanUpdater { fold_ops: fold_ops };
969     let ii = match ii {
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"))
974         }
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"))
978         }
979         IIForeign(i) => IIForeign(fld.fold_foreign_item(i))
980     };
981
982     let ii_parent = map.forest.inlined_items.alloc(InlinedParent {
983         path: path,
984         ii: ii
985     });
986
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,
991     };
992     collector.insert_entry(ii_parent_id, RootInlinedParent(ii_parent));
993     visit::walk_inlined_item(&mut collector, &ii_parent.ii);
994
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.
998     match ii_parent.ii {
999         IIItem(_) => {}
1000         IITraitItem(_, ref ti) => {
1001             collector.insert(ti.id, NodeTraitItem(ti));
1002         }
1003         IIImplItem(_, ref ii) => {
1004             collector.insert(ii.id, NodeImplItem(ii));
1005         }
1006         IIForeign(ref i) => {
1007             collector.insert(i.id, NodeForeignItem(i));
1008         }
1009     }
1010     *map.map.borrow_mut() = collector.map;
1011     &ii_parent.ii
1012 }
1013
1014 pub trait NodePrinter {
1015     fn print_node(&mut self, node: &Node) -> io::Result<()>;
1016 }
1017
1018 impl<'a> NodePrinter for pprust::State<'a> {
1019     fn print_node(&mut self, node: &Node) -> io::Result<()> {
1020         match *node {
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
1034             // printing.
1035             NodeLocal(_)       => panic!("cannot print isolated Local"),
1036             NodeArg(_)         => panic!("cannot print isolated Arg"),
1037             NodeStructCtor(_)  => panic!("cannot print isolated StructCtor"),
1038         }
1039     }
1040 }
1041
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 { "" };
1045
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",
1054                 ItemFn(..) => "fn",
1055                 ItemMod(..) => "mod",
1056                 ItemForeignMod(..) => "foreign mod",
1057                 ItemTy(..) => "ty",
1058                 ItemEnum(..) => "enum",
1059                 ItemStruct(..) => "struct",
1060                 ItemTrait(..) => "trait",
1061                 ItemImpl(..) => "impl",
1062                 ItemDefaultImpl(..) => "default impl",
1063                 ItemMac(..) => "macro"
1064             };
1065             format!("{} {}{}", item_str, path_str, id_str)
1066         }
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)
1070         }
1071         Some(NodeImplItem(ii)) => {
1072             match ii.node {
1073                 ConstImplItem(..) => {
1074                     format!("assoc const {} in {}{}",
1075                             ii.ident,
1076                             map.path_to_string(id),
1077                             id_str)
1078                 }
1079                 MethodImplItem(..) => {
1080                     format!("method {} in {}{}",
1081                             ii.ident,
1082                             map.path_to_string(id), id_str)
1083                 }
1084                 TypeImplItem(_) => {
1085                     format!("assoc type {} in {}{}",
1086                             ii.ident,
1087                             map.path_to_string(id),
1088                             id_str)
1089                 }
1090                 MacImplItem(ref mac) => {
1091                     format!("method macro {}{}",
1092                             pprust::mac_to_string(mac), id_str)
1093                 }
1094             }
1095         }
1096         Some(NodeTraitItem(ti)) => {
1097             let kind = match ti.node {
1098                 ConstTraitItem(..) => "assoc constant",
1099                 MethodTraitItem(..) => "trait method",
1100                 TypeTraitItem(..) => "assoc type",
1101             };
1102
1103             format!("{} {} in {}{}",
1104                     kind,
1105                     ti.ident,
1106                     map.path_to_string(id),
1107                     id_str)
1108         }
1109         Some(NodeVariant(ref variant)) => {
1110             format!("variant {} in {}{}",
1111                     variant.node.name,
1112                     map.path_to_string(id), id_str)
1113         }
1114         Some(NodeExpr(ref expr)) => {
1115             format!("expr {}{}", pprust::expr_to_string(&**expr), id_str)
1116         }
1117         Some(NodeStmt(ref stmt)) => {
1118             format!("stmt {}{}", pprust::stmt_to_string(&**stmt), id_str)
1119         }
1120         Some(NodeArg(ref pat)) => {
1121             format!("arg {}{}", pprust::pat_to_string(&**pat), id_str)
1122         }
1123         Some(NodeLocal(ref pat)) => {
1124             format!("local {}{}", pprust::pat_to_string(&**pat), id_str)
1125         }
1126         Some(NodePat(ref pat)) => {
1127             format!("pat {}{}", pprust::pat_to_string(&**pat), id_str)
1128         }
1129         Some(NodeBlock(ref block)) => {
1130             format!("block {}{}", pprust::block_to_string(&**block), id_str)
1131         }
1132         Some(NodeStructCtor(_)) => {
1133             format!("struct_ctor {}{}", map.path_to_string(id), id_str)
1134         }
1135         Some(NodeLifetime(ref l)) => {
1136             format!("lifetime {}{}",
1137                     pprust::lifetime_to_string(&**l), id_str)
1138         }
1139         Some(NodeTyParam(ref ty_param)) => {
1140             format!("typaram {:?}{}", ty_param, id_str)
1141         }
1142         None => {
1143             format!("unknown node{}", id_str)
1144         }
1145     }
1146 }