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