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