]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/map/mod.rs
rustc: split off BodyOwnerKind from MirSource.
[rust.git] / src / librustc / hir / 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 use self::MapEntry::*;
13 use self::collector::NodeCollector;
14 pub use self::def_collector::{DefCollector, MacroInvocationData};
15 pub use self::definitions::{Definitions, DefKey, DefPath, DefPathData,
16                             DisambiguatedDefPathData, DefPathHash};
17
18 use dep_graph::{DepGraph, DepNode, DepKind, DepNodeIndex};
19
20 use hir::def_id::{CRATE_DEF_INDEX, DefId, DefIndexAddressSpace};
21
22 use syntax::abi::Abi;
23 use syntax::ast::{self, Name, NodeId, CRATE_NODE_ID};
24 use syntax::codemap::Spanned;
25 use syntax_pos::Span;
26
27 use hir::*;
28 use hir::print::Nested;
29 use util::nodemap::{DefIdMap, FxHashMap};
30
31 use arena::TypedArena;
32 use std::cell::RefCell;
33 use std::io;
34
35 pub mod blocks;
36 mod collector;
37 mod def_collector;
38 pub mod definitions;
39 mod hir_id_validator;
40
41 pub const ITEM_LIKE_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::Low;
42 pub const REGULAR_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::High;
43
44 #[derive(Copy, Clone, Debug)]
45 pub enum Node<'hir> {
46     NodeItem(&'hir Item),
47     NodeForeignItem(&'hir ForeignItem),
48     NodeTraitItem(&'hir TraitItem),
49     NodeImplItem(&'hir ImplItem),
50     NodeVariant(&'hir Variant),
51     NodeField(&'hir StructField),
52     NodeExpr(&'hir Expr),
53     NodeStmt(&'hir Stmt),
54     NodeTy(&'hir Ty),
55     NodeTraitRef(&'hir TraitRef),
56     NodeBinding(&'hir Pat),
57     NodePat(&'hir Pat),
58     NodeBlock(&'hir Block),
59     NodeLocal(&'hir Local),
60     NodeMacroDef(&'hir MacroDef),
61
62     /// NodeStructCtor represents a tuple struct.
63     NodeStructCtor(&'hir VariantData),
64
65     NodeLifetime(&'hir Lifetime),
66     NodeTyParam(&'hir TyParam),
67     NodeVisibility(&'hir Visibility),
68 }
69
70 /// Represents an entry and its parent NodeID.
71 /// The odd layout is to bring down the total size.
72 #[derive(Copy, Debug)]
73 enum MapEntry<'hir> {
74     /// Placeholder for holes in the map.
75     NotPresent,
76
77     /// All the node types, with a parent ID.
78     EntryItem(NodeId, DepNodeIndex, &'hir Item),
79     EntryForeignItem(NodeId, DepNodeIndex, &'hir ForeignItem),
80     EntryTraitItem(NodeId, DepNodeIndex, &'hir TraitItem),
81     EntryImplItem(NodeId, DepNodeIndex, &'hir ImplItem),
82     EntryVariant(NodeId, DepNodeIndex, &'hir Variant),
83     EntryField(NodeId, DepNodeIndex, &'hir StructField),
84     EntryExpr(NodeId, DepNodeIndex, &'hir Expr),
85     EntryStmt(NodeId, DepNodeIndex, &'hir Stmt),
86     EntryTy(NodeId, DepNodeIndex, &'hir Ty),
87     EntryTraitRef(NodeId, DepNodeIndex, &'hir TraitRef),
88     EntryBinding(NodeId, DepNodeIndex, &'hir Pat),
89     EntryPat(NodeId, DepNodeIndex, &'hir Pat),
90     EntryBlock(NodeId, DepNodeIndex, &'hir Block),
91     EntryStructCtor(NodeId, DepNodeIndex, &'hir VariantData),
92     EntryLifetime(NodeId, DepNodeIndex, &'hir Lifetime),
93     EntryTyParam(NodeId, DepNodeIndex, &'hir TyParam),
94     EntryVisibility(NodeId, DepNodeIndex, &'hir Visibility),
95     EntryLocal(NodeId, DepNodeIndex, &'hir Local),
96
97     EntryMacroDef(DepNodeIndex, &'hir MacroDef),
98
99     /// Roots for node trees. The DepNodeIndex is the dependency node of the
100     /// crate's root module.
101     RootCrate(DepNodeIndex),
102 }
103
104 impl<'hir> Clone for MapEntry<'hir> {
105     fn clone(&self) -> MapEntry<'hir> {
106         *self
107     }
108 }
109
110 impl<'hir> MapEntry<'hir> {
111     fn parent_node(self) -> Option<NodeId> {
112         Some(match self {
113             EntryItem(id, _, _) => id,
114             EntryForeignItem(id, _, _) => id,
115             EntryTraitItem(id, _, _) => id,
116             EntryImplItem(id, _, _) => id,
117             EntryVariant(id, _, _) => id,
118             EntryField(id, _, _) => id,
119             EntryExpr(id, _, _) => id,
120             EntryStmt(id, _, _) => id,
121             EntryTy(id, _, _) => id,
122             EntryTraitRef(id, _, _) => id,
123             EntryBinding(id, _, _) => id,
124             EntryPat(id, _, _) => id,
125             EntryBlock(id, _, _) => id,
126             EntryStructCtor(id, _, _) => id,
127             EntryLifetime(id, _, _) => id,
128             EntryTyParam(id, _, _) => id,
129             EntryVisibility(id, _, _) => id,
130             EntryLocal(id, _, _) => id,
131
132             NotPresent |
133             EntryMacroDef(..) |
134             RootCrate(_) => return None,
135         })
136     }
137
138     fn to_node(self) -> Option<Node<'hir>> {
139         Some(match self {
140             EntryItem(_, _, n) => NodeItem(n),
141             EntryForeignItem(_, _, n) => NodeForeignItem(n),
142             EntryTraitItem(_, _, n) => NodeTraitItem(n),
143             EntryImplItem(_, _, n) => NodeImplItem(n),
144             EntryVariant(_, _, n) => NodeVariant(n),
145             EntryField(_, _, n) => NodeField(n),
146             EntryExpr(_, _, n) => NodeExpr(n),
147             EntryStmt(_, _, n) => NodeStmt(n),
148             EntryTy(_, _, n) => NodeTy(n),
149             EntryTraitRef(_, _, n) => NodeTraitRef(n),
150             EntryBinding(_, _, n) => NodeBinding(n),
151             EntryPat(_, _, n) => NodePat(n),
152             EntryBlock(_, _, n) => NodeBlock(n),
153             EntryStructCtor(_, _, n) => NodeStructCtor(n),
154             EntryLifetime(_, _, n) => NodeLifetime(n),
155             EntryTyParam(_, _, n) => NodeTyParam(n),
156             EntryVisibility(_, _, n) => NodeVisibility(n),
157             EntryLocal(_, _, n) => NodeLocal(n),
158             EntryMacroDef(_, n) => NodeMacroDef(n),
159
160             NotPresent |
161             RootCrate(_) => return None
162         })
163     }
164
165     fn associated_body(self) -> Option<BodyId> {
166         match self {
167             EntryItem(_, _, item) => {
168                 match item.node {
169                     ItemConst(_, body) |
170                     ItemStatic(.., body) |
171                     ItemFn(_, _, _, _, _, body) => Some(body),
172                     _ => None,
173                 }
174             }
175
176             EntryTraitItem(_, _, item) => {
177                 match item.node {
178                     TraitItemKind::Const(_, Some(body)) |
179                     TraitItemKind::Method(_, TraitMethod::Provided(body)) => Some(body),
180                     _ => None
181                 }
182             }
183
184             EntryImplItem(_, _, item) => {
185                 match item.node {
186                     ImplItemKind::Const(_, body) |
187                     ImplItemKind::Method(_, body) => Some(body),
188                     _ => None,
189                 }
190             }
191
192             EntryExpr(_, _, expr) => {
193                 match expr.node {
194                     ExprClosure(.., body, _, _) => Some(body),
195                     _ => None,
196                 }
197             }
198
199             _ => None
200         }
201     }
202
203     fn is_body_owner(self, node_id: NodeId) -> bool {
204         match self.associated_body() {
205             Some(b) => b.node_id == node_id,
206             None => false,
207         }
208     }
209 }
210
211 /// Stores a crate and any number of inlined items from other crates.
212 pub struct Forest {
213     krate: Crate,
214     pub dep_graph: DepGraph,
215     inlined_bodies: TypedArena<Body>
216 }
217
218 impl Forest {
219     pub fn new(krate: Crate, dep_graph: &DepGraph) -> Forest {
220         Forest {
221             krate,
222             dep_graph: dep_graph.clone(),
223             inlined_bodies: TypedArena::new()
224         }
225     }
226
227     pub fn krate<'hir>(&'hir self) -> &'hir Crate {
228         self.dep_graph.read(DepNode::new_no_params(DepKind::Krate));
229         &self.krate
230     }
231 }
232
233 /// Represents a mapping from Node IDs to AST elements and their parent
234 /// Node IDs
235 #[derive(Clone)]
236 pub struct Map<'hir> {
237     /// The backing storage for all the AST nodes.
238     pub forest: &'hir Forest,
239
240     /// Same as the dep_graph in forest, just available with one fewer
241     /// deref. This is a gratuitous micro-optimization.
242     pub dep_graph: DepGraph,
243
244     /// NodeIds are sequential integers from 0, so we can be
245     /// super-compact by storing them in a vector. Not everything with
246     /// a NodeId is in the map, but empirically the occupancy is about
247     /// 75-80%, so there's not too much overhead (certainly less than
248     /// a hashmap, since they (at the time of writing) have a maximum
249     /// of 75% occupancy).
250     ///
251     /// Also, indexing is pretty quick when you've got a vector and
252     /// plain old integers.
253     map: Vec<MapEntry<'hir>>,
254
255     definitions: &'hir Definitions,
256
257     /// Bodies inlined from other crates are cached here.
258     inlined_bodies: RefCell<DefIdMap<&'hir Body>>,
259
260     /// The reverse mapping of `node_to_hir_id`.
261     hir_to_node_id: FxHashMap<HirId, NodeId>,
262 }
263
264 impl<'hir> Map<'hir> {
265     /// Registers a read in the dependency graph of the AST node with
266     /// the given `id`. This needs to be called each time a public
267     /// function returns the HIR for a node -- in other words, when it
268     /// "reveals" the content of a node to the caller (who might not
269     /// otherwise have had access to those contents, and hence needs a
270     /// read recorded). If the function just returns a DefId or
271     /// NodeId, no actual content was returned, so no read is needed.
272     pub fn read(&self, id: NodeId) {
273         let entry = self.map[id.as_usize()];
274         match entry {
275             EntryItem(_, dep_node_index, _) |
276             EntryTraitItem(_, dep_node_index, _) |
277             EntryImplItem(_, dep_node_index, _) |
278             EntryVariant(_, dep_node_index, _) |
279             EntryForeignItem(_, dep_node_index, _) |
280             EntryField(_, dep_node_index, _) |
281             EntryStmt(_, dep_node_index, _) |
282             EntryTy(_, dep_node_index, _) |
283             EntryTraitRef(_, dep_node_index, _) |
284             EntryBinding(_, dep_node_index, _) |
285             EntryPat(_, dep_node_index, _) |
286             EntryBlock(_, dep_node_index, _) |
287             EntryStructCtor(_, dep_node_index, _) |
288             EntryLifetime(_, dep_node_index, _) |
289             EntryTyParam(_, dep_node_index, _) |
290             EntryVisibility(_, dep_node_index, _) |
291             EntryExpr(_, dep_node_index, _) |
292             EntryLocal(_, dep_node_index, _) |
293             EntryMacroDef(dep_node_index, _) |
294             RootCrate(dep_node_index) => {
295                 self.dep_graph.read_index(dep_node_index);
296             }
297             NotPresent => {
298                 bug!("called HirMap::read() with invalid NodeId")
299             }
300         }
301     }
302
303     #[inline]
304     pub fn definitions(&self) -> &'hir Definitions {
305         self.definitions
306     }
307
308     pub fn def_key(&self, def_id: DefId) -> DefKey {
309         assert!(def_id.is_local());
310         self.definitions.def_key(def_id.index)
311     }
312
313     pub fn def_path_from_id(&self, id: NodeId) -> Option<DefPath> {
314         self.opt_local_def_id(id).map(|def_id| {
315             self.def_path(def_id)
316         })
317     }
318
319     pub fn def_path(&self, def_id: DefId) -> DefPath {
320         assert!(def_id.is_local());
321         self.definitions.def_path(def_id.index)
322     }
323
324     #[inline]
325     pub fn local_def_id(&self, node: NodeId) -> DefId {
326         self.opt_local_def_id(node).unwrap_or_else(|| {
327             bug!("local_def_id: no entry for `{}`, which has a map of `{:?}`",
328                  node, self.find_entry(node))
329         })
330     }
331
332     #[inline]
333     pub fn opt_local_def_id(&self, node: NodeId) -> Option<DefId> {
334         self.definitions.opt_local_def_id(node)
335     }
336
337     #[inline]
338     pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
339         self.definitions.as_local_node_id(def_id)
340     }
341
342     #[inline]
343     pub fn hir_to_node_id(&self, hir_id: HirId) -> NodeId {
344         self.hir_to_node_id[&hir_id]
345     }
346
347     #[inline]
348     pub fn node_to_hir_id(&self, node_id: NodeId) -> HirId {
349         self.definitions.node_to_hir_id(node_id)
350     }
351
352     #[inline]
353     pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> HirId {
354         self.definitions.def_index_to_hir_id(def_index)
355     }
356
357     #[inline]
358     pub fn def_index_to_node_id(&self, def_index: DefIndex) -> NodeId {
359         self.definitions.as_local_node_id(DefId::local(def_index)).unwrap()
360     }
361
362     fn entry_count(&self) -> usize {
363         self.map.len()
364     }
365
366     fn find_entry(&self, id: NodeId) -> Option<MapEntry<'hir>> {
367         self.map.get(id.as_usize()).cloned()
368     }
369
370     pub fn krate(&self) -> &'hir Crate {
371         self.forest.krate()
372     }
373
374     pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem {
375         self.read(id.node_id);
376
377         // NB: intentionally bypass `self.forest.krate()` so that we
378         // do not trigger a read of the whole krate here
379         self.forest.krate.trait_item(id)
380     }
381
382     pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem {
383         self.read(id.node_id);
384
385         // NB: intentionally bypass `self.forest.krate()` so that we
386         // do not trigger a read of the whole krate here
387         self.forest.krate.impl_item(id)
388     }
389
390     pub fn body(&self, id: BodyId) -> &'hir Body {
391         self.read(id.node_id);
392
393         // NB: intentionally bypass `self.forest.krate()` so that we
394         // do not trigger a read of the whole krate here
395         self.forest.krate.body(id)
396     }
397
398     /// Returns the `NodeId` that corresponds to the definition of
399     /// which this is the body of, i.e. a `fn`, `const` or `static`
400     /// item (possibly associated), or a closure, or the body itself
401     /// for embedded constant expressions (e.g. `N` in `[T; N]`).
402     pub fn body_owner(&self, BodyId { node_id }: BodyId) -> NodeId {
403         let parent = self.get_parent_node(node_id);
404         if self.map[parent.as_usize()].is_body_owner(node_id) {
405             parent
406         } else {
407             node_id
408         }
409     }
410
411     pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
412         self.local_def_id(self.body_owner(id))
413     }
414
415     /// Given a node id, returns the `BodyId` associated with it,
416     /// if the node is a body owner, otherwise returns `None`.
417     pub fn maybe_body_owned_by(&self, id: NodeId) -> Option<BodyId> {
418         if let Some(entry) = self.find_entry(id) {
419             if self.dep_graph.is_fully_enabled() {
420                 let hir_id_owner = self.node_to_hir_id(id).owner;
421                 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
422                 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
423             }
424
425             if let Some(body_id) = entry.associated_body() {
426                 // For item-like things and closures, the associated
427                 // body has its own distinct id, and that is returned
428                 // by `associated_body`.
429                 Some(body_id)
430             } else {
431                 // For some expressions, the expression is its own body.
432                 if let EntryExpr(_, _, expr) = entry {
433                     Some(BodyId { node_id: expr.id })
434                 } else {
435                     None
436                 }
437             }
438         } else {
439             bug!("no entry for id `{}`", id)
440         }
441     }
442
443     /// Given a body owner's id, returns the `BodyId` associated with it.
444     pub fn body_owned_by(&self, id: NodeId) -> BodyId {
445         self.maybe_body_owned_by(id).unwrap_or_else(|| {
446             span_bug!(self.span(id), "body_owned_by: {} has no associated body",
447                       self.node_to_string(id));
448         })
449     }
450
451     pub fn body_owner_kind(&self, id: NodeId) -> BodyOwnerKind {
452         // Handle constants in enum discriminants, types, and repeat expressions.
453         let def_id = self.local_def_id(id);
454         let def_key = self.def_key(def_id);
455         if def_key.disambiguated_data.data == DefPathData::Initializer {
456             return BodyOwnerKind::Const;
457         }
458
459         match self.get(id) {
460             NodeItem(&Item { node: ItemConst(..), .. }) |
461             NodeTraitItem(&TraitItem { node: TraitItemKind::Const(..), .. }) |
462             NodeImplItem(&ImplItem { node: ImplItemKind::Const(..), .. }) => {
463                 BodyOwnerKind::Const
464             }
465             NodeItem(&Item { node: ItemStatic(_, m, _), .. }) => {
466                 BodyOwnerKind::Static(m)
467             }
468             // Default to function if it's not a constant or static.
469             _ => BodyOwnerKind::Fn
470         }
471     }
472
473     pub fn ty_param_owner(&self, id: NodeId) -> NodeId {
474         match self.get(id) {
475             NodeItem(&Item { node: ItemTrait(..), .. }) => id,
476             NodeTyParam(_) => self.get_parent_node(id),
477             _ => {
478                 bug!("ty_param_owner: {} not a type parameter",
479                     self.node_to_string(id))
480             }
481         }
482     }
483
484     pub fn ty_param_name(&self, id: NodeId) -> Name {
485         match self.get(id) {
486             NodeItem(&Item { node: ItemTrait(..), .. }) => {
487                 keywords::SelfType.name()
488             }
489             NodeTyParam(tp) => tp.name,
490             _ => {
491                 bug!("ty_param_name: {} not a type parameter",
492                     self.node_to_string(id))
493             }
494         }
495     }
496
497     pub fn trait_impls(&self, trait_did: DefId) -> &'hir [NodeId] {
498         self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
499
500         // NB: intentionally bypass `self.forest.krate()` so that we
501         // do not trigger a read of the whole krate here
502         self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
503     }
504
505     pub fn trait_auto_impl(&self, trait_did: DefId) -> Option<NodeId> {
506         self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
507
508         // NB: intentionally bypass `self.forest.krate()` so that we
509         // do not trigger a read of the whole krate here
510         self.forest.krate.trait_auto_impl.get(&trait_did).cloned()
511     }
512
513     pub fn trait_is_auto(&self, trait_did: DefId) -> bool {
514         self.trait_auto_impl(trait_did).is_some()
515     }
516
517     /// Get the attributes on the krate. This is preferable to
518     /// invoking `krate.attrs` because it registers a tighter
519     /// dep-graph access.
520     pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
521         let def_path_hash = self.definitions.def_path_hash(CRATE_DEF_INDEX);
522
523         self.dep_graph.read(def_path_hash.to_dep_node(DepKind::Hir));
524         &self.forest.krate.attrs
525     }
526
527     /// Retrieve the Node corresponding to `id`, panicking if it cannot
528     /// be found.
529     pub fn get(&self, id: NodeId) -> Node<'hir> {
530         match self.find(id) {
531             Some(node) => node, // read recorded by `find`
532             None => bug!("couldn't find node id {} in the AST map", id)
533         }
534     }
535
536     pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
537         self.as_local_node_id(id).map(|id| self.get(id)) // read recorded by `get`
538     }
539
540     /// Retrieve the Node corresponding to `id`, returning None if
541     /// cannot be found.
542     pub fn find(&self, id: NodeId) -> Option<Node<'hir>> {
543         let result = self.find_entry(id).and_then(|x| x.to_node());
544         if result.is_some() {
545             self.read(id);
546         }
547         result
548     }
549
550     /// Similar to get_parent, returns the parent node id or id if there is no
551     /// parent. Note that the parent may be CRATE_NODE_ID, which is not itself
552     /// present in the map -- so passing the return value of get_parent_node to
553     /// get may actually panic.
554     /// This function returns the immediate parent in the AST, whereas get_parent
555     /// returns the enclosing item. Note that this might not be the actual parent
556     /// node in the AST - some kinds of nodes are not in the map and these will
557     /// never appear as the parent_node. So you can always walk the parent_nodes
558     /// from a node to the root of the ast (unless you get the same id back here
559     /// that can happen if the id is not in the map itself or is just weird).
560     pub fn get_parent_node(&self, id: NodeId) -> NodeId {
561         if self.dep_graph.is_fully_enabled() {
562             let hir_id_owner = self.node_to_hir_id(id).owner;
563             let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
564             self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
565         }
566
567         self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
568     }
569
570     /// Check if the node is an argument. An argument is a local variable whose
571     /// immediate parent is an item or a closure.
572     pub fn is_argument(&self, id: NodeId) -> bool {
573         match self.find(id) {
574             Some(NodeBinding(_)) => (),
575             _ => return false,
576         }
577         match self.find(self.get_parent_node(id)) {
578             Some(NodeItem(_)) |
579             Some(NodeTraitItem(_)) |
580             Some(NodeImplItem(_)) => true,
581             Some(NodeExpr(e)) => {
582                 match e.node {
583                     ExprClosure(..) => true,
584                     _ => false,
585                 }
586             }
587             _ => false,
588         }
589     }
590
591     /// If there is some error when walking the parents (e.g., a node does not
592     /// have a parent in the map or a node can't be found), then we return the
593     /// last good node id we found. Note that reaching the crate root (id == 0),
594     /// is not an error, since items in the crate module have the crate root as
595     /// parent.
596     fn walk_parent_nodes<F, F2>(&self,
597                                 start_id: NodeId,
598                                 found: F,
599                                 bail_early: F2)
600         -> Result<NodeId, NodeId>
601         where F: Fn(&Node<'hir>) -> bool, F2: Fn(&Node<'hir>) -> bool
602     {
603         let mut id = start_id;
604         loop {
605             let parent_node = self.get_parent_node(id);
606             if parent_node == CRATE_NODE_ID {
607                 return Ok(CRATE_NODE_ID);
608             }
609             if parent_node == id {
610                 return Err(id);
611             }
612
613             let node = self.find_entry(parent_node);
614             if node.is_none() {
615                 return Err(id);
616             }
617             let node = node.unwrap().to_node();
618             match node {
619                 Some(ref node) => {
620                     if found(node) {
621                         return Ok(parent_node);
622                     } else if bail_early(node) {
623                         return Err(parent_node);
624                     }
625                 }
626                 None => {
627                     return Err(parent_node);
628                 }
629             }
630             id = parent_node;
631         }
632     }
633
634     /// Retrieve the NodeId for `id`'s enclosing method, unless there's a
635     /// `while` or `loop` before reaching it, as block tail returns are not
636     /// available in them.
637     ///
638     /// ```
639     /// fn foo(x: usize) -> bool {
640     ///     if x == 1 {
641     ///         true  // `get_return_block` gets passed the `id` corresponding
642     ///     } else {  // to this, it will return `foo`'s `NodeId`.
643     ///         false
644     ///     }
645     /// }
646     /// ```
647     ///
648     /// ```
649     /// fn foo(x: usize) -> bool {
650     ///     loop {
651     ///         true  // `get_return_block` gets passed the `id` corresponding
652     ///     }         // to this, it will return `None`.
653     ///     false
654     /// }
655     /// ```
656     pub fn get_return_block(&self, id: NodeId) -> Option<NodeId> {
657         let match_fn = |node: &Node| {
658             match *node {
659                 NodeItem(_) |
660                 NodeForeignItem(_) |
661                 NodeTraitItem(_) |
662                 NodeImplItem(_) => true,
663                 _ => false,
664             }
665         };
666         let match_non_returning_block = |node: &Node| {
667             match *node {
668                 NodeExpr(ref expr) => {
669                     match expr.node {
670                         ExprWhile(..) | ExprLoop(..) => true,
671                         _ => false,
672                     }
673                 }
674                 _ => false,
675             }
676         };
677
678         match self.walk_parent_nodes(id, match_fn, match_non_returning_block) {
679             Ok(id) => Some(id),
680             Err(_) => None,
681         }
682     }
683
684     /// Retrieve the NodeId for `id`'s parent item, or `id` itself if no
685     /// parent item is in this map. The "parent item" is the closest parent node
686     /// in the AST which is recorded by the map and is an item, either an item
687     /// in a module, trait, or impl.
688     pub fn get_parent(&self, id: NodeId) -> NodeId {
689         match self.walk_parent_nodes(id, |node| match *node {
690             NodeItem(_) |
691             NodeForeignItem(_) |
692             NodeTraitItem(_) |
693             NodeImplItem(_) => true,
694             _ => false,
695         }, |_| false) {
696             Ok(id) => id,
697             Err(id) => id,
698         }
699     }
700
701     /// Returns the NodeId of `id`'s nearest module parent, or `id` itself if no
702     /// module parent is in this map.
703     pub fn get_module_parent(&self, id: NodeId) -> DefId {
704         let id = match self.walk_parent_nodes(id, |node| match *node {
705             NodeItem(&Item { node: Item_::ItemMod(_), .. }) => true,
706             _ => false,
707         }, |_| false) {
708             Ok(id) => id,
709             Err(id) => id,
710         };
711         self.local_def_id(id)
712     }
713
714     /// Returns the nearest enclosing scope. A scope is an item or block.
715     /// FIXME it is not clear to me that all items qualify as scopes - statics
716     /// and associated types probably shouldn't, for example. Behavior in this
717     /// regard should be expected to be highly unstable.
718     pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
719         match self.walk_parent_nodes(id, |node| match *node {
720             NodeItem(_) |
721             NodeForeignItem(_) |
722             NodeTraitItem(_) |
723             NodeImplItem(_) |
724             NodeBlock(_) => true,
725             _ => false,
726         }, |_| false) {
727             Ok(id) => Some(id),
728             Err(_) => None,
729         }
730     }
731
732     pub fn get_parent_did(&self, id: NodeId) -> DefId {
733         self.local_def_id(self.get_parent(id))
734     }
735
736     pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
737         let parent = self.get_parent(id);
738         let abi = match self.find_entry(parent) {
739             Some(EntryItem(_, _, i)) => {
740                 match i.node {
741                     ItemForeignMod(ref nm) => Some(nm.abi),
742                     _ => None
743                 }
744             }
745             _ => None
746         };
747         match abi {
748             Some(abi) => {
749                 self.read(id); // reveals some of the content of a node
750                 abi
751             }
752             None => bug!("expected foreign mod or inlined parent, found {}",
753                           self.node_to_string(parent))
754         }
755     }
756
757     pub fn expect_item(&self, id: NodeId) -> &'hir Item {
758         match self.find(id) { // read recorded by `find`
759             Some(NodeItem(item)) => item,
760             _ => bug!("expected item, found {}", self.node_to_string(id))
761         }
762     }
763
764     pub fn expect_impl_item(&self, id: NodeId) -> &'hir ImplItem {
765         match self.find(id) {
766             Some(NodeImplItem(item)) => item,
767             _ => bug!("expected impl item, found {}", self.node_to_string(id))
768         }
769     }
770
771     pub fn expect_trait_item(&self, id: NodeId) -> &'hir TraitItem {
772         match self.find(id) {
773             Some(NodeTraitItem(item)) => item,
774             _ => bug!("expected trait item, found {}", self.node_to_string(id))
775         }
776     }
777
778     pub fn expect_variant_data(&self, id: NodeId) -> &'hir VariantData {
779         match self.find(id) {
780             Some(NodeItem(i)) => {
781                 match i.node {
782                     ItemStruct(ref struct_def, _) |
783                     ItemUnion(ref struct_def, _) => struct_def,
784                     _ => {
785                         bug!("struct ID bound to non-struct {}",
786                              self.node_to_string(id));
787                     }
788                 }
789             }
790             Some(NodeStructCtor(data)) => data,
791             Some(NodeVariant(variant)) => &variant.node.data,
792             _ => {
793                 bug!("expected struct or variant, found {}",
794                      self.node_to_string(id));
795             }
796         }
797     }
798
799     pub fn expect_variant(&self, id: NodeId) -> &'hir Variant {
800         match self.find(id) {
801             Some(NodeVariant(variant)) => variant,
802             _ => bug!("expected variant, found {}", self.node_to_string(id)),
803         }
804     }
805
806     pub fn expect_foreign_item(&self, id: NodeId) -> &'hir ForeignItem {
807         match self.find(id) {
808             Some(NodeForeignItem(item)) => item,
809             _ => bug!("expected foreign item, found {}", self.node_to_string(id))
810         }
811     }
812
813     pub fn expect_expr(&self, id: NodeId) -> &'hir Expr {
814         match self.find(id) { // read recorded by find
815             Some(NodeExpr(expr)) => expr,
816             _ => bug!("expected expr, found {}", self.node_to_string(id))
817         }
818     }
819
820     pub fn get_inlined_body_untracked(&self, def_id: DefId) -> Option<&'hir Body> {
821         self.inlined_bodies.borrow().get(&def_id).cloned()
822     }
823
824     pub fn intern_inlined_body(&self, def_id: DefId, body: Body) -> &'hir Body {
825         let body = self.forest.inlined_bodies.alloc(body);
826         self.inlined_bodies.borrow_mut().insert(def_id, body);
827         body
828     }
829
830     /// Returns the name associated with the given NodeId's AST.
831     pub fn name(&self, id: NodeId) -> Name {
832         match self.get(id) {
833             NodeItem(i) => i.name,
834             NodeForeignItem(i) => i.name,
835             NodeImplItem(ii) => ii.name,
836             NodeTraitItem(ti) => ti.name,
837             NodeVariant(v) => v.node.name,
838             NodeField(f) => f.name,
839             NodeLifetime(lt) => lt.name.name(),
840             NodeTyParam(tp) => tp.name,
841             NodeBinding(&Pat { node: PatKind::Binding(_,_,l,_), .. }) => l.node,
842             NodeStructCtor(_) => self.name(self.get_parent(id)),
843             _ => bug!("no name for {}", self.node_to_string(id))
844         }
845     }
846
847     /// Given a node ID, get a list of attributes associated with the AST
848     /// corresponding to the Node ID
849     pub fn attrs(&self, id: NodeId) -> &'hir [ast::Attribute] {
850         self.read(id); // reveals attributes on the node
851         let attrs = match self.find(id) {
852             Some(NodeItem(i)) => Some(&i.attrs[..]),
853             Some(NodeForeignItem(fi)) => Some(&fi.attrs[..]),
854             Some(NodeTraitItem(ref ti)) => Some(&ti.attrs[..]),
855             Some(NodeImplItem(ref ii)) => Some(&ii.attrs[..]),
856             Some(NodeVariant(ref v)) => Some(&v.node.attrs[..]),
857             Some(NodeField(ref f)) => Some(&f.attrs[..]),
858             Some(NodeExpr(ref e)) => Some(&*e.attrs),
859             Some(NodeStmt(ref s)) => Some(s.node.attrs()),
860             // unit/tuple structs take the attributes straight from
861             // the struct definition.
862             Some(NodeStructCtor(_)) => {
863                 return self.attrs(self.get_parent(id));
864             }
865             _ => None
866         };
867         attrs.unwrap_or(&[])
868     }
869
870     /// Returns an iterator that yields the node id's with paths that
871     /// match `parts`.  (Requires `parts` is non-empty.)
872     ///
873     /// For example, if given `parts` equal to `["bar", "quux"]`, then
874     /// the iterator will produce node id's for items with paths
875     /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
876     /// any other such items it can find in the map.
877     pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
878                                  -> NodesMatchingSuffix<'a, 'hir> {
879         NodesMatchingSuffix {
880             map: self,
881             item_name: parts.last().unwrap(),
882             in_which: &parts[..parts.len() - 1],
883             idx: CRATE_NODE_ID,
884         }
885     }
886
887     pub fn span(&self, id: NodeId) -> Span {
888         self.read(id); // reveals span from node
889         match self.find_entry(id) {
890             Some(EntryItem(_, _, item)) => item.span,
891             Some(EntryForeignItem(_, _, foreign_item)) => foreign_item.span,
892             Some(EntryTraitItem(_, _, trait_method)) => trait_method.span,
893             Some(EntryImplItem(_, _, impl_item)) => impl_item.span,
894             Some(EntryVariant(_, _, variant)) => variant.span,
895             Some(EntryField(_, _, field)) => field.span,
896             Some(EntryExpr(_, _, expr)) => expr.span,
897             Some(EntryStmt(_, _, stmt)) => stmt.span,
898             Some(EntryTy(_, _, ty)) => ty.span,
899             Some(EntryTraitRef(_, _, tr)) => tr.path.span,
900             Some(EntryBinding(_, _, pat)) => pat.span,
901             Some(EntryPat(_, _, pat)) => pat.span,
902             Some(EntryBlock(_, _, block)) => block.span,
903             Some(EntryStructCtor(_, _, _)) => self.expect_item(self.get_parent(id)).span,
904             Some(EntryLifetime(_, _, lifetime)) => lifetime.span,
905             Some(EntryTyParam(_, _, ty_param)) => ty_param.span,
906             Some(EntryVisibility(_, _, &Visibility::Restricted { ref path, .. })) => path.span,
907             Some(EntryVisibility(_, _, v)) => bug!("unexpected Visibility {:?}", v),
908             Some(EntryLocal(_, _, local)) => local.span,
909             Some(EntryMacroDef(_, macro_def)) => macro_def.span,
910
911             Some(RootCrate(_)) => self.forest.krate.span,
912             Some(NotPresent) | None => {
913                 bug!("hir::map::Map::span: id not in map: {:?}", id)
914             }
915         }
916     }
917
918     pub fn span_if_local(&self, id: DefId) -> Option<Span> {
919         self.as_local_node_id(id).map(|id| self.span(id))
920     }
921
922     pub fn node_to_string(&self, id: NodeId) -> String {
923         node_id_to_string(self, id, true)
924     }
925
926     pub fn node_to_user_string(&self, id: NodeId) -> String {
927         node_id_to_string(self, id, false)
928     }
929
930     pub fn node_to_pretty_string(&self, id: NodeId) -> String {
931         print::to_string(self, |s| s.print_node(self.get(id)))
932     }
933 }
934
935 pub struct NodesMatchingSuffix<'a, 'hir:'a> {
936     map: &'a Map<'hir>,
937     item_name: &'a String,
938     in_which: &'a [String],
939     idx: NodeId,
940 }
941
942 impl<'a, 'hir> NodesMatchingSuffix<'a, 'hir> {
943     /// Returns true only if some suffix of the module path for parent
944     /// matches `self.in_which`.
945     ///
946     /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
947     /// returns true if parent's path ends with the suffix
948     /// `x_0::x_1::...::x_k`.
949     fn suffix_matches(&self, parent: NodeId) -> bool {
950         let mut cursor = parent;
951         for part in self.in_which.iter().rev() {
952             let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
953                 None => return false,
954                 Some((node_id, name)) => (node_id, name),
955             };
956             if mod_name != &**part {
957                 return false;
958             }
959             cursor = self.map.get_parent(mod_id);
960         }
961         return true;
962
963         // Finds the first mod in parent chain for `id`, along with
964         // that mod's name.
965         //
966         // If `id` itself is a mod named `m` with parent `p`, then
967         // returns `Some(id, m, p)`.  If `id` has no mod in its parent
968         // chain, then returns `None`.
969         fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
970             loop {
971                 match map.find(id) {
972                     None => return None,
973                     Some(NodeItem(item)) if item_is_mod(&item) =>
974                         return Some((id, item.name)),
975                     _ => {}
976                 }
977                 let parent = map.get_parent(id);
978                 if parent == id { return None }
979                 id = parent;
980             }
981
982             fn item_is_mod(item: &Item) -> bool {
983                 match item.node {
984                     ItemMod(_) => true,
985                     _ => false,
986                 }
987             }
988         }
989     }
990
991     // We are looking at some node `n` with a given name and parent
992     // id; do their names match what I am seeking?
993     fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
994         name == &**self.item_name && self.suffix_matches(parent_of_n)
995     }
996 }
997
998 impl<'a, 'hir> Iterator for NodesMatchingSuffix<'a, 'hir> {
999     type Item = NodeId;
1000
1001     fn next(&mut self) -> Option<NodeId> {
1002         loop {
1003             let idx = self.idx;
1004             if idx.as_usize() >= self.map.entry_count() {
1005                 return None;
1006             }
1007             self.idx = NodeId::from_u32(self.idx.as_u32() + 1);
1008             let name = match self.map.find_entry(idx) {
1009                 Some(EntryItem(_, _, n))       => n.name(),
1010                 Some(EntryForeignItem(_, _, n))=> n.name(),
1011                 Some(EntryTraitItem(_, _, n))  => n.name(),
1012                 Some(EntryImplItem(_, _, n))   => n.name(),
1013                 Some(EntryVariant(_, _, n))    => n.name(),
1014                 Some(EntryField(_, _, n))      => n.name(),
1015                 _ => continue,
1016             };
1017             if self.matches_names(self.map.get_parent(idx), name) {
1018                 return Some(idx)
1019             }
1020         }
1021     }
1022 }
1023
1024 trait Named {
1025     fn name(&self) -> Name;
1026 }
1027
1028 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
1029
1030 impl Named for Item { fn name(&self) -> Name { self.name } }
1031 impl Named for ForeignItem { fn name(&self) -> Name { self.name } }
1032 impl Named for Variant_ { fn name(&self) -> Name { self.name } }
1033 impl Named for StructField { fn name(&self) -> Name { self.name } }
1034 impl Named for TraitItem { fn name(&self) -> Name { self.name } }
1035 impl Named for ImplItem { fn name(&self) -> Name { self.name } }
1036
1037 pub fn map_crate<'hir>(sess: &::session::Session,
1038                        cstore: &::middle::cstore::CrateStore,
1039                        forest: &'hir mut Forest,
1040                        definitions: &'hir Definitions)
1041                        -> Map<'hir> {
1042     let map = {
1043         let hcx = ::ich::StableHashingContext::new(sess, &forest.krate, definitions, cstore);
1044
1045         let mut collector = NodeCollector::root(&forest.krate,
1046                                                 &forest.dep_graph,
1047                                                 &definitions,
1048                                                 hcx);
1049         intravisit::walk_crate(&mut collector, &forest.krate);
1050
1051         let crate_disambiguator = sess.local_crate_disambiguator();
1052         collector.finalize_and_compute_crate_hash(crate_disambiguator)
1053     };
1054
1055     if log_enabled!(::log::LogLevel::Debug) {
1056         // This only makes sense for ordered stores; note the
1057         // enumerate to count the number of entries.
1058         let (entries_less_1, _) = map.iter().filter(|&x| {
1059             match *x {
1060                 NotPresent => false,
1061                 _ => true
1062             }
1063         }).enumerate().last().expect("AST map was empty after folding?");
1064
1065         let entries = entries_less_1 + 1;
1066         let vector_length = map.len();
1067         debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
1068               entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
1069     }
1070
1071     // Build the reverse mapping of `node_to_hir_id`.
1072     let hir_to_node_id = definitions.node_to_hir_id.iter_enumerated()
1073         .map(|(node_id, &hir_id)| (hir_id, node_id)).collect();
1074
1075     let map = Map {
1076         forest,
1077         dep_graph: forest.dep_graph.clone(),
1078         map,
1079         hir_to_node_id,
1080         definitions,
1081         inlined_bodies: RefCell::new(DefIdMap()),
1082     };
1083
1084     hir_id_validator::check_crate(&map);
1085
1086     map
1087 }
1088
1089 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1090 /// except it avoids creating a dependency on the whole crate.
1091 impl<'hir> print::PpAnn for Map<'hir> {
1092     fn nested(&self, state: &mut print::State, nested: print::Nested) -> io::Result<()> {
1093         match nested {
1094             Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1095             Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1096             Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1097             Nested::Body(id) => state.print_expr(&self.body(id).value),
1098             Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
1099         }
1100     }
1101 }
1102
1103 impl<'a> print::State<'a> {
1104     pub fn print_node(&mut self, node: Node) -> io::Result<()> {
1105         match node {
1106             NodeItem(a)        => self.print_item(&a),
1107             NodeForeignItem(a) => self.print_foreign_item(&a),
1108             NodeTraitItem(a)   => self.print_trait_item(a),
1109             NodeImplItem(a)    => self.print_impl_item(a),
1110             NodeVariant(a)     => self.print_variant(&a),
1111             NodeExpr(a)        => self.print_expr(&a),
1112             NodeStmt(a)        => self.print_stmt(&a),
1113             NodeTy(a)          => self.print_type(&a),
1114             NodeTraitRef(a)    => self.print_trait_ref(&a),
1115             NodeBinding(a)       |
1116             NodePat(a)         => self.print_pat(&a),
1117             NodeBlock(a)       => {
1118                 use syntax::print::pprust::PrintState;
1119
1120                 // containing cbox, will be closed by print-block at }
1121                 self.cbox(print::indent_unit)?;
1122                 // head-ibox, will be closed by print-block after {
1123                 self.ibox(0)?;
1124                 self.print_block(&a)
1125             }
1126             NodeLifetime(a)    => self.print_lifetime(&a),
1127             NodeVisibility(a)  => self.print_visibility(&a),
1128             NodeTyParam(_)     => bug!("cannot print TyParam"),
1129             NodeField(_)       => bug!("cannot print StructField"),
1130             // these cases do not carry enough information in the
1131             // hir_map to reconstruct their full structure for pretty
1132             // printing.
1133             NodeStructCtor(_)  => bug!("cannot print isolated StructCtor"),
1134             NodeLocal(a)       => self.print_local_decl(&a),
1135             NodeMacroDef(_)    => bug!("cannot print MacroDef"),
1136         }
1137     }
1138 }
1139
1140 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
1141     let id_str = format!(" (id={})", id);
1142     let id_str = if include_id { &id_str[..] } else { "" };
1143
1144     let path_str = || {
1145         // This functionality is used for debugging, try to use TyCtxt to get
1146         // the user-friendly path, otherwise fall back to stringifying DefPath.
1147         ::ty::tls::with_opt(|tcx| {
1148             if let Some(tcx) = tcx {
1149                 tcx.node_path_str(id)
1150             } else if let Some(path) = map.def_path_from_id(id) {
1151                 path.data.into_iter().map(|elem| {
1152                     elem.data.to_string()
1153                 }).collect::<Vec<_>>().join("::")
1154             } else {
1155                 String::from("<missing path>")
1156             }
1157         })
1158     };
1159
1160     match map.find(id) {
1161         Some(NodeItem(item)) => {
1162             let item_str = match item.node {
1163                 ItemExternCrate(..) => "extern crate",
1164                 ItemUse(..) => "use",
1165                 ItemStatic(..) => "static",
1166                 ItemConst(..) => "const",
1167                 ItemFn(..) => "fn",
1168                 ItemMod(..) => "mod",
1169                 ItemForeignMod(..) => "foreign mod",
1170                 ItemGlobalAsm(..) => "global asm",
1171                 ItemTy(..) => "ty",
1172                 ItemEnum(..) => "enum",
1173                 ItemStruct(..) => "struct",
1174                 ItemUnion(..) => "union",
1175                 ItemTrait(..) => "trait",
1176                 ItemImpl(..) => "impl",
1177                 ItemAutoImpl(..) => "default impl",
1178             };
1179             format!("{} {}{}", item_str, path_str(), id_str)
1180         }
1181         Some(NodeForeignItem(_)) => {
1182             format!("foreign item {}{}", path_str(), id_str)
1183         }
1184         Some(NodeImplItem(ii)) => {
1185             match ii.node {
1186                 ImplItemKind::Const(..) => {
1187                     format!("assoc const {} in {}{}", ii.name, path_str(), id_str)
1188                 }
1189                 ImplItemKind::Method(..) => {
1190                     format!("method {} in {}{}", ii.name, path_str(), id_str)
1191                 }
1192                 ImplItemKind::Type(_) => {
1193                     format!("assoc type {} in {}{}", ii.name, path_str(), id_str)
1194                 }
1195             }
1196         }
1197         Some(NodeTraitItem(ti)) => {
1198             let kind = match ti.node {
1199                 TraitItemKind::Const(..) => "assoc constant",
1200                 TraitItemKind::Method(..) => "trait method",
1201                 TraitItemKind::Type(..) => "assoc type",
1202             };
1203
1204             format!("{} {} in {}{}", kind, ti.name, path_str(), id_str)
1205         }
1206         Some(NodeVariant(ref variant)) => {
1207             format!("variant {} in {}{}",
1208                     variant.node.name,
1209                     path_str(), id_str)
1210         }
1211         Some(NodeField(ref field)) => {
1212             format!("field {} in {}{}",
1213                     field.name,
1214                     path_str(), id_str)
1215         }
1216         Some(NodeExpr(_)) => {
1217             format!("expr {}{}", map.node_to_pretty_string(id), id_str)
1218         }
1219         Some(NodeStmt(_)) => {
1220             format!("stmt {}{}", map.node_to_pretty_string(id), id_str)
1221         }
1222         Some(NodeTy(_)) => {
1223             format!("type {}{}", map.node_to_pretty_string(id), id_str)
1224         }
1225         Some(NodeTraitRef(_)) => {
1226             format!("trait_ref {}{}", map.node_to_pretty_string(id), id_str)
1227         }
1228         Some(NodeBinding(_)) => {
1229             format!("local {}{}", map.node_to_pretty_string(id), id_str)
1230         }
1231         Some(NodePat(_)) => {
1232             format!("pat {}{}", map.node_to_pretty_string(id), id_str)
1233         }
1234         Some(NodeBlock(_)) => {
1235             format!("block {}{}", map.node_to_pretty_string(id), id_str)
1236         }
1237         Some(NodeLocal(_)) => {
1238             format!("local {}{}", map.node_to_pretty_string(id), id_str)
1239         }
1240         Some(NodeStructCtor(_)) => {
1241             format!("struct_ctor {}{}", path_str(), id_str)
1242         }
1243         Some(NodeLifetime(_)) => {
1244             format!("lifetime {}{}", map.node_to_pretty_string(id), id_str)
1245         }
1246         Some(NodeTyParam(ref ty_param)) => {
1247             format!("typaram {:?}{}", ty_param, id_str)
1248         }
1249         Some(NodeVisibility(ref vis)) => {
1250             format!("visibility {:?}{}", vis, id_str)
1251         }
1252         Some(NodeMacroDef(_)) => {
1253             format!("macro {}{}",  path_str(), id_str)
1254         }
1255         None => {
1256             format!("unknown node{}", id_str)
1257         }
1258     }
1259 }