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