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