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