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