]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/map/mod.rs
d003ec40a06bd6563fc7005221d0339f8acf0398
[rust.git] / src / librustc / hir / map / mod.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 pub use self::Node::*;
12 use self::MapEntry::*;
13 use self::collector::NodeCollector;
14 pub use self::def_collector::{DefCollector, MacroInvocationData};
15 pub use self::definitions::{Definitions, DefKey, DefPath, DefPathData,
16                             DisambiguatedDefPathData, DefPathHash};
17
18 use dep_graph::{DepGraph, DepNode, DepKind, DepNodeIndex};
19
20 use hir::def_id::{CRATE_DEF_INDEX, DefId, DefIndexAddressSpace};
21
22 use syntax::abi::Abi;
23 use syntax::ast::{self, Name, NodeId, CRATE_NODE_ID};
24 use syntax::codemap::Spanned;
25 use syntax_pos::Span;
26
27 use hir::*;
28 use hir::print::Nested;
29 use util::nodemap::{DefIdMap, FxHashMap};
30
31 use arena::TypedArena;
32 use std::cell::RefCell;
33 use std::io;
34
35 pub mod blocks;
36 mod collector;
37 mod def_collector;
38 pub mod definitions;
39 mod hir_id_validator;
40
41 pub const ITEM_LIKE_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::Low;
42 pub const REGULAR_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::High;
43
44 #[derive(Copy, Clone, Debug)]
45 pub enum Node<'hir> {
46     NodeItem(&'hir Item),
47     NodeForeignItem(&'hir ForeignItem),
48     NodeTraitItem(&'hir TraitItem),
49     NodeImplItem(&'hir ImplItem),
50     NodeVariant(&'hir Variant),
51     NodeField(&'hir StructField),
52     NodeExpr(&'hir Expr),
53     NodeStmt(&'hir Stmt),
54     NodeTy(&'hir Ty),
55     NodeTraitRef(&'hir TraitRef),
56     NodeBinding(&'hir Pat),
57     NodePat(&'hir Pat),
58     NodeBlock(&'hir Block),
59     NodeLocal(&'hir Local),
60     NodeMacroDef(&'hir MacroDef),
61
62     /// NodeStructCtor represents a tuple struct.
63     NodeStructCtor(&'hir VariantData),
64
65     NodeLifetime(&'hir Lifetime),
66     NodeTyParam(&'hir TyParam),
67     NodeVisibility(&'hir Visibility),
68 }
69
70 /// Represents an entry and its parent NodeID.
71 /// The odd layout is to bring down the total size.
72 #[derive(Copy, Debug)]
73 enum MapEntry<'hir> {
74     /// Placeholder for holes in the map.
75     NotPresent,
76
77     /// All the node types, with a parent ID.
78     EntryItem(NodeId, DepNodeIndex, &'hir Item),
79     EntryForeignItem(NodeId, DepNodeIndex, &'hir ForeignItem),
80     EntryTraitItem(NodeId, DepNodeIndex, &'hir TraitItem),
81     EntryImplItem(NodeId, DepNodeIndex, &'hir ImplItem),
82     EntryVariant(NodeId, DepNodeIndex, &'hir Variant),
83     EntryField(NodeId, DepNodeIndex, &'hir StructField),
84     EntryExpr(NodeId, DepNodeIndex, &'hir Expr),
85     EntryStmt(NodeId, DepNodeIndex, &'hir Stmt),
86     EntryTy(NodeId, DepNodeIndex, &'hir Ty),
87     EntryTraitRef(NodeId, DepNodeIndex, &'hir TraitRef),
88     EntryBinding(NodeId, DepNodeIndex, &'hir Pat),
89     EntryPat(NodeId, DepNodeIndex, &'hir Pat),
90     EntryBlock(NodeId, DepNodeIndex, &'hir Block),
91     EntryStructCtor(NodeId, DepNodeIndex, &'hir VariantData),
92     EntryLifetime(NodeId, DepNodeIndex, &'hir Lifetime),
93     EntryTyParam(NodeId, DepNodeIndex, &'hir TyParam),
94     EntryVisibility(NodeId, DepNodeIndex, &'hir Visibility),
95     EntryLocal(NodeId, DepNodeIndex, &'hir Local),
96
97     EntryMacroDef(DepNodeIndex, &'hir MacroDef),
98
99     /// Roots for node trees. The DepNodeIndex is the dependency node of the
100     /// crate's root module.
101     RootCrate(DepNodeIndex),
102 }
103
104 impl<'hir> Clone for MapEntry<'hir> {
105     fn clone(&self) -> MapEntry<'hir> {
106         *self
107     }
108 }
109
110 impl<'hir> MapEntry<'hir> {
111     fn parent_node(self) -> Option<NodeId> {
112         Some(match self {
113             EntryItem(id, _, _) => id,
114             EntryForeignItem(id, _, _) => id,
115             EntryTraitItem(id, _, _) => id,
116             EntryImplItem(id, _, _) => id,
117             EntryVariant(id, _, _) => id,
118             EntryField(id, _, _) => id,
119             EntryExpr(id, _, _) => id,
120             EntryStmt(id, _, _) => id,
121             EntryTy(id, _, _) => id,
122             EntryTraitRef(id, _, _) => id,
123             EntryBinding(id, _, _) => id,
124             EntryPat(id, _, _) => id,
125             EntryBlock(id, _, _) => id,
126             EntryStructCtor(id, _, _) => id,
127             EntryLifetime(id, _, _) => id,
128             EntryTyParam(id, _, _) => id,
129             EntryVisibility(id, _, _) => id,
130             EntryLocal(id, _, _) => id,
131
132             NotPresent |
133             EntryMacroDef(..) |
134             RootCrate(_) => return None,
135         })
136     }
137
138     fn to_node(self) -> Option<Node<'hir>> {
139         Some(match self {
140             EntryItem(_, _, n) => NodeItem(n),
141             EntryForeignItem(_, _, n) => NodeForeignItem(n),
142             EntryTraitItem(_, _, n) => NodeTraitItem(n),
143             EntryImplItem(_, _, n) => NodeImplItem(n),
144             EntryVariant(_, _, n) => NodeVariant(n),
145             EntryField(_, _, n) => NodeField(n),
146             EntryExpr(_, _, n) => NodeExpr(n),
147             EntryStmt(_, _, n) => NodeStmt(n),
148             EntryTy(_, _, n) => NodeTy(n),
149             EntryTraitRef(_, _, n) => NodeTraitRef(n),
150             EntryBinding(_, _, n) => NodeBinding(n),
151             EntryPat(_, _, n) => NodePat(n),
152             EntryBlock(_, _, n) => NodeBlock(n),
153             EntryStructCtor(_, _, n) => NodeStructCtor(n),
154             EntryLifetime(_, _, n) => NodeLifetime(n),
155             EntryTyParam(_, _, n) => NodeTyParam(n),
156             EntryVisibility(_, _, n) => NodeVisibility(n),
157             EntryLocal(_, _, n) => NodeLocal(n),
158             EntryMacroDef(_, n) => NodeMacroDef(n),
159
160             NotPresent |
161             RootCrate(_) => return None
162         })
163     }
164
165     fn associated_body(self) -> Option<BodyId> {
166         match self {
167             EntryItem(_, _, item) => {
168                 match item.node {
169                     ItemConst(_, body) |
170                     ItemStatic(.., body) |
171                     ItemFn(_, _, _, _, _, body) => Some(body),
172                     _ => None,
173                 }
174             }
175
176             EntryTraitItem(_, _, item) => {
177                 match item.node {
178                     TraitItemKind::Const(_, Some(body)) |
179                     TraitItemKind::Method(_, TraitMethod::Provided(body)) => Some(body),
180                     _ => None
181                 }
182             }
183
184             EntryImplItem(_, _, item) => {
185                 match item.node {
186                     ImplItemKind::Const(_, body) |
187                     ImplItemKind::Method(_, body) => Some(body),
188                     _ => None,
189                 }
190             }
191
192             EntryExpr(_, _, expr) => {
193                 match expr.node {
194                     ExprClosure(.., body, _, _) => Some(body),
195                     _ => None,
196                 }
197             }
198
199             _ => None
200         }
201     }
202
203     fn is_body_owner(self, node_id: NodeId) -> bool {
204         match self.associated_body() {
205             Some(b) => b.node_id == node_id,
206             None => false,
207         }
208     }
209 }
210
211 /// Stores a crate and any number of inlined items from other crates.
212 pub struct Forest {
213     krate: Crate,
214     pub dep_graph: DepGraph,
215     inlined_bodies: TypedArena<Body>
216 }
217
218 impl Forest {
219     pub fn new(krate: Crate, dep_graph: &DepGraph) -> Forest {
220         Forest {
221             krate,
222             dep_graph: dep_graph.clone(),
223             inlined_bodies: TypedArena::new()
224         }
225     }
226
227     pub fn krate<'hir>(&'hir self) -> &'hir Crate {
228         self.dep_graph.read(DepNode::new_no_params(DepKind::Krate));
229         &self.krate
230     }
231 }
232
233 /// Represents a mapping from Node IDs to AST elements and their parent
234 /// Node IDs
235 #[derive(Clone)]
236 pub struct Map<'hir> {
237     /// The backing storage for all the AST nodes.
238     pub forest: &'hir Forest,
239
240     /// Same as the dep_graph in forest, just available with one fewer
241     /// deref. This is a gratuitous micro-optimization.
242     pub dep_graph: DepGraph,
243
244     /// NodeIds are sequential integers from 0, so we can be
245     /// super-compact by storing them in a vector. Not everything with
246     /// a NodeId is in the map, but empirically the occupancy is about
247     /// 75-80%, so there's not too much overhead (certainly less than
248     /// a hashmap, since they (at the time of writing) have a maximum
249     /// of 75% occupancy).
250     ///
251     /// Also, indexing is pretty quick when you've got a vector and
252     /// plain old integers.
253     map: Vec<MapEntry<'hir>>,
254
255     definitions: &'hir Definitions,
256
257     /// Bodies inlined from other crates are cached here.
258     inlined_bodies: RefCell<DefIdMap<&'hir Body>>,
259
260     /// The reverse mapping of `node_to_hir_id`.
261     hir_to_node_id: FxHashMap<HirId, NodeId>,
262 }
263
264 impl<'hir> Map<'hir> {
265     /// Registers a read in the dependency graph of the AST node with
266     /// the given `id`. This needs to be called each time a public
267     /// function returns the HIR for a node -- in other words, when it
268     /// "reveals" the content of a node to the caller (who might not
269     /// otherwise have had access to those contents, and hence needs a
270     /// read recorded). If the function just returns a DefId or
271     /// NodeId, no actual content was returned, so no read is needed.
272     pub fn read(&self, id: NodeId) {
273         let entry = self.map[id.as_usize()];
274         match entry {
275             EntryItem(_, dep_node_index, _) |
276             EntryTraitItem(_, dep_node_index, _) |
277             EntryImplItem(_, dep_node_index, _) |
278             EntryVariant(_, dep_node_index, _) |
279             EntryForeignItem(_, dep_node_index, _) |
280             EntryField(_, dep_node_index, _) |
281             EntryStmt(_, dep_node_index, _) |
282             EntryTy(_, dep_node_index, _) |
283             EntryTraitRef(_, dep_node_index, _) |
284             EntryBinding(_, dep_node_index, _) |
285             EntryPat(_, dep_node_index, _) |
286             EntryBlock(_, dep_node_index, _) |
287             EntryStructCtor(_, dep_node_index, _) |
288             EntryLifetime(_, dep_node_index, _) |
289             EntryTyParam(_, dep_node_index, _) |
290             EntryVisibility(_, dep_node_index, _) |
291             EntryExpr(_, dep_node_index, _) |
292             EntryLocal(_, dep_node_index, _) |
293             EntryMacroDef(dep_node_index, _) |
294             RootCrate(dep_node_index) => {
295                 self.dep_graph.read_index(dep_node_index);
296             }
297             NotPresent => {
298                 bug!("called HirMap::read() with invalid NodeId")
299             }
300         }
301     }
302
303     #[inline]
304     pub fn definitions(&self) -> &'hir Definitions {
305         self.definitions
306     }
307
308     pub fn def_key(&self, def_id: DefId) -> DefKey {
309         assert!(def_id.is_local());
310         self.definitions.def_key(def_id.index)
311     }
312
313     pub fn def_path_from_id(&self, id: NodeId) -> Option<DefPath> {
314         self.opt_local_def_id(id).map(|def_id| {
315             self.def_path(def_id)
316         })
317     }
318
319     pub fn def_path(&self, def_id: DefId) -> DefPath {
320         assert!(def_id.is_local());
321         self.definitions.def_path(def_id.index)
322     }
323
324     #[inline]
325     pub fn local_def_id(&self, node: NodeId) -> DefId {
326         self.opt_local_def_id(node).unwrap_or_else(|| {
327             bug!("local_def_id: no entry for `{}`, which has a map of `{:?}`",
328                  node, self.find_entry(node))
329         })
330     }
331
332     #[inline]
333     pub fn opt_local_def_id(&self, node: NodeId) -> Option<DefId> {
334         self.definitions.opt_local_def_id(node)
335     }
336
337     #[inline]
338     pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
339         self.definitions.as_local_node_id(def_id)
340     }
341
342     #[inline]
343     pub fn hir_to_node_id(&self, hir_id: HirId) -> NodeId {
344         self.hir_to_node_id[&hir_id]
345     }
346
347     #[inline]
348     pub fn node_to_hir_id(&self, node_id: NodeId) -> HirId {
349         self.definitions.node_to_hir_id(node_id)
350     }
351
352     #[inline]
353     pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> HirId {
354         self.definitions.def_index_to_hir_id(def_index)
355     }
356
357     #[inline]
358     pub fn def_index_to_node_id(&self, def_index: DefIndex) -> NodeId {
359         self.definitions.as_local_node_id(DefId::local(def_index)).unwrap()
360     }
361
362     fn entry_count(&self) -> usize {
363         self.map.len()
364     }
365
366     fn find_entry(&self, id: NodeId) -> Option<MapEntry<'hir>> {
367         self.map.get(id.as_usize()).cloned()
368     }
369
370     pub fn krate(&self) -> &'hir Crate {
371         self.forest.krate()
372     }
373
374     pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem {
375         self.read(id.node_id);
376
377         // NB: intentionally bypass `self.forest.krate()` so that we
378         // do not trigger a read of the whole krate here
379         self.forest.krate.trait_item(id)
380     }
381
382     pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem {
383         self.read(id.node_id);
384
385         // NB: intentionally bypass `self.forest.krate()` so that we
386         // do not trigger a read of the whole krate here
387         self.forest.krate.impl_item(id)
388     }
389
390     pub fn body(&self, id: BodyId) -> &'hir Body {
391         self.read(id.node_id);
392
393         // NB: intentionally bypass `self.forest.krate()` so that we
394         // do not trigger a read of the whole krate here
395         self.forest.krate.body(id)
396     }
397
398     /// Returns the `NodeId` that corresponds to the definition of
399     /// which this is the body of, i.e. a `fn`, `const` or `static`
400     /// item (possibly associated), or a closure, or the body itself
401     /// for embedded constant expressions (e.g. `N` in `[T; N]`).
402     pub fn body_owner(&self, BodyId { node_id }: BodyId) -> NodeId {
403         let parent = self.get_parent_node(node_id);
404         if self.map[parent.as_usize()].is_body_owner(node_id) {
405             parent
406         } else {
407             node_id
408         }
409     }
410
411     pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
412         self.local_def_id(self.body_owner(id))
413     }
414
415     /// Given a node id, returns the `BodyId` associated with it,
416     /// if the node is a body owner, otherwise returns `None`.
417     pub fn maybe_body_owned_by(&self, id: NodeId) -> Option<BodyId> {
418         if let Some(entry) = self.find_entry(id) {
419             if let Some(body_id) = entry.associated_body() {
420                 // For item-like things and closures, the associated
421                 // body has its own distinct id, and that is returned
422                 // by `associated_body`.
423                 Some(body_id)
424             } else {
425                 // For some expressions, the expression is its own body.
426                 if let EntryExpr(_, _, expr) = entry {
427                     Some(BodyId { node_id: expr.id })
428                 } else {
429                     None
430                 }
431             }
432         } else {
433             bug!("no entry for id `{}`", id)
434         }
435     }
436
437     /// Given a body owner's id, returns the `BodyId` associated with it.
438     pub fn body_owned_by(&self, id: NodeId) -> BodyId {
439         self.maybe_body_owned_by(id).unwrap_or_else(|| {
440             span_bug!(self.span(id), "body_owned_by: {} has no associated body",
441                       self.node_to_string(id));
442         })
443     }
444
445     pub fn ty_param_owner(&self, id: NodeId) -> NodeId {
446         match self.get(id) {
447             NodeItem(&Item { node: ItemTrait(..), .. }) => id,
448             NodeTyParam(_) => self.get_parent_node(id),
449             _ => {
450                 bug!("ty_param_owner: {} not a type parameter",
451                     self.node_to_string(id))
452             }
453         }
454     }
455
456     pub fn ty_param_name(&self, id: NodeId) -> Name {
457         match self.get(id) {
458             NodeItem(&Item { node: ItemTrait(..), .. }) => {
459                 keywords::SelfType.name()
460             }
461             NodeTyParam(tp) => tp.name,
462             _ => {
463                 bug!("ty_param_name: {} not a type parameter",
464                     self.node_to_string(id))
465             }
466         }
467     }
468
469     pub fn trait_impls(&self, trait_did: DefId) -> &'hir [NodeId] {
470         self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
471
472         // NB: intentionally bypass `self.forest.krate()` so that we
473         // do not trigger a read of the whole krate here
474         self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
475     }
476
477     pub fn trait_default_impl(&self, trait_did: DefId) -> Option<NodeId> {
478         self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
479
480         // NB: intentionally bypass `self.forest.krate()` so that we
481         // do not trigger a read of the whole krate here
482         self.forest.krate.trait_default_impl.get(&trait_did).cloned()
483     }
484
485     pub fn trait_is_auto(&self, trait_did: DefId) -> bool {
486         self.trait_default_impl(trait_did).is_some()
487     }
488
489     /// Get the attributes on the krate. This is preferable to
490     /// invoking `krate.attrs` because it registers a tighter
491     /// dep-graph access.
492     pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
493         let def_path_hash = self.definitions.def_path_hash(CRATE_DEF_INDEX);
494
495         self.dep_graph.read(def_path_hash.to_dep_node(DepKind::Hir));
496         &self.forest.krate.attrs
497     }
498
499     /// Retrieve the Node corresponding to `id`, panicking if it cannot
500     /// be found.
501     pub fn get(&self, id: NodeId) -> Node<'hir> {
502         match self.find(id) {
503             Some(node) => node, // read recorded by `find`
504             None => bug!("couldn't find node id {} in the AST map", id)
505         }
506     }
507
508     pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
509         self.as_local_node_id(id).map(|id| self.get(id)) // read recorded by `get`
510     }
511
512     /// Retrieve the Node corresponding to `id`, returning None if
513     /// cannot be found.
514     pub fn find(&self, id: NodeId) -> Option<Node<'hir>> {
515         let result = self.find_entry(id).and_then(|x| x.to_node());
516         if result.is_some() {
517             self.read(id);
518         }
519         result
520     }
521
522     /// Similar to get_parent, returns the parent node id or id if there is no
523     /// parent. Note that the parent may be CRATE_NODE_ID, which is not itself
524     /// present in the map -- so passing the return value of get_parent_node to
525     /// get may actually panic.
526     /// This function returns the immediate parent in the AST, whereas get_parent
527     /// returns the enclosing item. Note that this might not be the actual parent
528     /// node in the AST - some kinds of nodes are not in the map and these will
529     /// never appear as the parent_node. So you can always walk the parent_nodes
530     /// from a node to the root of the ast (unless you get the same id back here
531     /// that can happen if the id is not in the map itself or is just weird).
532     pub fn get_parent_node(&self, id: NodeId) -> NodeId {
533         self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
534     }
535
536     /// Check if the node is an argument. An argument is a local variable whose
537     /// immediate parent is an item or a closure.
538     pub fn is_argument(&self, id: NodeId) -> bool {
539         match self.find(id) {
540             Some(NodeBinding(_)) => (),
541             _ => return false,
542         }
543         match self.find(self.get_parent_node(id)) {
544             Some(NodeItem(_)) |
545             Some(NodeTraitItem(_)) |
546             Some(NodeImplItem(_)) => true,
547             Some(NodeExpr(e)) => {
548                 match e.node {
549                     ExprClosure(..) => true,
550                     _ => false,
551                 }
552             }
553             _ => false,
554         }
555     }
556
557     /// If there is some error when walking the parents (e.g., a node does not
558     /// have a parent in the map or a node can't be found), then we return the
559     /// last good node id we found. Note that reaching the crate root (id == 0),
560     /// is not an error, since items in the crate module have the crate root as
561     /// parent.
562     fn walk_parent_nodes<F, F2>(&self,
563                                 start_id: NodeId,
564                                 found: F,
565                                 bail_early: F2)
566         -> Result<NodeId, NodeId>
567         where F: Fn(&Node<'hir>) -> bool, F2: Fn(&Node<'hir>) -> bool
568     {
569         let mut id = start_id;
570         loop {
571             let parent_node = self.get_parent_node(id);
572             if parent_node == CRATE_NODE_ID {
573                 return Ok(CRATE_NODE_ID);
574             }
575             if parent_node == id {
576                 return Err(id);
577             }
578
579             let node = self.find_entry(parent_node);
580             if node.is_none() {
581                 return Err(id);
582             }
583             let node = node.unwrap().to_node();
584             match node {
585                 Some(ref node) => {
586                     if found(node) {
587                         return Ok(parent_node);
588                     } else if bail_early(node) {
589                         return Err(parent_node);
590                     }
591                 }
592                 None => {
593                     return Err(parent_node);
594                 }
595             }
596             id = parent_node;
597         }
598     }
599
600     /// Retrieve the NodeId for `id`'s enclosing method, unless there's a
601     /// `while` or `loop` before reaching it, as block tail returns are not
602     /// available in them.
603     ///
604     /// ```
605     /// fn foo(x: usize) -> bool {
606     ///     if x == 1 {
607     ///         true  // `get_return_block` gets passed the `id` corresponding
608     ///     } else {  // to this, it will return `foo`'s `NodeId`.
609     ///         false
610     ///     }
611     /// }
612     /// ```
613     ///
614     /// ```
615     /// fn foo(x: usize) -> bool {
616     ///     loop {
617     ///         true  // `get_return_block` gets passed the `id` corresponding
618     ///     }         // to this, it will return `None`.
619     ///     false
620     /// }
621     /// ```
622     pub fn get_return_block(&self, id: NodeId) -> Option<NodeId> {
623         let match_fn = |node: &Node| {
624             match *node {
625                 NodeItem(_) |
626                 NodeForeignItem(_) |
627                 NodeTraitItem(_) |
628                 NodeImplItem(_) => true,
629                 _ => false,
630             }
631         };
632         let match_non_returning_block = |node: &Node| {
633             match *node {
634                 NodeExpr(ref expr) => {
635                     match expr.node {
636                         ExprWhile(..) | ExprLoop(..) => true,
637                         _ => false,
638                     }
639                 }
640                 _ => false,
641             }
642         };
643
644         match self.walk_parent_nodes(id, match_fn, match_non_returning_block) {
645             Ok(id) => Some(id),
646             Err(_) => None,
647         }
648     }
649
650     /// Retrieve the NodeId for `id`'s parent item, or `id` itself if no
651     /// parent item is in this map. The "parent item" is the closest parent node
652     /// in the AST which is recorded by the map and is an item, either an item
653     /// in a module, trait, or impl.
654     pub fn get_parent(&self, id: NodeId) -> NodeId {
655         match self.walk_parent_nodes(id, |node| match *node {
656             NodeItem(_) |
657             NodeForeignItem(_) |
658             NodeTraitItem(_) |
659             NodeImplItem(_) => true,
660             _ => false,
661         }, |_| false) {
662             Ok(id) => id,
663             Err(id) => id,
664         }
665     }
666
667     /// Returns the NodeId of `id`'s nearest module parent, or `id` itself if no
668     /// module parent is in this map.
669     pub fn get_module_parent(&self, id: NodeId) -> DefId {
670         let id = match self.walk_parent_nodes(id, |node| match *node {
671             NodeItem(&Item { node: Item_::ItemMod(_), .. }) => true,
672             _ => false,
673         }, |_| false) {
674             Ok(id) => id,
675             Err(id) => id,
676         };
677         self.local_def_id(id)
678     }
679
680     /// Returns the nearest enclosing scope. A scope is an item or block.
681     /// FIXME it is not clear to me that all items qualify as scopes - statics
682     /// and associated types probably shouldn't, for example. Behavior in this
683     /// regard should be expected to be highly unstable.
684     pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
685         match self.walk_parent_nodes(id, |node| match *node {
686             NodeItem(_) |
687             NodeForeignItem(_) |
688             NodeTraitItem(_) |
689             NodeImplItem(_) |
690             NodeBlock(_) => true,
691             _ => false,
692         }, |_| false) {
693             Ok(id) => Some(id),
694             Err(_) => None,
695         }
696     }
697
698     pub fn get_parent_did(&self, id: NodeId) -> DefId {
699         self.local_def_id(self.get_parent(id))
700     }
701
702     pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
703         let parent = self.get_parent(id);
704         let abi = match self.find_entry(parent) {
705             Some(EntryItem(_, _, i)) => {
706                 match i.node {
707                     ItemForeignMod(ref nm) => Some(nm.abi),
708                     _ => None
709                 }
710             }
711             _ => None
712         };
713         match abi {
714             Some(abi) => {
715                 self.read(id); // reveals some of the content of a node
716                 abi
717             }
718             None => bug!("expected foreign mod or inlined parent, found {}",
719                           self.node_to_string(parent))
720         }
721     }
722
723     pub fn expect_item(&self, id: NodeId) -> &'hir Item {
724         match self.find(id) { // read recorded by `find`
725             Some(NodeItem(item)) => item,
726             _ => bug!("expected item, found {}", self.node_to_string(id))
727         }
728     }
729
730     pub fn expect_impl_item(&self, id: NodeId) -> &'hir ImplItem {
731         match self.find(id) {
732             Some(NodeImplItem(item)) => item,
733             _ => bug!("expected impl item, found {}", self.node_to_string(id))
734         }
735     }
736
737     pub fn expect_trait_item(&self, id: NodeId) -> &'hir TraitItem {
738         match self.find(id) {
739             Some(NodeTraitItem(item)) => item,
740             _ => bug!("expected trait item, found {}", self.node_to_string(id))
741         }
742     }
743
744     pub fn expect_variant_data(&self, id: NodeId) -> &'hir VariantData {
745         match self.find(id) {
746             Some(NodeItem(i)) => {
747                 match i.node {
748                     ItemStruct(ref struct_def, _) |
749                     ItemUnion(ref struct_def, _) => struct_def,
750                     _ => {
751                         bug!("struct ID bound to non-struct {}",
752                              self.node_to_string(id));
753                     }
754                 }
755             }
756             Some(NodeStructCtor(data)) => data,
757             Some(NodeVariant(variant)) => &variant.node.data,
758             _ => {
759                 bug!("expected struct or variant, found {}",
760                      self.node_to_string(id));
761             }
762         }
763     }
764
765     pub fn expect_variant(&self, id: NodeId) -> &'hir Variant {
766         match self.find(id) {
767             Some(NodeVariant(variant)) => variant,
768             _ => bug!("expected variant, found {}", self.node_to_string(id)),
769         }
770     }
771
772     pub fn expect_foreign_item(&self, id: NodeId) -> &'hir ForeignItem {
773         match self.find(id) {
774             Some(NodeForeignItem(item)) => item,
775             _ => bug!("expected foreign item, found {}", self.node_to_string(id))
776         }
777     }
778
779     pub fn expect_expr(&self, id: NodeId) -> &'hir Expr {
780         match self.find(id) { // read recorded by find
781             Some(NodeExpr(expr)) => expr,
782             _ => bug!("expected expr, found {}", self.node_to_string(id))
783         }
784     }
785
786     pub fn get_inlined_body_untracked(&self, def_id: DefId) -> Option<&'hir Body> {
787         self.inlined_bodies.borrow().get(&def_id).cloned()
788     }
789
790     pub fn intern_inlined_body(&self, def_id: DefId, body: Body) -> &'hir Body {
791         let body = self.forest.inlined_bodies.alloc(body);
792         self.inlined_bodies.borrow_mut().insert(def_id, body);
793         body
794     }
795
796     /// Returns the name associated with the given NodeId's AST.
797     pub fn name(&self, id: NodeId) -> Name {
798         match self.get(id) {
799             NodeItem(i) => i.name,
800             NodeForeignItem(i) => i.name,
801             NodeImplItem(ii) => ii.name,
802             NodeTraitItem(ti) => ti.name,
803             NodeVariant(v) => v.node.name,
804             NodeField(f) => f.name,
805             NodeLifetime(lt) => lt.name.name(),
806             NodeTyParam(tp) => tp.name,
807             NodeBinding(&Pat { node: PatKind::Binding(_,_,l,_), .. }) => l.node,
808             NodeStructCtor(_) => self.name(self.get_parent(id)),
809             _ => bug!("no name for {}", self.node_to_string(id))
810         }
811     }
812
813     /// Given a node ID, get a list of attributes associated with the AST
814     /// corresponding to the Node ID
815     pub fn attrs(&self, id: NodeId) -> &'hir [ast::Attribute] {
816         self.read(id); // reveals attributes on the node
817         let attrs = match self.find(id) {
818             Some(NodeItem(i)) => Some(&i.attrs[..]),
819             Some(NodeForeignItem(fi)) => Some(&fi.attrs[..]),
820             Some(NodeTraitItem(ref ti)) => Some(&ti.attrs[..]),
821             Some(NodeImplItem(ref ii)) => Some(&ii.attrs[..]),
822             Some(NodeVariant(ref v)) => Some(&v.node.attrs[..]),
823             Some(NodeField(ref f)) => Some(&f.attrs[..]),
824             Some(NodeExpr(ref e)) => Some(&*e.attrs),
825             Some(NodeStmt(ref s)) => Some(s.node.attrs()),
826             // unit/tuple structs take the attributes straight from
827             // the struct definition.
828             Some(NodeStructCtor(_)) => {
829                 return self.attrs(self.get_parent(id));
830             }
831             _ => None
832         };
833         attrs.unwrap_or(&[])
834     }
835
836     /// Returns an iterator that yields the node id's with paths that
837     /// match `parts`.  (Requires `parts` is non-empty.)
838     ///
839     /// For example, if given `parts` equal to `["bar", "quux"]`, then
840     /// the iterator will produce node id's for items with paths
841     /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
842     /// any other such items it can find in the map.
843     pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
844                                  -> NodesMatchingSuffix<'a, 'hir> {
845         NodesMatchingSuffix {
846             map: self,
847             item_name: parts.last().unwrap(),
848             in_which: &parts[..parts.len() - 1],
849             idx: CRATE_NODE_ID,
850         }
851     }
852
853     pub fn span(&self, id: NodeId) -> Span {
854         self.read(id); // reveals span from node
855         match self.find_entry(id) {
856             Some(EntryItem(_, _, item)) => item.span,
857             Some(EntryForeignItem(_, _, foreign_item)) => foreign_item.span,
858             Some(EntryTraitItem(_, _, trait_method)) => trait_method.span,
859             Some(EntryImplItem(_, _, impl_item)) => impl_item.span,
860             Some(EntryVariant(_, _, variant)) => variant.span,
861             Some(EntryField(_, _, field)) => field.span,
862             Some(EntryExpr(_, _, expr)) => expr.span,
863             Some(EntryStmt(_, _, stmt)) => stmt.span,
864             Some(EntryTy(_, _, ty)) => ty.span,
865             Some(EntryTraitRef(_, _, tr)) => tr.path.span,
866             Some(EntryBinding(_, _, pat)) => pat.span,
867             Some(EntryPat(_, _, pat)) => pat.span,
868             Some(EntryBlock(_, _, block)) => block.span,
869             Some(EntryStructCtor(_, _, _)) => self.expect_item(self.get_parent(id)).span,
870             Some(EntryLifetime(_, _, lifetime)) => lifetime.span,
871             Some(EntryTyParam(_, _, ty_param)) => ty_param.span,
872             Some(EntryVisibility(_, _, &Visibility::Restricted { ref path, .. })) => path.span,
873             Some(EntryVisibility(_, _, v)) => bug!("unexpected Visibility {:?}", v),
874             Some(EntryLocal(_, _, local)) => local.span,
875             Some(EntryMacroDef(_, macro_def)) => macro_def.span,
876
877             Some(RootCrate(_)) => self.forest.krate.span,
878             Some(NotPresent) | None => {
879                 // Some nodes, notably macro definitions, are not
880                 // present in the map for whatever reason, but
881                 // they *do* have def-ids. So if we encounter an
882                 // empty hole, check for that case.
883                 if let Some(def_index) = self.definitions.opt_def_index(id) {
884                     let def_path_hash = self.definitions.def_path_hash(def_index);
885                     self.dep_graph.read(def_path_hash.to_dep_node(DepKind::Hir));
886                     DUMMY_SP
887                 } else {
888                     bug!("hir::map::Map::span: id not in map: {:?}", id)
889                 }
890             }
891         }
892     }
893
894     pub fn span_if_local(&self, id: DefId) -> Option<Span> {
895         self.as_local_node_id(id).map(|id| self.span(id))
896     }
897
898     pub fn node_to_string(&self, id: NodeId) -> String {
899         node_id_to_string(self, id, true)
900     }
901
902     pub fn node_to_user_string(&self, id: NodeId) -> String {
903         node_id_to_string(self, id, false)
904     }
905
906     pub fn node_to_pretty_string(&self, id: NodeId) -> String {
907         print::to_string(self, |s| s.print_node(self.get(id)))
908     }
909 }
910
911 pub struct NodesMatchingSuffix<'a, 'hir:'a> {
912     map: &'a Map<'hir>,
913     item_name: &'a String,
914     in_which: &'a [String],
915     idx: NodeId,
916 }
917
918 impl<'a, 'hir> NodesMatchingSuffix<'a, 'hir> {
919     /// Returns true only if some suffix of the module path for parent
920     /// matches `self.in_which`.
921     ///
922     /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
923     /// returns true if parent's path ends with the suffix
924     /// `x_0::x_1::...::x_k`.
925     fn suffix_matches(&self, parent: NodeId) -> bool {
926         let mut cursor = parent;
927         for part in self.in_which.iter().rev() {
928             let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
929                 None => return false,
930                 Some((node_id, name)) => (node_id, name),
931             };
932             if mod_name != &**part {
933                 return false;
934             }
935             cursor = self.map.get_parent(mod_id);
936         }
937         return true;
938
939         // Finds the first mod in parent chain for `id`, along with
940         // that mod's name.
941         //
942         // If `id` itself is a mod named `m` with parent `p`, then
943         // returns `Some(id, m, p)`.  If `id` has no mod in its parent
944         // chain, then returns `None`.
945         fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
946             loop {
947                 match map.find(id) {
948                     None => return None,
949                     Some(NodeItem(item)) if item_is_mod(&item) =>
950                         return Some((id, item.name)),
951                     _ => {}
952                 }
953                 let parent = map.get_parent(id);
954                 if parent == id { return None }
955                 id = parent;
956             }
957
958             fn item_is_mod(item: &Item) -> bool {
959                 match item.node {
960                     ItemMod(_) => true,
961                     _ => false,
962                 }
963             }
964         }
965     }
966
967     // We are looking at some node `n` with a given name and parent
968     // id; do their names match what I am seeking?
969     fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
970         name == &**self.item_name && self.suffix_matches(parent_of_n)
971     }
972 }
973
974 impl<'a, 'hir> Iterator for NodesMatchingSuffix<'a, 'hir> {
975     type Item = NodeId;
976
977     fn next(&mut self) -> Option<NodeId> {
978         loop {
979             let idx = self.idx;
980             if idx.as_usize() >= self.map.entry_count() {
981                 return None;
982             }
983             self.idx = NodeId::from_u32(self.idx.as_u32() + 1);
984             let name = match self.map.find_entry(idx) {
985                 Some(EntryItem(_, _, n))       => n.name(),
986                 Some(EntryForeignItem(_, _, n))=> n.name(),
987                 Some(EntryTraitItem(_, _, n))  => n.name(),
988                 Some(EntryImplItem(_, _, n))   => n.name(),
989                 Some(EntryVariant(_, _, n))    => n.name(),
990                 Some(EntryField(_, _, n))      => n.name(),
991                 _ => continue,
992             };
993             if self.matches_names(self.map.get_parent(idx), name) {
994                 return Some(idx)
995             }
996         }
997     }
998 }
999
1000 trait Named {
1001     fn name(&self) -> Name;
1002 }
1003
1004 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
1005
1006 impl Named for Item { fn name(&self) -> Name { self.name } }
1007 impl Named for ForeignItem { fn name(&self) -> Name { self.name } }
1008 impl Named for Variant_ { fn name(&self) -> Name { self.name } }
1009 impl Named for StructField { fn name(&self) -> Name { self.name } }
1010 impl Named for TraitItem { fn name(&self) -> Name { self.name } }
1011 impl Named for ImplItem { fn name(&self) -> Name { self.name } }
1012
1013 pub fn map_crate<'hir>(sess: &::session::Session,
1014                        cstore: &::middle::cstore::CrateStore,
1015                        forest: &'hir mut Forest,
1016                        definitions: &'hir Definitions)
1017                        -> Map<'hir> {
1018     let map = {
1019         let hcx = ::ich::StableHashingContext::new(sess, &forest.krate, definitions, cstore);
1020
1021         let mut collector = NodeCollector::root(&forest.krate,
1022                                                 &forest.dep_graph,
1023                                                 &definitions,
1024                                                 hcx);
1025         intravisit::walk_crate(&mut collector, &forest.krate);
1026
1027         let crate_disambiguator = sess.local_crate_disambiguator().as_str();
1028         collector.finalize_and_compute_crate_hash(&crate_disambiguator)
1029     };
1030
1031     if log_enabled!(::log::LogLevel::Debug) {
1032         // This only makes sense for ordered stores; note the
1033         // enumerate to count the number of entries.
1034         let (entries_less_1, _) = map.iter().filter(|&x| {
1035             match *x {
1036                 NotPresent => false,
1037                 _ => true
1038             }
1039         }).enumerate().last().expect("AST map was empty after folding?");
1040
1041         let entries = entries_less_1 + 1;
1042         let vector_length = map.len();
1043         debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
1044               entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
1045     }
1046
1047     // Build the reverse mapping of `node_to_hir_id`.
1048     let hir_to_node_id = definitions.node_to_hir_id.iter_enumerated()
1049         .map(|(node_id, &hir_id)| (hir_id, node_id)).collect();
1050
1051     let map = Map {
1052         forest,
1053         dep_graph: forest.dep_graph.clone(),
1054         map,
1055         hir_to_node_id,
1056         definitions,
1057         inlined_bodies: RefCell::new(DefIdMap()),
1058     };
1059
1060     hir_id_validator::check_crate(&map);
1061
1062     map
1063 }
1064
1065 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1066 /// except it avoids creating a dependency on the whole crate.
1067 impl<'hir> print::PpAnn for Map<'hir> {
1068     fn nested(&self, state: &mut print::State, nested: print::Nested) -> io::Result<()> {
1069         match nested {
1070             Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1071             Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1072             Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1073             Nested::Body(id) => state.print_expr(&self.body(id).value),
1074             Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
1075         }
1076     }
1077 }
1078
1079 impl<'a> print::State<'a> {
1080     pub fn print_node(&mut self, node: Node) -> io::Result<()> {
1081         match node {
1082             NodeItem(a)        => self.print_item(&a),
1083             NodeForeignItem(a) => self.print_foreign_item(&a),
1084             NodeTraitItem(a)   => self.print_trait_item(a),
1085             NodeImplItem(a)    => self.print_impl_item(a),
1086             NodeVariant(a)     => self.print_variant(&a),
1087             NodeExpr(a)        => self.print_expr(&a),
1088             NodeStmt(a)        => self.print_stmt(&a),
1089             NodeTy(a)          => self.print_type(&a),
1090             NodeTraitRef(a)    => self.print_trait_ref(&a),
1091             NodeBinding(a)       |
1092             NodePat(a)         => self.print_pat(&a),
1093             NodeBlock(a)       => {
1094                 use syntax::print::pprust::PrintState;
1095
1096                 // containing cbox, will be closed by print-block at }
1097                 self.cbox(print::indent_unit)?;
1098                 // head-ibox, will be closed by print-block after {
1099                 self.ibox(0)?;
1100                 self.print_block(&a)
1101             }
1102             NodeLifetime(a)    => self.print_lifetime(&a),
1103             NodeVisibility(a)  => self.print_visibility(&a),
1104             NodeTyParam(_)     => bug!("cannot print TyParam"),
1105             NodeField(_)       => bug!("cannot print StructField"),
1106             // these cases do not carry enough information in the
1107             // hir_map to reconstruct their full structure for pretty
1108             // printing.
1109             NodeStructCtor(_)  => bug!("cannot print isolated StructCtor"),
1110             NodeLocal(a)       => self.print_local_decl(&a),
1111             NodeMacroDef(_)    => bug!("cannot print MacroDef"),
1112         }
1113     }
1114 }
1115
1116 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
1117     let id_str = format!(" (id={})", id);
1118     let id_str = if include_id { &id_str[..] } else { "" };
1119
1120     let path_str = || {
1121         // This functionality is used for debugging, try to use TyCtxt to get
1122         // the user-friendly path, otherwise fall back to stringifying DefPath.
1123         ::ty::tls::with_opt(|tcx| {
1124             if let Some(tcx) = tcx {
1125                 tcx.node_path_str(id)
1126             } else if let Some(path) = map.def_path_from_id(id) {
1127                 path.data.into_iter().map(|elem| {
1128                     elem.data.to_string()
1129                 }).collect::<Vec<_>>().join("::")
1130             } else {
1131                 String::from("<missing path>")
1132             }
1133         })
1134     };
1135
1136     match map.find(id) {
1137         Some(NodeItem(item)) => {
1138             let item_str = match item.node {
1139                 ItemExternCrate(..) => "extern crate",
1140                 ItemUse(..) => "use",
1141                 ItemStatic(..) => "static",
1142                 ItemConst(..) => "const",
1143                 ItemFn(..) => "fn",
1144                 ItemMod(..) => "mod",
1145                 ItemForeignMod(..) => "foreign mod",
1146                 ItemGlobalAsm(..) => "global asm",
1147                 ItemTy(..) => "ty",
1148                 ItemEnum(..) => "enum",
1149                 ItemStruct(..) => "struct",
1150                 ItemUnion(..) => "union",
1151                 ItemTrait(..) => "trait",
1152                 ItemImpl(..) => "impl",
1153                 ItemDefaultImpl(..) => "default impl",
1154             };
1155             format!("{} {}{}", item_str, path_str(), id_str)
1156         }
1157         Some(NodeForeignItem(_)) => {
1158             format!("foreign item {}{}", path_str(), id_str)
1159         }
1160         Some(NodeImplItem(ii)) => {
1161             match ii.node {
1162                 ImplItemKind::Const(..) => {
1163                     format!("assoc const {} in {}{}", ii.name, path_str(), id_str)
1164                 }
1165                 ImplItemKind::Method(..) => {
1166                     format!("method {} in {}{}", ii.name, path_str(), id_str)
1167                 }
1168                 ImplItemKind::Type(_) => {
1169                     format!("assoc type {} in {}{}", ii.name, path_str(), id_str)
1170                 }
1171             }
1172         }
1173         Some(NodeTraitItem(ti)) => {
1174             let kind = match ti.node {
1175                 TraitItemKind::Const(..) => "assoc constant",
1176                 TraitItemKind::Method(..) => "trait method",
1177                 TraitItemKind::Type(..) => "assoc type",
1178             };
1179
1180             format!("{} {} in {}{}", kind, ti.name, path_str(), id_str)
1181         }
1182         Some(NodeVariant(ref variant)) => {
1183             format!("variant {} in {}{}",
1184                     variant.node.name,
1185                     path_str(), id_str)
1186         }
1187         Some(NodeField(ref field)) => {
1188             format!("field {} in {}{}",
1189                     field.name,
1190                     path_str(), id_str)
1191         }
1192         Some(NodeExpr(_)) => {
1193             format!("expr {}{}", map.node_to_pretty_string(id), id_str)
1194         }
1195         Some(NodeStmt(_)) => {
1196             format!("stmt {}{}", map.node_to_pretty_string(id), id_str)
1197         }
1198         Some(NodeTy(_)) => {
1199             format!("type {}{}", map.node_to_pretty_string(id), id_str)
1200         }
1201         Some(NodeTraitRef(_)) => {
1202             format!("trait_ref {}{}", map.node_to_pretty_string(id), id_str)
1203         }
1204         Some(NodeBinding(_)) => {
1205             format!("local {}{}", map.node_to_pretty_string(id), id_str)
1206         }
1207         Some(NodePat(_)) => {
1208             format!("pat {}{}", map.node_to_pretty_string(id), id_str)
1209         }
1210         Some(NodeBlock(_)) => {
1211             format!("block {}{}", map.node_to_pretty_string(id), id_str)
1212         }
1213         Some(NodeLocal(_)) => {
1214             format!("local {}{}", map.node_to_pretty_string(id), id_str)
1215         }
1216         Some(NodeStructCtor(_)) => {
1217             format!("struct_ctor {}{}", path_str(), id_str)
1218         }
1219         Some(NodeLifetime(_)) => {
1220             format!("lifetime {}{}", map.node_to_pretty_string(id), id_str)
1221         }
1222         Some(NodeTyParam(ref ty_param)) => {
1223             format!("typaram {:?}{}", ty_param, id_str)
1224         }
1225         Some(NodeVisibility(ref vis)) => {
1226             format!("visibility {:?}{}", vis, id_str)
1227         }
1228         Some(NodeMacroDef(_)) => {
1229             format!("macro {}{}",  path_str(), id_str)
1230         }
1231         None => {
1232             format!("unknown node{}", id_str)
1233         }
1234     }
1235 }