]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/map/mod.rs
Rollup merge of #51765 - jonas-schievink:patch-1, r=KodrAus
[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;
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     /// Retrieve the Node corresponding to `id`, returning None if
668     /// cannot be found.
669     pub fn find(&self, id: NodeId) -> Option<Node<'hir>> {
670         let result = self.find_entry(id).and_then(|x| x.to_node());
671         if result.is_some() {
672             self.read(id);
673         }
674         result
675     }
676
677     /// Similar to get_parent, returns the parent node id or id if there is no
678     /// parent. Note that the parent may be CRATE_NODE_ID, which is not itself
679     /// present in the map -- so passing the return value of get_parent_node to
680     /// get may actually panic.
681     /// This function returns the immediate parent in the AST, whereas get_parent
682     /// returns the enclosing item. Note that this might not be the actual parent
683     /// node in the AST - some kinds of nodes are not in the map and these will
684     /// never appear as the parent_node. So you can always walk the parent_nodes
685     /// from a node to the root of the ast (unless you get the same id back here
686     /// that can happen if the id is not in the map itself or is just weird).
687     pub fn get_parent_node(&self, id: NodeId) -> NodeId {
688         if self.dep_graph.is_fully_enabled() {
689             let hir_id_owner = self.node_to_hir_id(id).owner;
690             let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
691             self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
692         }
693
694         self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
695     }
696
697     /// Check if the node is an argument. An argument is a local variable whose
698     /// immediate parent is an item or a closure.
699     pub fn is_argument(&self, id: NodeId) -> bool {
700         match self.find(id) {
701             Some(NodeBinding(_)) => (),
702             _ => return false,
703         }
704         match self.find(self.get_parent_node(id)) {
705             Some(NodeItem(_)) |
706             Some(NodeTraitItem(_)) |
707             Some(NodeImplItem(_)) => true,
708             Some(NodeExpr(e)) => {
709                 match e.node {
710                     ExprClosure(..) => true,
711                     _ => false,
712                 }
713             }
714             _ => false,
715         }
716     }
717
718     /// If there is some error when walking the parents (e.g., a node does not
719     /// have a parent in the map or a node can't be found), then we return the
720     /// last good node id we found. Note that reaching the crate root (id == 0),
721     /// is not an error, since items in the crate module have the crate root as
722     /// parent.
723     fn walk_parent_nodes<F, F2>(&self,
724                                 start_id: NodeId,
725                                 found: F,
726                                 bail_early: F2)
727         -> Result<NodeId, NodeId>
728         where F: Fn(&Node<'hir>) -> bool, F2: Fn(&Node<'hir>) -> bool
729     {
730         let mut id = start_id;
731         loop {
732             let parent_node = self.get_parent_node(id);
733             if parent_node == CRATE_NODE_ID {
734                 return Ok(CRATE_NODE_ID);
735             }
736             if parent_node == id {
737                 return Err(id);
738             }
739
740             let node = self.find_entry(parent_node);
741             if node.is_none() {
742                 return Err(id);
743             }
744             let node = node.unwrap().to_node();
745             match node {
746                 Some(ref node) => {
747                     if found(node) {
748                         return Ok(parent_node);
749                     } else if bail_early(node) {
750                         return Err(parent_node);
751                     }
752                 }
753                 None => {
754                     return Err(parent_node);
755                 }
756             }
757             id = parent_node;
758         }
759     }
760
761     /// Retrieve the NodeId for `id`'s enclosing method, unless there's a
762     /// `while` or `loop` before reaching it, as block tail returns are not
763     /// available in them.
764     ///
765     /// ```
766     /// fn foo(x: usize) -> bool {
767     ///     if x == 1 {
768     ///         true  // `get_return_block` gets passed the `id` corresponding
769     ///     } else {  // to this, it will return `foo`'s `NodeId`.
770     ///         false
771     ///     }
772     /// }
773     /// ```
774     ///
775     /// ```
776     /// fn foo(x: usize) -> bool {
777     ///     loop {
778     ///         true  // `get_return_block` gets passed the `id` corresponding
779     ///     }         // to this, it will return `None`.
780     ///     false
781     /// }
782     /// ```
783     pub fn get_return_block(&self, id: NodeId) -> Option<NodeId> {
784         let match_fn = |node: &Node| {
785             match *node {
786                 NodeItem(_) |
787                 NodeForeignItem(_) |
788                 NodeTraitItem(_) |
789                 NodeImplItem(_) => true,
790                 _ => false,
791             }
792         };
793         let match_non_returning_block = |node: &Node| {
794             match *node {
795                 NodeExpr(ref expr) => {
796                     match expr.node {
797                         ExprWhile(..) | ExprLoop(..) => true,
798                         _ => false,
799                     }
800                 }
801                 _ => false,
802             }
803         };
804
805         match self.walk_parent_nodes(id, match_fn, match_non_returning_block) {
806             Ok(id) => Some(id),
807             Err(_) => None,
808         }
809     }
810
811     /// Retrieve the NodeId for `id`'s parent item, or `id` itself if no
812     /// parent item is in this map. The "parent item" is the closest parent node
813     /// in the HIR which is recorded by the map and is an item, either an item
814     /// in a module, trait, or impl.
815     pub fn get_parent(&self, id: NodeId) -> NodeId {
816         match self.walk_parent_nodes(id, |node| match *node {
817             NodeItem(_) |
818             NodeForeignItem(_) |
819             NodeTraitItem(_) |
820             NodeImplItem(_) => true,
821             _ => false,
822         }, |_| false) {
823             Ok(id) => id,
824             Err(id) => id,
825         }
826     }
827
828     /// Returns the NodeId of `id`'s nearest module parent, or `id` itself if no
829     /// module parent is in this map.
830     pub fn get_module_parent(&self, id: NodeId) -> DefId {
831         let id = match self.walk_parent_nodes(id, |node| match *node {
832             NodeItem(&Item { node: Item_::ItemMod(_), .. }) => true,
833             _ => false,
834         }, |_| false) {
835             Ok(id) => id,
836             Err(id) => id,
837         };
838         self.local_def_id(id)
839     }
840
841     /// Returns the nearest enclosing scope. A scope is an item or block.
842     /// FIXME it is not clear to me that all items qualify as scopes - statics
843     /// and associated types probably shouldn't, for example. Behavior in this
844     /// regard should be expected to be highly unstable.
845     pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
846         match self.walk_parent_nodes(id, |node| match *node {
847             NodeItem(_) |
848             NodeForeignItem(_) |
849             NodeTraitItem(_) |
850             NodeImplItem(_) |
851             NodeBlock(_) => true,
852             _ => false,
853         }, |_| false) {
854             Ok(id) => Some(id),
855             Err(_) => None,
856         }
857     }
858
859     pub fn get_parent_did(&self, id: NodeId) -> DefId {
860         self.local_def_id(self.get_parent(id))
861     }
862
863     pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
864         let parent = self.get_parent(id);
865         let abi = match self.find_entry(parent) {
866             Some(EntryItem(_, _, i)) => {
867                 match i.node {
868                     ItemForeignMod(ref nm) => Some(nm.abi),
869                     _ => None
870                 }
871             }
872             _ => None
873         };
874         match abi {
875             Some(abi) => {
876                 self.read(id); // reveals some of the content of a node
877                 abi
878             }
879             None => bug!("expected foreign mod or inlined parent, found {}",
880                           self.node_to_string(parent))
881         }
882     }
883
884     pub fn expect_item(&self, id: NodeId) -> &'hir Item {
885         match self.find(id) { // read recorded by `find`
886             Some(NodeItem(item)) => item,
887             _ => bug!("expected item, found {}", self.node_to_string(id))
888         }
889     }
890
891     pub fn expect_impl_item(&self, id: NodeId) -> &'hir ImplItem {
892         match self.find(id) {
893             Some(NodeImplItem(item)) => item,
894             _ => bug!("expected impl item, found {}", self.node_to_string(id))
895         }
896     }
897
898     pub fn expect_trait_item(&self, id: NodeId) -> &'hir TraitItem {
899         match self.find(id) {
900             Some(NodeTraitItem(item)) => item,
901             _ => bug!("expected trait item, found {}", self.node_to_string(id))
902         }
903     }
904
905     pub fn expect_variant_data(&self, id: NodeId) -> &'hir VariantData {
906         match self.find(id) {
907             Some(NodeItem(i)) => {
908                 match i.node {
909                     ItemStruct(ref struct_def, _) |
910                     ItemUnion(ref struct_def, _) => struct_def,
911                     _ => {
912                         bug!("struct ID bound to non-struct {}",
913                              self.node_to_string(id));
914                     }
915                 }
916             }
917             Some(NodeStructCtor(data)) => data,
918             Some(NodeVariant(variant)) => &variant.node.data,
919             _ => {
920                 bug!("expected struct or variant, found {}",
921                      self.node_to_string(id));
922             }
923         }
924     }
925
926     pub fn expect_variant(&self, id: NodeId) -> &'hir Variant {
927         match self.find(id) {
928             Some(NodeVariant(variant)) => variant,
929             _ => bug!("expected variant, found {}", self.node_to_string(id)),
930         }
931     }
932
933     pub fn expect_foreign_item(&self, id: NodeId) -> &'hir ForeignItem {
934         match self.find(id) {
935             Some(NodeForeignItem(item)) => item,
936             _ => bug!("expected foreign item, found {}", self.node_to_string(id))
937         }
938     }
939
940     pub fn expect_expr(&self, id: NodeId) -> &'hir Expr {
941         match self.find(id) { // read recorded by find
942             Some(NodeExpr(expr)) => expr,
943             _ => bug!("expected expr, found {}", self.node_to_string(id))
944         }
945     }
946
947     /// Returns the name associated with the given NodeId's AST.
948     pub fn name(&self, id: NodeId) -> Name {
949         match self.get(id) {
950             NodeItem(i) => i.name,
951             NodeForeignItem(i) => i.name,
952             NodeImplItem(ii) => ii.ident.name,
953             NodeTraitItem(ti) => ti.ident.name,
954             NodeVariant(v) => v.node.name,
955             NodeField(f) => f.ident.name,
956             NodeLifetime(lt) => lt.name.ident().name,
957             NodeGenericParam(param) => param.name.ident().name,
958             NodeBinding(&Pat { node: PatKind::Binding(_,_,l,_), .. }) => l.name,
959             NodeStructCtor(_) => self.name(self.get_parent(id)),
960             _ => bug!("no name for {}", self.node_to_string(id))
961         }
962     }
963
964     /// Given a node ID, get a list of attributes associated with the AST
965     /// corresponding to the Node ID
966     pub fn attrs(&self, id: NodeId) -> &'hir [ast::Attribute] {
967         self.read(id); // reveals attributes on the node
968         let attrs = match self.find(id) {
969             Some(NodeItem(i)) => Some(&i.attrs[..]),
970             Some(NodeForeignItem(fi)) => Some(&fi.attrs[..]),
971             Some(NodeTraitItem(ref ti)) => Some(&ti.attrs[..]),
972             Some(NodeImplItem(ref ii)) => Some(&ii.attrs[..]),
973             Some(NodeVariant(ref v)) => Some(&v.node.attrs[..]),
974             Some(NodeField(ref f)) => Some(&f.attrs[..]),
975             Some(NodeExpr(ref e)) => Some(&*e.attrs),
976             Some(NodeStmt(ref s)) => Some(s.node.attrs()),
977             Some(NodeGenericParam(param)) => Some(&param.attrs[..]),
978             // unit/tuple structs take the attributes straight from
979             // the struct definition.
980             Some(NodeStructCtor(_)) => {
981                 return self.attrs(self.get_parent(id));
982             }
983             _ => None
984         };
985         attrs.unwrap_or(&[])
986     }
987
988     /// Returns an iterator that yields the node id's with paths that
989     /// match `parts`.  (Requires `parts` is non-empty.)
990     ///
991     /// For example, if given `parts` equal to `["bar", "quux"]`, then
992     /// the iterator will produce node id's for items with paths
993     /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
994     /// any other such items it can find in the map.
995     pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
996                                  -> NodesMatchingSuffix<'a, 'hir> {
997         NodesMatchingSuffix {
998             map: self,
999             item_name: parts.last().unwrap(),
1000             in_which: &parts[..parts.len() - 1],
1001             idx: CRATE_NODE_ID,
1002         }
1003     }
1004
1005     pub fn span(&self, id: NodeId) -> Span {
1006         self.read(id); // reveals span from node
1007         match self.find_entry(id) {
1008             Some(EntryItem(_, _, item)) => item.span,
1009             Some(EntryForeignItem(_, _, foreign_item)) => foreign_item.span,
1010             Some(EntryTraitItem(_, _, trait_method)) => trait_method.span,
1011             Some(EntryImplItem(_, _, impl_item)) => impl_item.span,
1012             Some(EntryVariant(_, _, variant)) => variant.span,
1013             Some(EntryField(_, _, field)) => field.span,
1014             Some(EntryAnonConst(_, _, constant)) => self.body(constant.body).value.span,
1015             Some(EntryExpr(_, _, expr)) => expr.span,
1016             Some(EntryStmt(_, _, stmt)) => stmt.span,
1017             Some(EntryTy(_, _, ty)) => ty.span,
1018             Some(EntryTraitRef(_, _, tr)) => tr.path.span,
1019             Some(EntryBinding(_, _, pat)) => pat.span,
1020             Some(EntryPat(_, _, pat)) => pat.span,
1021             Some(EntryBlock(_, _, block)) => block.span,
1022             Some(EntryStructCtor(_, _, _)) => self.expect_item(self.get_parent(id)).span,
1023             Some(EntryLifetime(_, _, lifetime)) => lifetime.span,
1024             Some(EntryGenericParam(_, _, param)) => param.span,
1025             Some(EntryVisibility(_, _, &Visibility::Restricted { ref path, .. })) => path.span,
1026             Some(EntryVisibility(_, _, v)) => bug!("unexpected Visibility {:?}", v),
1027             Some(EntryLocal(_, _, local)) => local.span,
1028             Some(EntryMacroDef(_, macro_def)) => macro_def.span,
1029
1030             Some(RootCrate(_)) => self.forest.krate.span,
1031             Some(NotPresent) | None => {
1032                 bug!("hir::map::Map::span: id not in map: {:?}", id)
1033             }
1034         }
1035     }
1036
1037     pub fn span_if_local(&self, id: DefId) -> Option<Span> {
1038         self.as_local_node_id(id).map(|id| self.span(id))
1039     }
1040
1041     pub fn node_to_string(&self, id: NodeId) -> String {
1042         node_id_to_string(self, id, true)
1043     }
1044
1045     pub fn node_to_user_string(&self, id: NodeId) -> String {
1046         node_id_to_string(self, id, false)
1047     }
1048
1049     pub fn node_to_pretty_string(&self, id: NodeId) -> String {
1050         print::to_string(self, |s| s.print_node(self.get(id)))
1051     }
1052 }
1053
1054 pub struct NodesMatchingSuffix<'a, 'hir:'a> {
1055     map: &'a Map<'hir>,
1056     item_name: &'a String,
1057     in_which: &'a [String],
1058     idx: NodeId,
1059 }
1060
1061 impl<'a, 'hir> NodesMatchingSuffix<'a, 'hir> {
1062     /// Returns true only if some suffix of the module path for parent
1063     /// matches `self.in_which`.
1064     ///
1065     /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
1066     /// returns true if parent's path ends with the suffix
1067     /// `x_0::x_1::...::x_k`.
1068     fn suffix_matches(&self, parent: NodeId) -> bool {
1069         let mut cursor = parent;
1070         for part in self.in_which.iter().rev() {
1071             let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
1072                 None => return false,
1073                 Some((node_id, name)) => (node_id, name),
1074             };
1075             if mod_name != &**part {
1076                 return false;
1077             }
1078             cursor = self.map.get_parent(mod_id);
1079         }
1080         return true;
1081
1082         // Finds the first mod in parent chain for `id`, along with
1083         // that mod's name.
1084         //
1085         // If `id` itself is a mod named `m` with parent `p`, then
1086         // returns `Some(id, m, p)`.  If `id` has no mod in its parent
1087         // chain, then returns `None`.
1088         fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
1089             loop {
1090                 match map.find(id)? {
1091                     NodeItem(item) if item_is_mod(&item) =>
1092                         return Some((id, item.name)),
1093                     _ => {}
1094                 }
1095                 let parent = map.get_parent(id);
1096                 if parent == id { return None }
1097                 id = parent;
1098             }
1099
1100             fn item_is_mod(item: &Item) -> bool {
1101                 match item.node {
1102                     ItemMod(_) => true,
1103                     _ => false,
1104                 }
1105             }
1106         }
1107     }
1108
1109     // We are looking at some node `n` with a given name and parent
1110     // id; do their names match what I am seeking?
1111     fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
1112         name == &**self.item_name && self.suffix_matches(parent_of_n)
1113     }
1114 }
1115
1116 impl<'a, 'hir> Iterator for NodesMatchingSuffix<'a, 'hir> {
1117     type Item = NodeId;
1118
1119     fn next(&mut self) -> Option<NodeId> {
1120         loop {
1121             let idx = self.idx;
1122             if idx.as_usize() >= self.map.entry_count() {
1123                 return None;
1124             }
1125             self.idx = NodeId::from_u32(self.idx.as_u32() + 1);
1126             let name = match self.map.find_entry(idx) {
1127                 Some(EntryItem(_, _, n))       => n.name(),
1128                 Some(EntryForeignItem(_, _, n))=> n.name(),
1129                 Some(EntryTraitItem(_, _, n))  => n.name(),
1130                 Some(EntryImplItem(_, _, n))   => n.name(),
1131                 Some(EntryVariant(_, _, n))    => n.name(),
1132                 Some(EntryField(_, _, n))      => n.name(),
1133                 _ => continue,
1134             };
1135             if self.matches_names(self.map.get_parent(idx), name) {
1136                 return Some(idx)
1137             }
1138         }
1139     }
1140 }
1141
1142 trait Named {
1143     fn name(&self) -> Name;
1144 }
1145
1146 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
1147
1148 impl Named for Item { fn name(&self) -> Name { self.name } }
1149 impl Named for ForeignItem { fn name(&self) -> Name { self.name } }
1150 impl Named for Variant_ { fn name(&self) -> Name { self.name } }
1151 impl Named for StructField { fn name(&self) -> Name { self.ident.name } }
1152 impl Named for TraitItem { fn name(&self) -> Name { self.ident.name } }
1153 impl Named for ImplItem { fn name(&self) -> Name { self.ident.name } }
1154
1155
1156 pub fn map_crate<'hir>(sess: &::session::Session,
1157                        cstore: &dyn CrateStore,
1158                        forest: &'hir mut Forest,
1159                        definitions: &'hir Definitions)
1160                        -> Map<'hir> {
1161     let (map, crate_hash) = {
1162         let hcx = ::ich::StableHashingContext::new(sess, &forest.krate, definitions, cstore);
1163
1164         let mut collector = NodeCollector::root(&forest.krate,
1165                                                 &forest.dep_graph,
1166                                                 &definitions,
1167                                                 hcx);
1168         intravisit::walk_crate(&mut collector, &forest.krate);
1169
1170         let crate_disambiguator = sess.local_crate_disambiguator();
1171         let cmdline_args = sess.opts.dep_tracking_hash();
1172         collector.finalize_and_compute_crate_hash(crate_disambiguator,
1173                                                   cstore,
1174                                                   sess.codemap(),
1175                                                   cmdline_args)
1176     };
1177
1178     if log_enabled!(::log::Level::Debug) {
1179         // This only makes sense for ordered stores; note the
1180         // enumerate to count the number of entries.
1181         let (entries_less_1, _) = map.iter().filter(|&x| {
1182             match *x {
1183                 NotPresent => false,
1184                 _ => true
1185             }
1186         }).enumerate().last().expect("AST map was empty after folding?");
1187
1188         let entries = entries_less_1 + 1;
1189         let vector_length = map.len();
1190         debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
1191               entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
1192     }
1193
1194     // Build the reverse mapping of `node_to_hir_id`.
1195     let hir_to_node_id = definitions.node_to_hir_id.iter_enumerated()
1196         .map(|(node_id, &hir_id)| (hir_id, node_id)).collect();
1197
1198     let map = Map {
1199         forest,
1200         dep_graph: forest.dep_graph.clone(),
1201         crate_hash,
1202         map,
1203         hir_to_node_id,
1204         definitions,
1205     };
1206
1207     hir_id_validator::check_crate(&map);
1208
1209     map
1210 }
1211
1212 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1213 /// except it avoids creating a dependency on the whole crate.
1214 impl<'hir> print::PpAnn for Map<'hir> {
1215     fn nested(&self, state: &mut print::State, nested: print::Nested) -> io::Result<()> {
1216         match nested {
1217             Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1218             Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1219             Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1220             Nested::Body(id) => state.print_expr(&self.body(id).value),
1221             Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
1222         }
1223     }
1224 }
1225
1226 impl<'a> print::State<'a> {
1227     pub fn print_node(&mut self, node: Node) -> io::Result<()> {
1228         match node {
1229             NodeItem(a)         => self.print_item(&a),
1230             NodeForeignItem(a)  => self.print_foreign_item(&a),
1231             NodeTraitItem(a)    => self.print_trait_item(a),
1232             NodeImplItem(a)     => self.print_impl_item(a),
1233             NodeVariant(a)      => self.print_variant(&a),
1234             NodeAnonConst(a)    => self.print_anon_const(&a),
1235             NodeExpr(a)         => self.print_expr(&a),
1236             NodeStmt(a)         => self.print_stmt(&a),
1237             NodeTy(a)           => self.print_type(&a),
1238             NodeTraitRef(a)     => self.print_trait_ref(&a),
1239             NodeBinding(a)       |
1240             NodePat(a)          => self.print_pat(&a),
1241             NodeBlock(a)        => {
1242                 use syntax::print::pprust::PrintState;
1243
1244                 // containing cbox, will be closed by print-block at }
1245                 self.cbox(print::indent_unit)?;
1246                 // head-ibox, will be closed by print-block after {
1247                 self.ibox(0)?;
1248                 self.print_block(&a)
1249             }
1250             NodeLifetime(a)     => self.print_lifetime(&a),
1251             NodeVisibility(a)   => self.print_visibility(&a),
1252             NodeGenericParam(_) => bug!("cannot print NodeGenericParam"),
1253             NodeField(_)        => bug!("cannot print StructField"),
1254             // these cases do not carry enough information in the
1255             // hir_map to reconstruct their full structure for pretty
1256             // printing.
1257             NodeStructCtor(_)   => bug!("cannot print isolated StructCtor"),
1258             NodeLocal(a)        => self.print_local_decl(&a),
1259             NodeMacroDef(_)     => bug!("cannot print MacroDef"),
1260         }
1261     }
1262 }
1263
1264 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
1265     let id_str = format!(" (id={})", id);
1266     let id_str = if include_id { &id_str[..] } else { "" };
1267
1268     let path_str = || {
1269         // This functionality is used for debugging, try to use TyCtxt to get
1270         // the user-friendly path, otherwise fall back to stringifying DefPath.
1271         ::ty::tls::with_opt(|tcx| {
1272             if let Some(tcx) = tcx {
1273                 tcx.node_path_str(id)
1274             } else if let Some(path) = map.def_path_from_id(id) {
1275                 path.data.into_iter().map(|elem| {
1276                     elem.data.to_string()
1277                 }).collect::<Vec<_>>().join("::")
1278             } else {
1279                 String::from("<missing path>")
1280             }
1281         })
1282     };
1283
1284     match map.find(id) {
1285         Some(NodeItem(item)) => {
1286             let item_str = match item.node {
1287                 ItemExternCrate(..) => "extern crate",
1288                 ItemUse(..) => "use",
1289                 ItemStatic(..) => "static",
1290                 ItemConst(..) => "const",
1291                 ItemFn(..) => "fn",
1292                 ItemMod(..) => "mod",
1293                 ItemForeignMod(..) => "foreign mod",
1294                 ItemGlobalAsm(..) => "global asm",
1295                 ItemTy(..) => "ty",
1296                 ItemExistential(..) => "existential",
1297                 ItemEnum(..) => "enum",
1298                 ItemStruct(..) => "struct",
1299                 ItemUnion(..) => "union",
1300                 ItemTrait(..) => "trait",
1301                 ItemTraitAlias(..) => "trait alias",
1302                 ItemImpl(..) => "impl",
1303             };
1304             format!("{} {}{}", item_str, path_str(), id_str)
1305         }
1306         Some(NodeForeignItem(_)) => {
1307             format!("foreign item {}{}", path_str(), id_str)
1308         }
1309         Some(NodeImplItem(ii)) => {
1310             match ii.node {
1311                 ImplItemKind::Const(..) => {
1312                     format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1313                 }
1314                 ImplItemKind::Method(..) => {
1315                     format!("method {} in {}{}", ii.ident, path_str(), id_str)
1316                 }
1317                 ImplItemKind::Type(_) => {
1318                     format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1319                 }
1320             }
1321         }
1322         Some(NodeTraitItem(ti)) => {
1323             let kind = match ti.node {
1324                 TraitItemKind::Const(..) => "assoc constant",
1325                 TraitItemKind::Method(..) => "trait method",
1326                 TraitItemKind::Type(..) => "assoc type",
1327             };
1328
1329             format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1330         }
1331         Some(NodeVariant(ref variant)) => {
1332             format!("variant {} in {}{}",
1333                     variant.node.name,
1334                     path_str(), id_str)
1335         }
1336         Some(NodeField(ref field)) => {
1337             format!("field {} in {}{}",
1338                     field.ident,
1339                     path_str(), id_str)
1340         }
1341         Some(NodeAnonConst(_)) => {
1342             format!("const {}{}", map.node_to_pretty_string(id), id_str)
1343         }
1344         Some(NodeExpr(_)) => {
1345             format!("expr {}{}", map.node_to_pretty_string(id), id_str)
1346         }
1347         Some(NodeStmt(_)) => {
1348             format!("stmt {}{}", map.node_to_pretty_string(id), id_str)
1349         }
1350         Some(NodeTy(_)) => {
1351             format!("type {}{}", map.node_to_pretty_string(id), id_str)
1352         }
1353         Some(NodeTraitRef(_)) => {
1354             format!("trait_ref {}{}", map.node_to_pretty_string(id), id_str)
1355         }
1356         Some(NodeBinding(_)) => {
1357             format!("local {}{}", map.node_to_pretty_string(id), id_str)
1358         }
1359         Some(NodePat(_)) => {
1360             format!("pat {}{}", map.node_to_pretty_string(id), id_str)
1361         }
1362         Some(NodeBlock(_)) => {
1363             format!("block {}{}", map.node_to_pretty_string(id), id_str)
1364         }
1365         Some(NodeLocal(_)) => {
1366             format!("local {}{}", map.node_to_pretty_string(id), id_str)
1367         }
1368         Some(NodeStructCtor(_)) => {
1369             format!("struct_ctor {}{}", path_str(), id_str)
1370         }
1371         Some(NodeLifetime(_)) => {
1372             format!("lifetime {}{}", map.node_to_pretty_string(id), id_str)
1373         }
1374         Some(NodeGenericParam(ref param)) => {
1375             format!("generic_param {:?}{}", param, id_str)
1376         }
1377         Some(NodeVisibility(ref vis)) => {
1378             format!("visibility {:?}{}", vis, id_str)
1379         }
1380         Some(NodeMacroDef(_)) => {
1381             format!("macro {}{}",  path_str(), id_str)
1382         }
1383         None => {
1384             format!("unknown node{}", id_str)
1385         }
1386     }
1387 }
1388
1389 pub fn describe_def(tcx: TyCtxt, def_id: DefId) -> Option<Def> {
1390     if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1391         tcx.hir.describe_def(node_id)
1392     } else {
1393         bug!("Calling local describe_def query provider for upstream DefId: {:?}",
1394              def_id)
1395     }
1396 }