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