]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ast_map/mod.rs
Doc says to avoid mixing allocator instead of forbiding it
[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 ast_util::PostExpansionMethod;
15 use codemap::{DUMMY_SP, Span, Spanned};
16 use fold::Folder;
17 use parse::token;
18 use print::pprust;
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                 }
395             },
396             NodeTraitItem(tm) => match *tm {
397                 RequiredMethod(ref m) => PathName(m.ident.name),
398                 ProvidedMethod(ref m) => match m.node {
399                     MethDecl(ident, _, _, _, _, _, _, _) => {
400                         PathName(ident.name)
401                     }
402                     MethMac(_) => fail!("no path elem for {:?}", node),
403                 }
404             },
405             NodeVariant(v) => PathName(v.node.name.name),
406             _ => fail!("no path elem for {:?}", node)
407         }
408     }
409
410     pub fn with_path<T>(&self, id: NodeId, f: |PathElems| -> T) -> T {
411         self.with_path_next(id, None, f)
412     }
413
414     pub fn path_to_string(&self, id: NodeId) -> String {
415         self.with_path(id, |path| path_to_string(path))
416     }
417
418     fn path_to_str_with_ident(&self, id: NodeId, i: Ident) -> String {
419         self.with_path(id, |path| {
420             path_to_string(path.chain(Some(PathName(i.name)).move_iter()))
421         })
422     }
423
424     fn with_path_next<T>(&self, id: NodeId, next: LinkedPath, f: |PathElems| -> T) -> T {
425         let parent = self.get_parent(id);
426         let parent = match self.find_entry(id) {
427             Some(EntryForeignItem(..)) | Some(EntryVariant(..)) => {
428                 // Anonymous extern items, enum variants and struct ctors
429                 // go in the parent scope.
430                 self.get_parent(parent)
431             }
432             // But tuple struct ctors don't have names, so use the path of its
433             // parent, the struct item. Similarly with closure expressions.
434             Some(EntryStructCtor(..)) | Some(EntryExpr(..)) => {
435                 return self.with_path_next(parent, next, f);
436             }
437             _ => parent
438         };
439         if parent == id {
440             match self.find_entry(id) {
441                 Some(RootInlinedParent(data)) => {
442                     f(Values(data.path.iter()).chain(next))
443                 }
444                 _ => f(Values([].iter()).chain(next))
445             }
446         } else {
447             self.with_path_next(parent, Some(&LinkedPathNode {
448                 node: self.get_path_elem(id),
449                 next: next
450             }), f)
451         }
452     }
453
454     /// Given a node ID and a closure, apply the closure to the array
455     /// of attributes associated with the AST corresponding to the Node ID
456     pub fn with_attrs<T>(&self, id: NodeId, f: |Option<&[Attribute]>| -> T) -> T {
457         let attrs = match self.get(id) {
458             NodeItem(i) => Some(i.attrs.as_slice()),
459             NodeForeignItem(fi) => Some(fi.attrs.as_slice()),
460             NodeTraitItem(ref tm) => match **tm {
461                 RequiredMethod(ref type_m) => Some(type_m.attrs.as_slice()),
462                 ProvidedMethod(ref m) => Some(m.attrs.as_slice())
463             },
464             NodeImplItem(ref ii) => {
465                 match **ii {
466                     MethodImplItem(ref m) => Some(m.attrs.as_slice()),
467                 }
468             }
469             NodeVariant(ref v) => Some(v.node.attrs.as_slice()),
470             // unit/tuple structs take the attributes straight from
471             // the struct definition.
472             // FIXME(eddyb) make this work again (requires access to the map).
473             NodeStructCtor(_) => {
474                 return self.with_attrs(self.get_parent(id), f);
475             }
476             _ => None
477         };
478         f(attrs)
479     }
480
481     /// Returns an iterator that yields the node id's with paths that
482     /// match `parts`.  (Requires `parts` is non-empty.)
483     ///
484     /// For example, if given `parts` equal to `["bar", "quux"]`, then
485     /// the iterator will produce node id's for items with paths
486     /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
487     /// any other such items it can find in the map.
488     pub fn nodes_matching_suffix<'a, S:Str>(&'a self, parts: &'a [S])
489                                  -> NodesMatchingSuffix<'a, 'ast, S> {
490         NodesMatchingSuffix {
491             map: self,
492             item_name: parts.last().unwrap(),
493             in_which: parts.slice_to(parts.len() - 1),
494             idx: 0,
495         }
496     }
497
498     pub fn opt_span(&self, id: NodeId) -> Option<Span> {
499         let sp = match self.find(id) {
500             Some(NodeItem(item)) => item.span,
501             Some(NodeForeignItem(foreign_item)) => foreign_item.span,
502             Some(NodeTraitItem(trait_method)) => {
503                 match *trait_method {
504                     RequiredMethod(ref type_method) => type_method.span,
505                     ProvidedMethod(ref method) => method.span,
506                 }
507             }
508             Some(NodeImplItem(ref impl_item)) => {
509                 match **impl_item {
510                     MethodImplItem(ref method) => method.span,
511                 }
512             }
513             Some(NodeVariant(variant)) => variant.span,
514             Some(NodeExpr(expr)) => expr.span,
515             Some(NodeStmt(stmt)) => stmt.span,
516             Some(NodeArg(pat)) | Some(NodeLocal(pat)) => pat.span,
517             Some(NodePat(pat)) => pat.span,
518             Some(NodeBlock(block)) => block.span,
519             Some(NodeStructCtor(_)) => self.expect_item(self.get_parent(id)).span,
520             _ => return None,
521         };
522         Some(sp)
523     }
524
525     pub fn span(&self, id: NodeId) -> Span {
526         self.opt_span(id)
527             .unwrap_or_else(|| fail!("AstMap.span: could not find span for id {}", id))
528     }
529
530     pub fn node_to_string(&self, id: NodeId) -> String {
531         node_id_to_string(self, id)
532     }
533 }
534
535 pub struct NodesMatchingSuffix<'a, 'ast:'a, S:'a> {
536     map: &'a Map<'ast>,
537     item_name: &'a S,
538     in_which: &'a [S],
539     idx: NodeId,
540 }
541
542 impl<'a, 'ast, S:Str> NodesMatchingSuffix<'a, 'ast, S> {
543     /// Returns true only if some suffix of the module path for parent
544     /// matches `self.in_which`.
545     ///
546     /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
547     /// returns true if parent's path ends with the suffix
548     /// `x_0::x_1::...::x_k`.
549     fn suffix_matches(&self, parent: NodeId) -> bool {
550         let mut cursor = parent;
551         for part in self.in_which.iter().rev() {
552             let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
553                 None => return false,
554                 Some((node_id, name)) => (node_id, name),
555             };
556             if part.as_slice() != mod_name.as_str() {
557                 return false;
558             }
559             cursor = self.map.get_parent(mod_id);
560         }
561         return true;
562
563         // Finds the first mod in parent chain for `id`, along with
564         // that mod's name.
565         //
566         // If `id` itself is a mod named `m` with parent `p`, then
567         // returns `Some(id, m, p)`.  If `id` has no mod in its parent
568         // chain, then returns `None`.
569         fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
570             loop {
571                 match map.find(id) {
572                     None => return None,
573                     Some(NodeItem(item)) if item_is_mod(&*item) =>
574                         return Some((id, item.ident.name)),
575                     _ => {}
576                 }
577                 let parent = map.get_parent(id);
578                 if parent == id { return None }
579                 id = parent;
580             }
581
582             fn item_is_mod(item: &Item) -> bool {
583                 match item.node {
584                     ItemMod(_) => true,
585                     _ => false,
586                 }
587             }
588         }
589     }
590
591     // We are looking at some node `n` with a given name and parent
592     // id; do their names match what I am seeking?
593     fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
594         name.as_str() == self.item_name.as_slice() &&
595             self.suffix_matches(parent_of_n)
596     }
597 }
598
599 impl<'a, 'ast, S:Str> Iterator<NodeId> for NodesMatchingSuffix<'a, 'ast, S> {
600     fn next(&mut self) -> Option<NodeId> {
601         loop {
602             let idx = self.idx;
603             if idx as uint >= self.map.entry_count() {
604                 return None;
605             }
606             self.idx += 1;
607             let (p, name) = match self.map.find_entry(idx) {
608                 Some(EntryItem(p, n))       => (p, n.name()),
609                 Some(EntryForeignItem(p, n))=> (p, n.name()),
610                 Some(EntryTraitItem(p, n))  => (p, n.name()),
611                 Some(EntryImplItem(p, n))   => (p, n.name()),
612                 Some(EntryVariant(p, n))    => (p, n.name()),
613                 _ => continue,
614             };
615             if self.matches_names(p, name) {
616                 return Some(idx)
617             }
618         }
619     }
620 }
621
622 trait Named {
623     fn name(&self) -> Name;
624 }
625
626 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
627
628 impl Named for Item { fn name(&self) -> Name { self.ident.name } }
629 impl Named for ForeignItem { fn name(&self) -> Name { self.ident.name } }
630 impl Named for Variant_ { fn name(&self) -> Name { self.name.name } }
631 impl Named for TraitItem {
632     fn name(&self) -> Name {
633         match *self {
634             RequiredMethod(ref tm) => tm.ident.name,
635             ProvidedMethod(ref m) => m.name(),
636         }
637     }
638 }
639 impl Named for ImplItem {
640     fn name(&self) -> Name {
641         match *self {
642             MethodImplItem(ref m) => m.name(),
643         }
644     }
645 }
646 impl Named for Method {
647     fn name(&self) -> Name {
648         match self.node {
649             MethDecl(i, _, _, _, _, _, _, _) => i.name,
650             MethMac(_) => fail!("encountered unexpanded method macro."),
651         }
652     }
653 }
654
655 pub trait FoldOps {
656     fn new_id(&self, id: NodeId) -> NodeId {
657         id
658     }
659     fn new_def_id(&self, def_id: DefId) -> DefId {
660         def_id
661     }
662     fn new_span(&self, span: Span) -> Span {
663         span
664     }
665 }
666
667 /// A Folder that updates IDs and Span's according to fold_ops.
668 struct IdAndSpanUpdater<F> {
669     fold_ops: F
670 }
671
672 impl<F: FoldOps> Folder for IdAndSpanUpdater<F> {
673     fn new_id(&mut self, id: NodeId) -> NodeId {
674         self.fold_ops.new_id(id)
675     }
676
677     fn new_span(&mut self, span: Span) -> Span {
678         self.fold_ops.new_span(span)
679     }
680 }
681
682 /// A Visitor that walks over an AST and collects Node's into an AST Map.
683 struct NodeCollector<'ast> {
684     map: Vec<MapEntry<'ast>>,
685     /// The node in which we are currently mapping (an item or a method).
686     parent: NodeId
687 }
688
689 impl<'ast> NodeCollector<'ast> {
690     fn insert_entry(&mut self, id: NodeId, entry: MapEntry<'ast>) {
691         self.map.grow_set(id as uint, &NotPresent, entry);
692         debug!("ast_map: {} => {}", id, entry);
693     }
694
695     fn insert(&mut self, id: NodeId, node: Node<'ast>) {
696         let entry = MapEntry::from_node(self.parent, node);
697         self.insert_entry(id, entry);
698     }
699
700     fn visit_fn_decl(&mut self, decl: &'ast FnDecl) {
701         for a in decl.inputs.iter() {
702             self.insert(a.id, NodeArg(&*a.pat));
703         }
704     }
705 }
706
707 impl<'ast> Visitor<'ast> for NodeCollector<'ast> {
708     fn visit_item(&mut self, i: &'ast Item) {
709         self.insert(i.id, NodeItem(i));
710         let parent = self.parent;
711         self.parent = i.id;
712         match i.node {
713             ItemImpl(_, _, _, ref impl_items) => {
714                 for impl_item in impl_items.iter() {
715                     let id = match *impl_item {
716                         MethodImplItem(ref m) => m.id
717                     };
718                     self.insert(id, NodeImplItem(impl_item));
719                 }
720             }
721             ItemEnum(ref enum_definition, _) => {
722                 for v in enum_definition.variants.iter() {
723                     self.insert(v.node.id, NodeVariant(&**v));
724                 }
725             }
726             ItemForeignMod(ref nm) => {
727                 for nitem in nm.items.iter() {
728                     self.insert(nitem.id, NodeForeignItem(&**nitem));
729                 }
730             }
731             ItemStruct(ref struct_def, _) => {
732                 // If this is a tuple-like struct, register the constructor.
733                 match struct_def.ctor_id {
734                     Some(ctor_id) => {
735                         self.insert(ctor_id, NodeStructCtor(&**struct_def));
736                     }
737                     None => {}
738                 }
739             }
740             ItemTrait(_, _, _, ref methods) => {
741                 for tm in methods.iter() {
742                     let id = match *tm {
743                         RequiredMethod(ref m) => m.id,
744                         ProvidedMethod(ref m) => m.id
745                     };
746                     self.insert(id, NodeTraitItem(tm));
747                 }
748             }
749             _ => {}
750         }
751         visit::walk_item(self, i);
752         self.parent = parent;
753     }
754
755     fn visit_pat(&mut self, pat: &'ast Pat) {
756         self.insert(pat.id, match pat.node {
757             // Note: this is at least *potentially* a pattern...
758             PatIdent(..) => NodeLocal(pat),
759             _ => NodePat(pat)
760         });
761         visit::walk_pat(self, pat);
762     }
763
764     fn visit_expr(&mut self, expr: &'ast Expr) {
765         self.insert(expr.id, NodeExpr(expr));
766         visit::walk_expr(self, expr);
767     }
768
769     fn visit_stmt(&mut self, stmt: &'ast Stmt) {
770         self.insert(ast_util::stmt_id(stmt), NodeStmt(stmt));
771         visit::walk_stmt(self, stmt);
772     }
773
774     fn visit_ty_method(&mut self, m: &'ast TypeMethod) {
775         let parent = self.parent;
776         self.parent = m.id;
777         self.visit_fn_decl(&*m.decl);
778         visit::walk_ty_method(self, m);
779         self.parent = parent;
780     }
781
782     fn visit_fn(&mut self, fk: visit::FnKind<'ast>, fd: &'ast FnDecl,
783                 b: &'ast Block, s: Span, id: NodeId) {
784         match fk {
785             visit::FkMethod(..) => {
786                 let parent = self.parent;
787                 self.parent = id;
788                 self.visit_fn_decl(fd);
789                 visit::walk_fn(self, fk, fd, b, s);
790                 self.parent = parent;
791             }
792             _ => {
793                 self.visit_fn_decl(fd);
794                 visit::walk_fn(self, fk, fd, b, s);
795             }
796         }
797     }
798
799     fn visit_ty(&mut self, ty: &'ast Ty) {
800         match ty.node {
801             TyClosure(ref fd) | TyProc(ref fd) => {
802                 self.visit_fn_decl(&*fd.decl);
803             }
804             TyBareFn(ref fd) => {
805                 self.visit_fn_decl(&*fd.decl);
806             }
807             TyUnboxedFn(ref fd) => {
808                 self.visit_fn_decl(&*fd.decl);
809             }
810             _ => {}
811         }
812         visit::walk_ty(self, ty);
813     }
814
815     fn visit_block(&mut self, block: &'ast Block) {
816         self.insert(block.id, NodeBlock(block));
817         visit::walk_block(self, block);
818     }
819
820     fn visit_lifetime_ref(&mut self, lifetime: &'ast Lifetime) {
821         self.insert(lifetime.id, NodeLifetime(lifetime));
822     }
823
824     fn visit_lifetime_decl(&mut self, def: &'ast LifetimeDef) {
825         self.visit_lifetime_ref(&def.lifetime);
826     }
827 }
828
829 pub fn map_crate<'ast, F: FoldOps>(forest: &'ast mut Forest, fold_ops: F) -> Map<'ast> {
830     // Replace the crate with an empty one to take it out.
831     let krate = mem::replace(&mut forest.krate, Crate {
832         module: Mod {
833             inner: DUMMY_SP,
834             view_items: vec![],
835             items: vec![],
836         },
837         attrs: vec![],
838         config: vec![],
839         exported_macros: vec![],
840         span: DUMMY_SP
841     });
842     forest.krate = IdAndSpanUpdater { fold_ops: fold_ops }.fold_crate(krate);
843
844     let mut collector = NodeCollector {
845         map: vec![],
846         parent: CRATE_NODE_ID
847     };
848     collector.insert_entry(CRATE_NODE_ID, RootCrate);
849     visit::walk_crate(&mut collector, &forest.krate);
850     let map = collector.map;
851
852     if log_enabled!(::log::DEBUG) {
853         // This only makes sense for ordered stores; note the
854         // enumerate to count the number of entries.
855         let (entries_less_1, _) = map.iter().filter(|&x| {
856             match *x {
857                 NotPresent => false,
858                 _ => true
859             }
860         }).enumerate().last().expect("AST map was empty after folding?");
861
862         let entries = entries_less_1 + 1;
863         let vector_length = map.len();
864         debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
865               entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
866     }
867
868     Map {
869         forest: forest,
870         map: RefCell::new(map)
871     }
872 }
873
874 /// Used for items loaded from external crate that are being inlined into this
875 /// crate.  The `path` should be the path to the item but should not include
876 /// the item itself.
877 pub fn map_decoded_item<'ast, F: FoldOps>(map: &Map<'ast>,
878                                           path: Vec<PathElem>,
879                                           ii: InlinedItem,
880                                           fold_ops: F)
881                                           -> &'ast InlinedItem {
882     let mut fld = IdAndSpanUpdater { fold_ops: fold_ops };
883     let ii = match ii {
884         IIItem(i) => IIItem(fld.fold_item(i).expect_one("expected one item")),
885         IITraitItem(d, ti) => match ti {
886             ProvidedMethod(m) => {
887                 IITraitItem(fld.fold_ops.new_def_id(d),
888                             ProvidedMethod(fld.fold_method(m)
889                                               .expect_one("expected one method")))
890             }
891             RequiredMethod(ty_m) => {
892                 IITraitItem(fld.fold_ops.new_def_id(d),
893                             RequiredMethod(fld.fold_type_method(ty_m)))
894             }
895         },
896         IIImplItem(d, m) => match m {
897             MethodImplItem(m) => {
898                 IIImplItem(fld.fold_ops.new_def_id(d),
899                            MethodImplItem(fld.fold_method(m)
900                                              .expect_one("expected one method")))
901             }
902         },
903         IIForeign(i) => IIForeign(fld.fold_foreign_item(i))
904     };
905
906     let ii_parent = map.forest.inlined_items.alloc(InlinedParent {
907         path: path,
908         ii: ii
909     });
910
911     let mut collector = NodeCollector {
912         map: mem::replace(&mut *map.map.borrow_mut(), vec![]),
913         parent: fld.new_id(DUMMY_NODE_ID)
914     };
915     let ii_parent_id = collector.parent;
916     collector.insert_entry(ii_parent_id, RootInlinedParent(ii_parent));
917     visit::walk_inlined_item(&mut collector, &ii_parent.ii);
918
919     // Methods get added to the AST map when their impl is visited.  Since we
920     // don't decode and instantiate the impl, but just the method, we have to
921     // add it to the table now. Likewise with foreign items.
922     match ii_parent.ii {
923         IIItem(_) => {}
924         IITraitItem(_, ref trait_item) => {
925             let trait_item_id = match *trait_item {
926                 ProvidedMethod(ref m) => m.id,
927                 RequiredMethod(ref m) => m.id
928             };
929
930             collector.insert(trait_item_id, NodeTraitItem(trait_item));
931         }
932         IIImplItem(_, ref impl_item) => {
933             let impl_item_id = match *impl_item {
934                 MethodImplItem(ref m) => m.id
935             };
936
937             collector.insert(impl_item_id, NodeImplItem(impl_item));
938         }
939         IIForeign(ref i) => {
940             collector.insert(i.id, NodeForeignItem(&**i));
941         }
942     }
943     *map.map.borrow_mut() = collector.map;
944     &ii_parent.ii
945 }
946
947 pub trait NodePrinter {
948     fn print_node(&mut self, node: &Node) -> IoResult<()>;
949 }
950
951 impl<'a> NodePrinter for pprust::State<'a> {
952     fn print_node(&mut self, node: &Node) -> IoResult<()> {
953         match *node {
954             NodeItem(a)        => self.print_item(&*a),
955             NodeForeignItem(a) => self.print_foreign_item(&*a),
956             NodeTraitItem(a)   => self.print_trait_method(&*a),
957             NodeImplItem(a)    => self.print_impl_item(&*a),
958             NodeVariant(a)     => self.print_variant(&*a),
959             NodeExpr(a)        => self.print_expr(&*a),
960             NodeStmt(a)        => self.print_stmt(&*a),
961             NodePat(a)         => self.print_pat(&*a),
962             NodeBlock(a)       => self.print_block(&*a),
963             NodeLifetime(a)    => self.print_lifetime(&*a),
964
965             // these cases do not carry enough information in the
966             // ast_map to reconstruct their full structure for pretty
967             // printing.
968             NodeLocal(_)       => fail!("cannot print isolated Local"),
969             NodeArg(_)         => fail!("cannot print isolated Arg"),
970             NodeStructCtor(_)  => fail!("cannot print isolated StructCtor"),
971         }
972     }
973 }
974
975 fn node_id_to_string(map: &Map, id: NodeId) -> String {
976     match map.find(id) {
977         Some(NodeItem(item)) => {
978             let path_str = map.path_to_str_with_ident(id, item.ident);
979             let item_str = match item.node {
980                 ItemStatic(..) => "static",
981                 ItemFn(..) => "fn",
982                 ItemMod(..) => "mod",
983                 ItemForeignMod(..) => "foreign mod",
984                 ItemTy(..) => "ty",
985                 ItemEnum(..) => "enum",
986                 ItemStruct(..) => "struct",
987                 ItemTrait(..) => "trait",
988                 ItemImpl(..) => "impl",
989                 ItemMac(..) => "macro"
990             };
991             format!("{} {} (id={})", item_str, path_str, id)
992         }
993         Some(NodeForeignItem(item)) => {
994             let path_str = map.path_to_str_with_ident(id, item.ident);
995             format!("foreign item {} (id={})", path_str, id)
996         }
997         Some(NodeImplItem(ref ii)) => {
998             match **ii {
999                 MethodImplItem(ref m) => {
1000                     match m.node {
1001                         MethDecl(ident, _, _, _, _, _, _, _) =>
1002                             format!("method {} in {} (id={})",
1003                                     token::get_ident(ident),
1004                                     map.path_to_string(id), id),
1005                         MethMac(ref mac) =>
1006                             format!("method macro {} (id={})",
1007                                     pprust::mac_to_string(mac), id)
1008                     }
1009                 }
1010             }
1011         }
1012         Some(NodeTraitItem(ref ti)) => {
1013             let ident = match **ti {
1014                 ProvidedMethod(ref m) => m.pe_ident(),
1015                 RequiredMethod(ref m) => m.ident
1016             };
1017             format!("method {} in {} (id={})",
1018                     token::get_ident(ident),
1019                     map.path_to_string(id), id)
1020         }
1021         Some(NodeVariant(ref variant)) => {
1022             format!("variant {} in {} (id={})",
1023                     token::get_ident(variant.node.name),
1024                     map.path_to_string(id), id)
1025         }
1026         Some(NodeExpr(ref expr)) => {
1027             format!("expr {} (id={})", pprust::expr_to_string(&**expr), id)
1028         }
1029         Some(NodeStmt(ref stmt)) => {
1030             format!("stmt {} (id={})", pprust::stmt_to_string(&**stmt), id)
1031         }
1032         Some(NodeArg(ref pat)) => {
1033             format!("arg {} (id={})", pprust::pat_to_string(&**pat), id)
1034         }
1035         Some(NodeLocal(ref pat)) => {
1036             format!("local {} (id={})", pprust::pat_to_string(&**pat), id)
1037         }
1038         Some(NodePat(ref pat)) => {
1039             format!("pat {} (id={})", pprust::pat_to_string(&**pat), id)
1040         }
1041         Some(NodeBlock(ref block)) => {
1042             format!("block {} (id={})", pprust::block_to_string(&**block), id)
1043         }
1044         Some(NodeStructCtor(_)) => {
1045             format!("struct_ctor {} (id={})", map.path_to_string(id), id)
1046         }
1047         Some(NodeLifetime(ref l)) => {
1048             format!("lifetime {} (id={})",
1049                     pprust::lifetime_to_string(&**l), id)
1050         }
1051         None => {
1052             format!("unknown node (id={})", id)
1053         }
1054     }
1055 }