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