]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ast_map/mod.rs
return &mut T from the arenas, not &T
[rust.git] / src / libsyntax / 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 use abi;
12 use ast::*;
13 use ast_util;
14 use codemap::{DUMMY_SP, Span, Spanned};
15 use fold::Folder;
16 use parse::token;
17 use print::pprust;
18 use ptr::P;
19 use visit::{mod, Visitor};
20
21 use arena::TypedArena;
22 use std::cell::RefCell;
23 use std::fmt;
24 use std::io::IoResult;
25 use std::iter;
26 use std::mem;
27 use std::slice;
28
29 pub mod blocks;
30
31 #[deriving(Clone, PartialEq)]
32 pub enum PathElem {
33     PathMod(Name),
34     PathName(Name)
35 }
36
37 impl PathElem {
38     pub fn name(&self) -> Name {
39         match *self {
40             PathMod(name) | PathName(name) => name
41         }
42     }
43 }
44
45 impl fmt::Show for PathElem {
46     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
47         let slot = token::get_name(self.name());
48         write!(f, "{}", slot)
49     }
50 }
51
52 #[deriving(Clone)]
53 struct LinkedPathNode<'a> {
54     node: PathElem,
55     next: LinkedPath<'a>,
56 }
57
58 type LinkedPath<'a> = Option<&'a LinkedPathNode<'a>>;
59
60 impl<'a> Iterator<PathElem> for LinkedPath<'a> {
61     fn next(&mut self) -> Option<PathElem> {
62         match *self {
63             Some(node) => {
64                 *self = node.next;
65                 Some(node.node)
66             }
67             None => None
68         }
69     }
70 }
71
72 // HACK(eddyb) move this into libstd (value wrapper for slice::Items).
73 #[deriving(Clone)]
74 pub struct Values<'a, T:'a>(pub slice::Items<'a, T>);
75
76 impl<'a, T: Copy> Iterator<T> for Values<'a, T> {
77     fn next(&mut self) -> Option<T> {
78         let &Values(ref mut items) = self;
79         items.next().map(|&x| x)
80     }
81 }
82
83 /// The type of the iterator used by with_path.
84 pub type PathElems<'a, 'b> = iter::Chain<Values<'a, PathElem>, LinkedPath<'b>>;
85
86 pub fn path_to_string<PI: Iterator<PathElem>>(mut path: PI) -> String {
87     let itr = token::get_ident_interner();
88
89     path.fold(String::new(), |mut s, e| {
90         let e = itr.get(e.name());
91         if !s.is_empty() {
92             s.push_str("::");
93         }
94         s.push_str(e.as_slice());
95         s
96     }).to_string()
97 }
98
99 #[deriving(Show)]
100 pub enum Node<'ast> {
101     NodeItem(&'ast Item),
102     NodeForeignItem(&'ast ForeignItem),
103     NodeTraitItem(&'ast TraitItem),
104     NodeImplItem(&'ast ImplItem),
105     NodeVariant(&'ast Variant),
106     NodeExpr(&'ast Expr),
107     NodeStmt(&'ast Stmt),
108     NodeArg(&'ast Pat),
109     NodeLocal(&'ast Pat),
110     NodePat(&'ast Pat),
111     NodeBlock(&'ast Block),
112
113     /// NodeStructCtor represents a tuple struct.
114     NodeStructCtor(&'ast StructDef),
115
116     NodeLifetime(&'ast Lifetime),
117 }
118
119 /// Represents an entry and its parent Node ID
120 /// The odd layout is to bring down the total size.
121 #[deriving(Show)]
122 enum MapEntry<'ast> {
123     /// Placeholder for holes in the map.
124     NotPresent,
125
126     /// All the node types, with a parent ID.
127     EntryItem(NodeId, &'ast Item),
128     EntryForeignItem(NodeId, &'ast ForeignItem),
129     EntryTraitItem(NodeId, &'ast TraitItem),
130     EntryImplItem(NodeId, &'ast ImplItem),
131     EntryVariant(NodeId, &'ast Variant),
132     EntryExpr(NodeId, &'ast Expr),
133     EntryStmt(NodeId, &'ast Stmt),
134     EntryArg(NodeId, &'ast Pat),
135     EntryLocal(NodeId, &'ast Pat),
136     EntryPat(NodeId, &'ast Pat),
137     EntryBlock(NodeId, &'ast Block),
138     EntryStructCtor(NodeId, &'ast StructDef),
139     EntryLifetime(NodeId, &'ast Lifetime),
140
141     /// Roots for node trees.
142     RootCrate,
143     RootInlinedParent(&'ast InlinedParent)
144 }
145
146 impl<'ast> Clone for MapEntry<'ast> {
147     fn clone(&self) -> MapEntry<'ast> {
148         *self
149     }
150 }
151
152 #[deriving(Show)]
153 struct InlinedParent {
154     path: Vec<PathElem>,
155     ii: InlinedItem
156 }
157
158 impl<'ast> MapEntry<'ast> {
159     fn from_node(p: NodeId, node: Node<'ast>) -> MapEntry<'ast> {
160         match node {
161             NodeItem(n) => EntryItem(p, n),
162             NodeForeignItem(n) => EntryForeignItem(p, n),
163             NodeTraitItem(n) => EntryTraitItem(p, n),
164             NodeImplItem(n) => EntryImplItem(p, n),
165             NodeVariant(n) => EntryVariant(p, n),
166             NodeExpr(n) => EntryExpr(p, n),
167             NodeStmt(n) => EntryStmt(p, n),
168             NodeArg(n) => EntryArg(p, n),
169             NodeLocal(n) => EntryLocal(p, n),
170             NodePat(n) => EntryPat(p, n),
171             NodeBlock(n) => EntryBlock(p, n),
172             NodeStructCtor(n) => EntryStructCtor(p, n),
173             NodeLifetime(n) => EntryLifetime(p, n)
174         }
175     }
176
177     fn parent(self) -> Option<NodeId> {
178         Some(match self {
179             EntryItem(id, _) => id,
180             EntryForeignItem(id, _) => id,
181             EntryTraitItem(id, _) => id,
182             EntryImplItem(id, _) => id,
183             EntryVariant(id, _) => id,
184             EntryExpr(id, _) => id,
185             EntryStmt(id, _) => id,
186             EntryArg(id, _) => id,
187             EntryLocal(id, _) => id,
188             EntryPat(id, _) => id,
189             EntryBlock(id, _) => id,
190             EntryStructCtor(id, _) => id,
191             EntryLifetime(id, _) => id,
192             _ => return None
193         })
194     }
195
196     fn to_node(self) -> Option<Node<'ast>> {
197         Some(match self {
198             EntryItem(_, n) => NodeItem(n),
199             EntryForeignItem(_, n) => NodeForeignItem(n),
200             EntryTraitItem(_, n) => NodeTraitItem(n),
201             EntryImplItem(_, n) => NodeImplItem(n),
202             EntryVariant(_, n) => NodeVariant(n),
203             EntryExpr(_, n) => NodeExpr(n),
204             EntryStmt(_, n) => NodeStmt(n),
205             EntryArg(_, n) => NodeArg(n),
206             EntryLocal(_, n) => NodeLocal(n),
207             EntryPat(_, n) => NodePat(n),
208             EntryBlock(_, n) => NodeBlock(n),
209             EntryStructCtor(_, n) => NodeStructCtor(n),
210             EntryLifetime(_, n) => NodeLifetime(n),
211             _ => return None
212         })
213     }
214 }
215
216 /// Stores a crate and any number of inlined items from other crates.
217 pub struct Forest {
218     krate: Crate,
219     inlined_items: TypedArena<InlinedParent>
220 }
221
222 impl Forest {
223     pub fn new(krate: Crate) -> Forest {
224         Forest {
225             krate: krate,
226             inlined_items: TypedArena::new()
227         }
228     }
229
230     pub fn krate<'ast>(&'ast self) -> &'ast Crate {
231         &self.krate
232     }
233 }
234
235 /// Represents a mapping from Node IDs to AST elements and their parent
236 /// Node IDs
237 pub struct Map<'ast> {
238     /// The backing storage for all the AST nodes.
239     forest: &'ast Forest,
240
241     /// NodeIds are sequential integers from 0, so we can be
242     /// super-compact by storing them in a vector. Not everything with
243     /// a NodeId is in the map, but empirically the occupancy is about
244     /// 75-80%, so there's not too much overhead (certainly less than
245     /// a hashmap, since they (at the time of writing) have a maximum
246     /// of 75% occupancy).
247     ///
248     /// Also, indexing is pretty quick when you've got a vector and
249     /// plain old integers.
250     map: RefCell<Vec<MapEntry<'ast>>>
251 }
252
253 impl<'ast> Map<'ast> {
254     fn entry_count(&self) -> uint {
255         self.map.borrow().len()
256     }
257
258     fn find_entry(&self, id: NodeId) -> Option<MapEntry<'ast>> {
259         self.map.borrow().as_slice().get(id as uint).map(|e| *e)
260     }
261
262     pub fn krate(&self) -> &'ast Crate {
263         &self.forest.krate
264     }
265
266     /// Retrieve the Node corresponding to `id`, failing if it cannot
267     /// be found.
268     pub fn get(&self, id: NodeId) -> Node<'ast> {
269         match self.find(id) {
270             Some(node) => node,
271             None => fail!("couldn't find node id {} in the AST map", id)
272         }
273     }
274
275     /// Retrieve the Node corresponding to `id`, returning None if
276     /// cannot be found.
277     pub fn find(&self, id: NodeId) -> Option<Node<'ast>> {
278         self.find_entry(id).and_then(|x| x.to_node())
279     }
280
281     /// Retrieve the parent NodeId for `id`, or `id` itself if no
282     /// parent is registered in this map.
283     pub fn get_parent(&self, id: NodeId) -> NodeId {
284         self.find_entry(id).and_then(|x| x.parent()).unwrap_or(id)
285     }
286
287     pub fn get_parent_did(&self, id: NodeId) -> DefId {
288         let parent = self.get_parent(id);
289         match self.find_entry(parent) {
290             Some(RootInlinedParent(&InlinedParent {ii: IITraitItem(did, _), ..})) => did,
291             Some(RootInlinedParent(&InlinedParent {ii: IIImplItem(did, _), ..})) => did,
292             _ => ast_util::local_def(parent)
293         }
294     }
295
296     pub fn get_foreign_abi(&self, id: NodeId) -> abi::Abi {
297         let parent = self.get_parent(id);
298         let abi = match self.find_entry(parent) {
299             Some(EntryItem(_, i)) => {
300                 match i.node {
301                     ItemForeignMod(ref nm) => Some(nm.abi),
302                     _ => None
303                 }
304             }
305             /// Wrong but OK, because the only inlined foreign items are intrinsics.
306             Some(RootInlinedParent(_)) => Some(abi::RustIntrinsic),
307             _ => None
308         };
309         match abi {
310             Some(abi) => abi,
311             None => fail!("expected foreign mod or inlined parent, found {}",
312                           self.node_to_string(parent))
313         }
314     }
315
316     pub fn get_foreign_vis(&self, id: NodeId) -> Visibility {
317         let vis = self.expect_foreign_item(id).vis;
318         match self.find(self.get_parent(id)) {
319             Some(NodeItem(i)) => vis.inherit_from(i.vis),
320             _ => vis
321         }
322     }
323
324     pub fn expect_item(&self, id: NodeId) -> &'ast Item {
325         match self.find(id) {
326             Some(NodeItem(item)) => item,
327             _ => fail!("expected item, found {}", self.node_to_string(id))
328         }
329     }
330
331     pub fn expect_struct(&self, id: NodeId) -> &'ast StructDef {
332         match self.find(id) {
333             Some(NodeItem(i)) => {
334                 match i.node {
335                     ItemStruct(ref struct_def, _) => &**struct_def,
336                     _ => fail!("struct ID bound to non-struct")
337                 }
338             }
339             Some(NodeVariant(variant)) => {
340                 match variant.node.kind {
341                     StructVariantKind(ref struct_def) => &**struct_def,
342                     _ => fail!("struct ID bound to enum variant that isn't struct-like"),
343                 }
344             }
345             _ => fail!(format!("expected struct, found {}", self.node_to_string(id))),
346         }
347     }
348
349     pub fn expect_variant(&self, id: NodeId) -> &'ast Variant {
350         match self.find(id) {
351             Some(NodeVariant(variant)) => variant,
352             _ => fail!(format!("expected variant, found {}", self.node_to_string(id))),
353         }
354     }
355
356     pub fn expect_foreign_item(&self, id: NodeId) -> &'ast ForeignItem {
357         match self.find(id) {
358             Some(NodeForeignItem(item)) => item,
359             _ => fail!("expected foreign item, found {}", self.node_to_string(id))
360         }
361     }
362
363     pub fn expect_expr(&self, id: NodeId) -> &'ast Expr {
364         match self.find(id) {
365             Some(NodeExpr(expr)) => expr,
366             _ => fail!("expected expr, found {}", self.node_to_string(id))
367         }
368     }
369
370     /// returns the name associated with the given NodeId's AST
371     pub fn get_path_elem(&self, id: NodeId) -> PathElem {
372         let node = self.get(id);
373         match node {
374             NodeItem(item) => {
375                 match item.node {
376                     ItemMod(_) | ItemForeignMod(_) => {
377                         PathMod(item.ident.name)
378                     }
379                     _ => PathName(item.ident.name)
380                 }
381             }
382             NodeForeignItem(i) => PathName(i.ident.name),
383             NodeImplItem(ii) => {
384                 match *ii {
385                     MethodImplItem(ref m) => {
386                         match m.node {
387                             MethDecl(ident, _, _, _, _, _, _, _) => {
388                                 PathName(ident.name)
389                             }
390                             MethMac(_) => {
391                                 fail!("no path elem for {}", node)
392                             }
393                         }
394                     }
395                     TypeImplItem(ref t) => PathName(t.ident.name),
396                 }
397             },
398             NodeTraitItem(tm) => match *tm {
399                 RequiredMethod(ref m) => PathName(m.ident.name),
400                 ProvidedMethod(ref m) => {
401                     match m.node {
402                         MethDecl(ident, _, _, _, _, _, _, _) => {
403                             PathName(ident.name)
404                         }
405                         MethMac(_) => fail!("no path elem for {}", node),
406                     }
407                 }
408                 TypeTraitItem(ref m) => PathName(m.ident.name),
409             },
410             NodeVariant(v) => PathName(v.node.name.name),
411             _ => fail!("no path elem for {}", node)
412         }
413     }
414
415     pub fn with_path<T>(&self, id: NodeId, f: |PathElems| -> T) -> T {
416         self.with_path_next(id, None, f)
417     }
418
419     pub fn path_to_string(&self, id: NodeId) -> String {
420         self.with_path(id, |path| path_to_string(path))
421     }
422
423     fn path_to_str_with_ident(&self, id: NodeId, i: Ident) -> String {
424         self.with_path(id, |path| {
425             path_to_string(path.chain(Some(PathName(i.name)).into_iter()))
426         })
427     }
428
429     fn with_path_next<T>(&self, id: NodeId, next: LinkedPath, f: |PathElems| -> T) -> T {
430         let parent = self.get_parent(id);
431         let parent = match self.find_entry(id) {
432             Some(EntryForeignItem(..)) | Some(EntryVariant(..)) => {
433                 // Anonymous extern items, enum variants and struct ctors
434                 // go in the parent scope.
435                 self.get_parent(parent)
436             }
437             // But tuple struct ctors don't have names, so use the path of its
438             // parent, the struct item. Similarly with closure expressions.
439             Some(EntryStructCtor(..)) | Some(EntryExpr(..)) => {
440                 return self.with_path_next(parent, next, f);
441             }
442             _ => parent
443         };
444         if parent == id {
445             match self.find_entry(id) {
446                 Some(RootInlinedParent(data)) => {
447                     f(Values(data.path.iter()).chain(next))
448                 }
449                 _ => f(Values([].iter()).chain(next))
450             }
451         } else {
452             self.with_path_next(parent, Some(&LinkedPathNode {
453                 node: self.get_path_elem(id),
454                 next: next
455             }), f)
456         }
457     }
458
459     /// Given a node ID and a closure, apply the closure to the array
460     /// of attributes associated with the AST corresponding to the Node ID
461     pub fn with_attrs<T>(&self, id: NodeId, f: |Option<&[Attribute]>| -> T) -> T {
462         let attrs = match self.get(id) {
463             NodeItem(i) => Some(i.attrs.as_slice()),
464             NodeForeignItem(fi) => Some(fi.attrs.as_slice()),
465             NodeTraitItem(ref tm) => match **tm {
466                 RequiredMethod(ref type_m) => Some(type_m.attrs.as_slice()),
467                 ProvidedMethod(ref m) => Some(m.attrs.as_slice()),
468                 TypeTraitItem(ref typ) => Some(typ.attrs.as_slice()),
469             },
470             NodeImplItem(ref ii) => {
471                 match **ii {
472                     MethodImplItem(ref m) => Some(m.attrs.as_slice()),
473                     TypeImplItem(ref t) => Some(t.attrs.as_slice()),
474                 }
475             }
476             NodeVariant(ref v) => Some(v.node.attrs.as_slice()),
477             // unit/tuple structs take the attributes straight from
478             // the struct definition.
479             // FIXME(eddyb) make this work again (requires access to the map).
480             NodeStructCtor(_) => {
481                 return self.with_attrs(self.get_parent(id), f);
482             }
483             _ => None
484         };
485         f(attrs)
486     }
487
488     /// Returns an iterator that yields the node id's with paths that
489     /// match `parts`.  (Requires `parts` is non-empty.)
490     ///
491     /// For example, if given `parts` equal to `["bar", "quux"]`, then
492     /// the iterator will produce node id's for items with paths
493     /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
494     /// any other such items it can find in the map.
495     pub fn nodes_matching_suffix<'a, S:Str>(&'a self, parts: &'a [S])
496                                  -> NodesMatchingSuffix<'a, 'ast, S> {
497         NodesMatchingSuffix {
498             map: self,
499             item_name: parts.last().unwrap(),
500             in_which: parts[..parts.len() - 1],
501             idx: 0,
502         }
503     }
504
505     pub fn opt_span(&self, id: NodeId) -> Option<Span> {
506         let sp = match self.find(id) {
507             Some(NodeItem(item)) => item.span,
508             Some(NodeForeignItem(foreign_item)) => foreign_item.span,
509             Some(NodeTraitItem(trait_method)) => {
510                 match *trait_method {
511                     RequiredMethod(ref type_method) => type_method.span,
512                     ProvidedMethod(ref method) => method.span,
513                     TypeTraitItem(ref typedef) => typedef.span,
514                 }
515             }
516             Some(NodeImplItem(ref impl_item)) => {
517                 match **impl_item {
518                     MethodImplItem(ref method) => method.span,
519                     TypeImplItem(ref typedef) => typedef.span,
520                 }
521             }
522             Some(NodeVariant(variant)) => variant.span,
523             Some(NodeExpr(expr)) => expr.span,
524             Some(NodeStmt(stmt)) => stmt.span,
525             Some(NodeArg(pat)) | Some(NodeLocal(pat)) => pat.span,
526             Some(NodePat(pat)) => pat.span,
527             Some(NodeBlock(block)) => block.span,
528             Some(NodeStructCtor(_)) => self.expect_item(self.get_parent(id)).span,
529             _ => return None,
530         };
531         Some(sp)
532     }
533
534     pub fn span(&self, id: NodeId) -> Span {
535         self.opt_span(id)
536             .unwrap_or_else(|| fail!("AstMap.span: could not find span for id {}", id))
537     }
538
539     pub fn def_id_span(&self, def_id: DefId, fallback: Span) -> Span {
540         if def_id.krate == LOCAL_CRATE {
541             self.span(def_id.node)
542         } else {
543             fallback
544         }
545     }
546
547     pub fn node_to_string(&self, id: NodeId) -> String {
548         node_id_to_string(self, id)
549     }
550 }
551
552 pub struct NodesMatchingSuffix<'a, 'ast:'a, S:'a> {
553     map: &'a Map<'ast>,
554     item_name: &'a S,
555     in_which: &'a [S],
556     idx: NodeId,
557 }
558
559 impl<'a, 'ast, S:Str> NodesMatchingSuffix<'a, 'ast, S> {
560     /// Returns true only if some suffix of the module path for parent
561     /// matches `self.in_which`.
562     ///
563     /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
564     /// returns true if parent's path ends with the suffix
565     /// `x_0::x_1::...::x_k`.
566     fn suffix_matches(&self, parent: NodeId) -> bool {
567         let mut cursor = parent;
568         for part in self.in_which.iter().rev() {
569             let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
570                 None => return false,
571                 Some((node_id, name)) => (node_id, name),
572             };
573             if part.as_slice() != mod_name.as_str() {
574                 return false;
575             }
576             cursor = self.map.get_parent(mod_id);
577         }
578         return true;
579
580         // Finds the first mod in parent chain for `id`, along with
581         // that mod's name.
582         //
583         // If `id` itself is a mod named `m` with parent `p`, then
584         // returns `Some(id, m, p)`.  If `id` has no mod in its parent
585         // chain, then returns `None`.
586         fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
587             loop {
588                 match map.find(id) {
589                     None => return None,
590                     Some(NodeItem(item)) if item_is_mod(&*item) =>
591                         return Some((id, item.ident.name)),
592                     _ => {}
593                 }
594                 let parent = map.get_parent(id);
595                 if parent == id { return None }
596                 id = parent;
597             }
598
599             fn item_is_mod(item: &Item) -> bool {
600                 match item.node {
601                     ItemMod(_) => true,
602                     _ => false,
603                 }
604             }
605         }
606     }
607
608     // We are looking at some node `n` with a given name and parent
609     // id; do their names match what I am seeking?
610     fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
611         name.as_str() == self.item_name.as_slice() &&
612             self.suffix_matches(parent_of_n)
613     }
614 }
615
616 impl<'a, 'ast, S:Str> Iterator<NodeId> for NodesMatchingSuffix<'a, 'ast, S> {
617     fn next(&mut self) -> Option<NodeId> {
618         loop {
619             let idx = self.idx;
620             if idx as uint >= self.map.entry_count() {
621                 return None;
622             }
623             self.idx += 1;
624             let (p, name) = match self.map.find_entry(idx) {
625                 Some(EntryItem(p, n))       => (p, n.name()),
626                 Some(EntryForeignItem(p, n))=> (p, n.name()),
627                 Some(EntryTraitItem(p, n))  => (p, n.name()),
628                 Some(EntryImplItem(p, n))   => (p, n.name()),
629                 Some(EntryVariant(p, n))    => (p, n.name()),
630                 _ => continue,
631             };
632             if self.matches_names(p, name) {
633                 return Some(idx)
634             }
635         }
636     }
637 }
638
639 trait Named {
640     fn name(&self) -> Name;
641 }
642
643 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
644
645 impl Named for Item { fn name(&self) -> Name { self.ident.name } }
646 impl Named for ForeignItem { fn name(&self) -> Name { self.ident.name } }
647 impl Named for Variant_ { fn name(&self) -> Name { self.name.name } }
648 impl Named for TraitItem {
649     fn name(&self) -> Name {
650         match *self {
651             RequiredMethod(ref tm) => tm.ident.name,
652             ProvidedMethod(ref m) => m.name(),
653             TypeTraitItem(ref at) => at.ident.name,
654         }
655     }
656 }
657 impl Named for ImplItem {
658     fn name(&self) -> Name {
659         match *self {
660             MethodImplItem(ref m) => m.name(),
661             TypeImplItem(ref td) => td.ident.name,
662         }
663     }
664 }
665 impl Named for Method {
666     fn name(&self) -> Name {
667         match self.node {
668             MethDecl(i, _, _, _, _, _, _, _) => i.name,
669             MethMac(_) => fail!("encountered unexpanded method macro."),
670         }
671     }
672 }
673
674 pub trait FoldOps {
675     fn new_id(&self, id: NodeId) -> NodeId {
676         id
677     }
678     fn new_def_id(&self, def_id: DefId) -> DefId {
679         def_id
680     }
681     fn new_span(&self, span: Span) -> Span {
682         span
683     }
684 }
685
686 /// A Folder that updates IDs and Span's according to fold_ops.
687 struct IdAndSpanUpdater<F> {
688     fold_ops: F
689 }
690
691 impl<F: FoldOps> Folder for IdAndSpanUpdater<F> {
692     fn new_id(&mut self, id: NodeId) -> NodeId {
693         self.fold_ops.new_id(id)
694     }
695
696     fn new_span(&mut self, span: Span) -> Span {
697         self.fold_ops.new_span(span)
698     }
699 }
700
701 /// A Visitor that walks over an AST and collects Node's into an AST Map.
702 struct NodeCollector<'ast> {
703     map: Vec<MapEntry<'ast>>,
704     /// The node in which we are currently mapping (an item or a method).
705     parent: NodeId
706 }
707
708 impl<'ast> NodeCollector<'ast> {
709     fn insert_entry(&mut self, id: NodeId, entry: MapEntry<'ast>) {
710         debug!("ast_map: {} => {}", id, entry);
711         let len = self.map.len();
712         if id as uint >= len {
713             self.map.grow(id as uint - len + 1, NotPresent);
714         }
715         *self.map.get_mut(id as uint) = entry;
716     }
717
718     fn insert(&mut self, id: NodeId, node: Node<'ast>) {
719         let entry = MapEntry::from_node(self.parent, node);
720         self.insert_entry(id, entry);
721     }
722
723     fn visit_fn_decl(&mut self, decl: &'ast FnDecl) {
724         for a in decl.inputs.iter() {
725             self.insert(a.id, NodeArg(&*a.pat));
726         }
727     }
728 }
729
730 impl<'ast> Visitor<'ast> for NodeCollector<'ast> {
731     fn visit_item(&mut self, i: &'ast Item) {
732         self.insert(i.id, NodeItem(i));
733         let parent = self.parent;
734         self.parent = i.id;
735         match i.node {
736             ItemImpl(_, _, _, ref impl_items) => {
737                 for impl_item in impl_items.iter() {
738                     match *impl_item {
739                         MethodImplItem(ref m) => {
740                             self.insert(m.id, NodeImplItem(impl_item));
741                         }
742                         TypeImplItem(ref t) => {
743                             self.insert(t.id, NodeImplItem(impl_item));
744                         }
745                     }
746                 }
747             }
748             ItemEnum(ref enum_definition, _) => {
749                 for v in enum_definition.variants.iter() {
750                     self.insert(v.node.id, NodeVariant(&**v));
751                 }
752             }
753             ItemForeignMod(ref nm) => {
754                 for nitem in nm.items.iter() {
755                     self.insert(nitem.id, NodeForeignItem(&**nitem));
756                 }
757             }
758             ItemStruct(ref struct_def, _) => {
759                 // If this is a tuple-like struct, register the constructor.
760                 match struct_def.ctor_id {
761                     Some(ctor_id) => {
762                         self.insert(ctor_id, NodeStructCtor(&**struct_def));
763                     }
764                     None => {}
765                 }
766             }
767             ItemTrait(_, _, ref bounds, ref trait_items) => {
768                 for b in bounds.iter() {
769                     match *b {
770                         TraitTyParamBound(ref t) => {
771                             self.insert(t.ref_id, NodeItem(i));
772                         }
773                         _ => {}
774                     }
775                 }
776
777                 for tm in trait_items.iter() {
778                     match *tm {
779                         RequiredMethod(ref m) => {
780                             self.insert(m.id, NodeTraitItem(tm));
781                         }
782                         ProvidedMethod(ref m) => {
783                             self.insert(m.id, NodeTraitItem(tm));
784                         }
785                         TypeTraitItem(ref typ) => {
786                             self.insert(typ.id, NodeTraitItem(tm));
787                         }
788                     }
789                 }
790             }
791             _ => {}
792         }
793         visit::walk_item(self, i);
794         self.parent = parent;
795     }
796
797     fn visit_pat(&mut self, pat: &'ast Pat) {
798         self.insert(pat.id, match pat.node {
799             // Note: this is at least *potentially* a pattern...
800             PatIdent(..) => NodeLocal(pat),
801             _ => NodePat(pat)
802         });
803         visit::walk_pat(self, pat);
804     }
805
806     fn visit_expr(&mut self, expr: &'ast Expr) {
807         self.insert(expr.id, NodeExpr(expr));
808         visit::walk_expr(self, expr);
809     }
810
811     fn visit_stmt(&mut self, stmt: &'ast Stmt) {
812         self.insert(ast_util::stmt_id(stmt), NodeStmt(stmt));
813         visit::walk_stmt(self, stmt);
814     }
815
816     fn visit_ty_method(&mut self, m: &'ast TypeMethod) {
817         let parent = self.parent;
818         self.parent = m.id;
819         self.visit_fn_decl(&*m.decl);
820         visit::walk_ty_method(self, m);
821         self.parent = parent;
822     }
823
824     fn visit_fn(&mut self, fk: visit::FnKind<'ast>, fd: &'ast FnDecl,
825                 b: &'ast Block, s: Span, id: NodeId) {
826         match fk {
827             visit::FkMethod(..) => {
828                 let parent = self.parent;
829                 self.parent = id;
830                 self.visit_fn_decl(fd);
831                 visit::walk_fn(self, fk, fd, b, s);
832                 self.parent = parent;
833             }
834             _ => {
835                 self.visit_fn_decl(fd);
836                 visit::walk_fn(self, fk, fd, b, s);
837             }
838         }
839     }
840
841     fn visit_ty(&mut self, ty: &'ast Ty) {
842         match ty.node {
843             TyClosure(ref fd) | TyProc(ref fd) => {
844                 self.visit_fn_decl(&*fd.decl);
845             }
846             TyBareFn(ref fd) => {
847                 self.visit_fn_decl(&*fd.decl);
848             }
849             TyUnboxedFn(ref fd) => {
850                 self.visit_fn_decl(&*fd.decl);
851             }
852             _ => {}
853         }
854         visit::walk_ty(self, ty);
855     }
856
857     fn visit_block(&mut self, block: &'ast Block) {
858         self.insert(block.id, NodeBlock(block));
859         visit::walk_block(self, block);
860     }
861
862     fn visit_lifetime_ref(&mut self, lifetime: &'ast Lifetime) {
863         self.insert(lifetime.id, NodeLifetime(lifetime));
864     }
865
866     fn visit_lifetime_decl(&mut self, def: &'ast LifetimeDef) {
867         self.visit_lifetime_ref(&def.lifetime);
868     }
869 }
870
871 pub fn map_crate<'ast, F: FoldOps>(forest: &'ast mut Forest, fold_ops: F) -> Map<'ast> {
872     // Replace the crate with an empty one to take it out.
873     let krate = mem::replace(&mut forest.krate, Crate {
874         module: Mod {
875             inner: DUMMY_SP,
876             view_items: vec![],
877             items: vec![],
878         },
879         attrs: vec![],
880         config: vec![],
881         exported_macros: vec![],
882         span: DUMMY_SP
883     });
884     forest.krate = IdAndSpanUpdater { fold_ops: fold_ops }.fold_crate(krate);
885
886     let mut collector = NodeCollector {
887         map: vec![],
888         parent: CRATE_NODE_ID
889     };
890     collector.insert_entry(CRATE_NODE_ID, RootCrate);
891     visit::walk_crate(&mut collector, &forest.krate);
892     let map = collector.map;
893
894     if log_enabled!(::log::DEBUG) {
895         // This only makes sense for ordered stores; note the
896         // enumerate to count the number of entries.
897         let (entries_less_1, _) = map.iter().filter(|&x| {
898             match *x {
899                 NotPresent => false,
900                 _ => true
901             }
902         }).enumerate().last().expect("AST map was empty after folding?");
903
904         let entries = entries_less_1 + 1;
905         let vector_length = map.len();
906         debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
907               entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
908     }
909
910     Map {
911         forest: forest,
912         map: RefCell::new(map)
913     }
914 }
915
916 /// Used for items loaded from external crate that are being inlined into this
917 /// crate.  The `path` should be the path to the item but should not include
918 /// the item itself.
919 pub fn map_decoded_item<'ast, F: FoldOps>(map: &Map<'ast>,
920                                           path: Vec<PathElem>,
921                                           ii: InlinedItem,
922                                           fold_ops: F)
923                                           -> &'ast InlinedItem {
924     let mut fld = IdAndSpanUpdater { fold_ops: fold_ops };
925     let ii = match ii {
926         IIItem(i) => IIItem(fld.fold_item(i).expect_one("expected one item")),
927         IITraitItem(d, ti) => match ti {
928             ProvidedMethod(m) => {
929                 IITraitItem(fld.fold_ops.new_def_id(d),
930                             ProvidedMethod(fld.fold_method(m)
931                                               .expect_one("expected one method")))
932             }
933             RequiredMethod(ty_m) => {
934                 IITraitItem(fld.fold_ops.new_def_id(d),
935                             RequiredMethod(fld.fold_type_method(ty_m)))
936             }
937             TypeTraitItem(at) => {
938                 IITraitItem(
939                     fld.fold_ops.new_def_id(d),
940                     TypeTraitItem(P(fld.fold_associated_type((*at).clone()))))
941             }
942         },
943         IIImplItem(d, m) => match m {
944             MethodImplItem(m) => {
945                 IIImplItem(fld.fold_ops.new_def_id(d),
946                            MethodImplItem(fld.fold_method(m)
947                                              .expect_one("expected one method")))
948             }
949             TypeImplItem(t) => {
950                 IIImplItem(fld.fold_ops.new_def_id(d),
951                            TypeImplItem(P(fld.fold_typedef((*t).clone()))))
952             }
953         },
954         IIForeign(i) => IIForeign(fld.fold_foreign_item(i))
955     };
956
957     let ii_parent = map.forest.inlined_items.alloc(InlinedParent {
958         path: path,
959         ii: ii
960     });
961
962     let mut collector = NodeCollector {
963         map: mem::replace(&mut *map.map.borrow_mut(), vec![]),
964         parent: fld.new_id(DUMMY_NODE_ID)
965     };
966     let ii_parent_id = collector.parent;
967     collector.insert_entry(ii_parent_id, RootInlinedParent(ii_parent));
968     visit::walk_inlined_item(&mut collector, &ii_parent.ii);
969
970     // Methods get added to the AST map when their impl is visited.  Since we
971     // don't decode and instantiate the impl, but just the method, we have to
972     // add it to the table now. Likewise with foreign items.
973     match ii_parent.ii {
974         IIItem(_) => {}
975         IITraitItem(_, ref trait_item) => {
976             let trait_item_id = match *trait_item {
977                 ProvidedMethod(ref m) => m.id,
978                 RequiredMethod(ref m) => m.id,
979                 TypeTraitItem(ref ty) => ty.id,
980             };
981
982             collector.insert(trait_item_id, NodeTraitItem(trait_item));
983         }
984         IIImplItem(_, ref impl_item) => {
985             let impl_item_id = match *impl_item {
986                 MethodImplItem(ref m) => m.id,
987                 TypeImplItem(ref ti) => ti.id,
988             };
989
990             collector.insert(impl_item_id, NodeImplItem(impl_item));
991         }
992         IIForeign(ref i) => {
993             collector.insert(i.id, NodeForeignItem(&**i));
994         }
995     }
996     *map.map.borrow_mut() = collector.map;
997     &ii_parent.ii
998 }
999
1000 pub trait NodePrinter {
1001     fn print_node(&mut self, node: &Node) -> IoResult<()>;
1002 }
1003
1004 impl<'a> NodePrinter for pprust::State<'a> {
1005     fn print_node(&mut self, node: &Node) -> IoResult<()> {
1006         match *node {
1007             NodeItem(a)        => self.print_item(&*a),
1008             NodeForeignItem(a) => self.print_foreign_item(&*a),
1009             NodeTraitItem(a)   => self.print_trait_method(&*a),
1010             NodeImplItem(a)    => self.print_impl_item(&*a),
1011             NodeVariant(a)     => self.print_variant(&*a),
1012             NodeExpr(a)        => self.print_expr(&*a),
1013             NodeStmt(a)        => self.print_stmt(&*a),
1014             NodePat(a)         => self.print_pat(&*a),
1015             NodeBlock(a)       => self.print_block(&*a),
1016             NodeLifetime(a)    => self.print_lifetime(&*a),
1017
1018             // these cases do not carry enough information in the
1019             // ast_map to reconstruct their full structure for pretty
1020             // printing.
1021             NodeLocal(_)       => fail!("cannot print isolated Local"),
1022             NodeArg(_)         => fail!("cannot print isolated Arg"),
1023             NodeStructCtor(_)  => fail!("cannot print isolated StructCtor"),
1024         }
1025     }
1026 }
1027
1028 fn node_id_to_string(map: &Map, id: NodeId) -> String {
1029     match map.find(id) {
1030         Some(NodeItem(item)) => {
1031             let path_str = map.path_to_str_with_ident(id, item.ident);
1032             let item_str = match item.node {
1033                 ItemStatic(..) => "static",
1034                 ItemConst(..) => "const",
1035                 ItemFn(..) => "fn",
1036                 ItemMod(..) => "mod",
1037                 ItemForeignMod(..) => "foreign mod",
1038                 ItemTy(..) => "ty",
1039                 ItemEnum(..) => "enum",
1040                 ItemStruct(..) => "struct",
1041                 ItemTrait(..) => "trait",
1042                 ItemImpl(..) => "impl",
1043                 ItemMac(..) => "macro"
1044             };
1045             format!("{} {} (id={})", item_str, path_str, id)
1046         }
1047         Some(NodeForeignItem(item)) => {
1048             let path_str = map.path_to_str_with_ident(id, item.ident);
1049             format!("foreign item {} (id={})", path_str, id)
1050         }
1051         Some(NodeImplItem(ref ii)) => {
1052             match **ii {
1053                 MethodImplItem(ref m) => {
1054                     match m.node {
1055                         MethDecl(ident, _, _, _, _, _, _, _) =>
1056                             format!("method {} in {} (id={})",
1057                                     token::get_ident(ident),
1058                                     map.path_to_string(id), id),
1059                         MethMac(ref mac) =>
1060                             format!("method macro {} (id={})",
1061                                     pprust::mac_to_string(mac), id)
1062                     }
1063                 }
1064                 TypeImplItem(ref t) => {
1065                     format!("typedef {} in {} (id={})",
1066                             token::get_ident(t.ident),
1067                             map.path_to_string(id),
1068                             id)
1069                 }
1070             }
1071         }
1072         Some(NodeTraitItem(ref tm)) => {
1073             match **tm {
1074                 RequiredMethod(_) | ProvidedMethod(_) => {
1075                     let m = ast_util::trait_item_to_ty_method(&**tm);
1076                     format!("method {} in {} (id={})",
1077                             token::get_ident(m.ident),
1078                             map.path_to_string(id),
1079                             id)
1080                 }
1081                 TypeTraitItem(ref t) => {
1082                     format!("type item {} in {} (id={})",
1083                             token::get_ident(t.ident),
1084                             map.path_to_string(id),
1085                             id)
1086                 }
1087             }
1088         }
1089         Some(NodeVariant(ref variant)) => {
1090             format!("variant {} in {} (id={})",
1091                     token::get_ident(variant.node.name),
1092                     map.path_to_string(id), id)
1093         }
1094         Some(NodeExpr(ref expr)) => {
1095             format!("expr {} (id={})", pprust::expr_to_string(&**expr), id)
1096         }
1097         Some(NodeStmt(ref stmt)) => {
1098             format!("stmt {} (id={})", pprust::stmt_to_string(&**stmt), id)
1099         }
1100         Some(NodeArg(ref pat)) => {
1101             format!("arg {} (id={})", pprust::pat_to_string(&**pat), id)
1102         }
1103         Some(NodeLocal(ref pat)) => {
1104             format!("local {} (id={})", pprust::pat_to_string(&**pat), id)
1105         }
1106         Some(NodePat(ref pat)) => {
1107             format!("pat {} (id={})", pprust::pat_to_string(&**pat), id)
1108         }
1109         Some(NodeBlock(ref block)) => {
1110             format!("block {} (id={})", pprust::block_to_string(&**block), id)
1111         }
1112         Some(NodeStructCtor(_)) => {
1113             format!("struct_ctor {} (id={})", map.path_to_string(id), id)
1114         }
1115         Some(NodeLifetime(ref l)) => {
1116             format!("lifetime {} (id={})",
1117                     pprust::lifetime_to_string(&**l), id)
1118         }
1119         None => {
1120             format!("unknown node (id={})", id)
1121         }
1122     }
1123 }