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