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