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