]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/map/mod.rs
Auto merge of #42394 - ollie27:rustdoc_deref_box, r=QuietMisdreavus
[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};
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) -> DefId {
641         let id = 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         self.local_def_id(id)
649     }
650
651     /// Returns the nearest enclosing scope. A scope is an item or block.
652     /// FIXME it is not clear to me that all items qualify as scopes - statics
653     /// and associated types probably shouldn't, for example. Behaviour in this
654     /// regard should be expected to be highly unstable.
655     pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
656         match self.walk_parent_nodes(id, |node| match *node {
657             NodeItem(_) |
658             NodeForeignItem(_) |
659             NodeTraitItem(_) |
660             NodeImplItem(_) |
661             NodeBlock(_) => true,
662             _ => false,
663         }) {
664             Ok(id) => Some(id),
665             Err(_) => None,
666         }
667     }
668
669     pub fn get_parent_did(&self, id: NodeId) -> DefId {
670         self.local_def_id(self.get_parent(id))
671     }
672
673     pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
674         let parent = self.get_parent(id);
675         let abi = match self.find_entry(parent) {
676             Some(EntryItem(_, i)) => {
677                 match i.node {
678                     ItemForeignMod(ref nm) => Some(nm.abi),
679                     _ => None
680                 }
681             }
682             _ => None
683         };
684         match abi {
685             Some(abi) => {
686                 self.read(id); // reveals some of the content of a node
687                 abi
688             }
689             None => bug!("expected foreign mod or inlined parent, found {}",
690                           self.node_to_string(parent))
691         }
692     }
693
694     pub fn expect_item(&self, id: NodeId) -> &'hir Item {
695         match self.find(id) { // read recorded by `find`
696             Some(NodeItem(item)) => item,
697             _ => bug!("expected item, found {}", self.node_to_string(id))
698         }
699     }
700
701     pub fn expect_impl_item(&self, id: NodeId) -> &'hir ImplItem {
702         match self.find(id) {
703             Some(NodeImplItem(item)) => item,
704             _ => bug!("expected impl item, found {}", self.node_to_string(id))
705         }
706     }
707
708     pub fn expect_trait_item(&self, id: NodeId) -> &'hir TraitItem {
709         match self.find(id) {
710             Some(NodeTraitItem(item)) => item,
711             _ => bug!("expected trait item, found {}", self.node_to_string(id))
712         }
713     }
714
715     pub fn expect_variant_data(&self, id: NodeId) -> &'hir VariantData {
716         match self.find(id) {
717             Some(NodeItem(i)) => {
718                 match i.node {
719                     ItemStruct(ref struct_def, _) |
720                     ItemUnion(ref struct_def, _) => struct_def,
721                     _ => {
722                         bug!("struct ID bound to non-struct {}",
723                              self.node_to_string(id));
724                     }
725                 }
726             }
727             Some(NodeStructCtor(data)) => data,
728             Some(NodeVariant(variant)) => &variant.node.data,
729             _ => {
730                 bug!("expected struct or variant, found {}",
731                      self.node_to_string(id));
732             }
733         }
734     }
735
736     pub fn expect_variant(&self, id: NodeId) -> &'hir Variant {
737         match self.find(id) {
738             Some(NodeVariant(variant)) => variant,
739             _ => bug!("expected variant, found {}", self.node_to_string(id)),
740         }
741     }
742
743     pub fn expect_foreign_item(&self, id: NodeId) -> &'hir ForeignItem {
744         match self.find(id) {
745             Some(NodeForeignItem(item)) => item,
746             _ => bug!("expected foreign item, found {}", self.node_to_string(id))
747         }
748     }
749
750     pub fn expect_expr(&self, id: NodeId) -> &'hir Expr {
751         match self.find(id) { // read recorded by find
752             Some(NodeExpr(expr)) => expr,
753             _ => bug!("expected expr, found {}", self.node_to_string(id))
754         }
755     }
756
757     pub fn get_inlined_body(&self, def_id: DefId) -> Option<&'hir Body> {
758         self.inlined_bodies.borrow().get(&def_id).map(|&body| {
759             self.dep_graph.read(DepNode::MetaData(def_id));
760             body
761         })
762     }
763
764     pub fn intern_inlined_body(&self, def_id: DefId, body: Body) -> &'hir Body {
765         let body = self.forest.inlined_bodies.alloc(body);
766         self.inlined_bodies.borrow_mut().insert(def_id, body);
767         body
768     }
769
770     /// Returns the name associated with the given NodeId's AST.
771     pub fn name(&self, id: NodeId) -> Name {
772         match self.get(id) {
773             NodeItem(i) => i.name,
774             NodeForeignItem(i) => i.name,
775             NodeImplItem(ii) => ii.name,
776             NodeTraitItem(ti) => ti.name,
777             NodeVariant(v) => v.node.name,
778             NodeField(f) => f.name,
779             NodeLifetime(lt) => lt.name,
780             NodeTyParam(tp) => tp.name,
781             NodeLocal(&Pat { node: PatKind::Binding(_,_,l,_), .. }) => l.node,
782             NodeStructCtor(_) => self.name(self.get_parent(id)),
783             _ => bug!("no name for {}", self.node_to_string(id))
784         }
785     }
786
787     /// Given a node ID, get a list of attributes associated with the AST
788     /// corresponding to the Node ID
789     pub fn attrs(&self, id: NodeId) -> &'hir [ast::Attribute] {
790         self.read(id); // reveals attributes on the node
791         let attrs = match self.find(id) {
792             Some(NodeItem(i)) => Some(&i.attrs[..]),
793             Some(NodeForeignItem(fi)) => Some(&fi.attrs[..]),
794             Some(NodeTraitItem(ref ti)) => Some(&ti.attrs[..]),
795             Some(NodeImplItem(ref ii)) => Some(&ii.attrs[..]),
796             Some(NodeVariant(ref v)) => Some(&v.node.attrs[..]),
797             Some(NodeField(ref f)) => Some(&f.attrs[..]),
798             Some(NodeExpr(ref e)) => Some(&*e.attrs),
799             Some(NodeStmt(ref s)) => Some(s.node.attrs()),
800             // unit/tuple structs take the attributes straight from
801             // the struct definition.
802             Some(NodeStructCtor(_)) => {
803                 return self.attrs(self.get_parent(id));
804             }
805             _ => None
806         };
807         attrs.unwrap_or(&[])
808     }
809
810     /// Returns an iterator that yields the node id's with paths that
811     /// match `parts`.  (Requires `parts` is non-empty.)
812     ///
813     /// For example, if given `parts` equal to `["bar", "quux"]`, then
814     /// the iterator will produce node id's for items with paths
815     /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
816     /// any other such items it can find in the map.
817     pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
818                                  -> NodesMatchingSuffix<'a, 'hir> {
819         NodesMatchingSuffix {
820             map: self,
821             item_name: parts.last().unwrap(),
822             in_which: &parts[..parts.len() - 1],
823             idx: CRATE_NODE_ID,
824         }
825     }
826
827     pub fn span(&self, id: NodeId) -> Span {
828         self.read(id); // reveals span from node
829         match self.find_entry(id) {
830             Some(EntryItem(_, item)) => item.span,
831             Some(EntryForeignItem(_, foreign_item)) => foreign_item.span,
832             Some(EntryTraitItem(_, trait_method)) => trait_method.span,
833             Some(EntryImplItem(_, impl_item)) => impl_item.span,
834             Some(EntryVariant(_, variant)) => variant.span,
835             Some(EntryField(_, field)) => field.span,
836             Some(EntryExpr(_, expr)) => expr.span,
837             Some(EntryStmt(_, stmt)) => stmt.span,
838             Some(EntryTy(_, ty)) => ty.span,
839             Some(EntryTraitRef(_, tr)) => tr.path.span,
840             Some(EntryLocal(_, pat)) => pat.span,
841             Some(EntryPat(_, pat)) => pat.span,
842             Some(EntryBlock(_, block)) => block.span,
843             Some(EntryStructCtor(_, _)) => self.expect_item(self.get_parent(id)).span,
844             Some(EntryLifetime(_, lifetime)) => lifetime.span,
845             Some(EntryTyParam(_, ty_param)) => ty_param.span,
846             Some(EntryVisibility(_, &Visibility::Restricted { ref path, .. })) => path.span,
847             Some(EntryVisibility(_, v)) => bug!("unexpected Visibility {:?}", v),
848
849             Some(RootCrate) => self.forest.krate.span,
850             Some(NotPresent) | None => {
851                 bug!("hir::map::Map::span: id not in map: {:?}", id)
852             }
853         }
854     }
855
856     pub fn span_if_local(&self, id: DefId) -> Option<Span> {
857         self.as_local_node_id(id).map(|id| self.span(id))
858     }
859
860     pub fn node_to_string(&self, id: NodeId) -> String {
861         node_id_to_string(self, id, true)
862     }
863
864     pub fn node_to_user_string(&self, id: NodeId) -> String {
865         node_id_to_string(self, id, false)
866     }
867
868     pub fn node_to_pretty_string(&self, id: NodeId) -> String {
869         print::to_string(self, |s| s.print_node(self.get(id)))
870     }
871 }
872
873 pub struct NodesMatchingSuffix<'a, 'hir:'a> {
874     map: &'a Map<'hir>,
875     item_name: &'a String,
876     in_which: &'a [String],
877     idx: NodeId,
878 }
879
880 impl<'a, 'hir> NodesMatchingSuffix<'a, 'hir> {
881     /// Returns true only if some suffix of the module path for parent
882     /// matches `self.in_which`.
883     ///
884     /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
885     /// returns true if parent's path ends with the suffix
886     /// `x_0::x_1::...::x_k`.
887     fn suffix_matches(&self, parent: NodeId) -> bool {
888         let mut cursor = parent;
889         for part in self.in_which.iter().rev() {
890             let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
891                 None => return false,
892                 Some((node_id, name)) => (node_id, name),
893             };
894             if mod_name != &**part {
895                 return false;
896             }
897             cursor = self.map.get_parent(mod_id);
898         }
899         return true;
900
901         // Finds the first mod in parent chain for `id`, along with
902         // that mod's name.
903         //
904         // If `id` itself is a mod named `m` with parent `p`, then
905         // returns `Some(id, m, p)`.  If `id` has no mod in its parent
906         // chain, then returns `None`.
907         fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
908             loop {
909                 match map.find(id) {
910                     None => return None,
911                     Some(NodeItem(item)) if item_is_mod(&item) =>
912                         return Some((id, item.name)),
913                     _ => {}
914                 }
915                 let parent = map.get_parent(id);
916                 if parent == id { return None }
917                 id = parent;
918             }
919
920             fn item_is_mod(item: &Item) -> bool {
921                 match item.node {
922                     ItemMod(_) => true,
923                     _ => false,
924                 }
925             }
926         }
927     }
928
929     // We are looking at some node `n` with a given name and parent
930     // id; do their names match what I am seeking?
931     fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
932         name == &**self.item_name && self.suffix_matches(parent_of_n)
933     }
934 }
935
936 impl<'a, 'hir> Iterator for NodesMatchingSuffix<'a, 'hir> {
937     type Item = NodeId;
938
939     fn next(&mut self) -> Option<NodeId> {
940         loop {
941             let idx = self.idx;
942             if idx.as_usize() >= self.map.entry_count() {
943                 return None;
944             }
945             self.idx = NodeId::from_u32(self.idx.as_u32() + 1);
946             let name = match self.map.find_entry(idx) {
947                 Some(EntryItem(_, n))       => n.name(),
948                 Some(EntryForeignItem(_, n))=> n.name(),
949                 Some(EntryTraitItem(_, n))  => n.name(),
950                 Some(EntryImplItem(_, n))   => n.name(),
951                 Some(EntryVariant(_, n))    => n.name(),
952                 Some(EntryField(_, n))      => n.name(),
953                 _ => continue,
954             };
955             if self.matches_names(self.map.get_parent(idx), name) {
956                 return Some(idx)
957             }
958         }
959     }
960 }
961
962 trait Named {
963     fn name(&self) -> Name;
964 }
965
966 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
967
968 impl Named for Item { fn name(&self) -> Name { self.name } }
969 impl Named for ForeignItem { fn name(&self) -> Name { self.name } }
970 impl Named for Variant_ { fn name(&self) -> Name { self.name } }
971 impl Named for StructField { fn name(&self) -> Name { self.name } }
972 impl Named for TraitItem { fn name(&self) -> Name { self.name } }
973 impl Named for ImplItem { fn name(&self) -> Name { self.name } }
974
975 pub fn map_crate<'hir>(forest: &'hir mut Forest,
976                        definitions: Definitions)
977                        -> Map<'hir> {
978     let mut collector = NodeCollector::root(&forest.krate);
979     intravisit::walk_crate(&mut collector, &forest.krate);
980     let map = collector.map;
981
982     if log_enabled!(::log::LogLevel::Debug) {
983         // This only makes sense for ordered stores; note the
984         // enumerate to count the number of entries.
985         let (entries_less_1, _) = map.iter().filter(|&x| {
986             match *x {
987                 NotPresent => false,
988                 _ => true
989             }
990         }).enumerate().last().expect("AST map was empty after folding?");
991
992         let entries = entries_less_1 + 1;
993         let vector_length = map.len();
994         debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
995               entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
996     }
997
998     let map = Map {
999         forest: forest,
1000         dep_graph: forest.dep_graph.clone(),
1001         map: map,
1002         definitions: definitions,
1003         inlined_bodies: RefCell::new(DefIdMap()),
1004     };
1005
1006     hir_id_validator::check_crate(&map);
1007
1008     map
1009 }
1010
1011 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1012 /// except it avoids creating a dependency on the whole crate.
1013 impl<'hir> print::PpAnn for Map<'hir> {
1014     fn nested(&self, state: &mut print::State, nested: print::Nested) -> io::Result<()> {
1015         match nested {
1016             Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1017             Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1018             Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1019             Nested::Body(id) => state.print_expr(&self.body(id).value),
1020             Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
1021         }
1022     }
1023 }
1024
1025 impl<'a> print::State<'a> {
1026     pub fn print_node(&mut self, node: Node) -> io::Result<()> {
1027         match node {
1028             NodeItem(a)        => self.print_item(&a),
1029             NodeForeignItem(a) => self.print_foreign_item(&a),
1030             NodeTraitItem(a)   => self.print_trait_item(a),
1031             NodeImplItem(a)    => self.print_impl_item(a),
1032             NodeVariant(a)     => self.print_variant(&a),
1033             NodeExpr(a)        => self.print_expr(&a),
1034             NodeStmt(a)        => self.print_stmt(&a),
1035             NodeTy(a)          => self.print_type(&a),
1036             NodeTraitRef(a)    => self.print_trait_ref(&a),
1037             NodeLocal(a)       |
1038             NodePat(a)         => self.print_pat(&a),
1039             NodeBlock(a)       => {
1040                 use syntax::print::pprust::PrintState;
1041
1042                 // containing cbox, will be closed by print-block at }
1043                 self.cbox(print::indent_unit)?;
1044                 // head-ibox, will be closed by print-block after {
1045                 self.ibox(0)?;
1046                 self.print_block(&a)
1047             }
1048             NodeLifetime(a)    => self.print_lifetime(&a),
1049             NodeVisibility(a)  => self.print_visibility(&a),
1050             NodeTyParam(_)     => bug!("cannot print TyParam"),
1051             NodeField(_)       => bug!("cannot print StructField"),
1052             // these cases do not carry enough information in the
1053             // hir_map to reconstruct their full structure for pretty
1054             // printing.
1055             NodeStructCtor(_)  => bug!("cannot print isolated StructCtor"),
1056         }
1057     }
1058 }
1059
1060 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
1061     let id_str = format!(" (id={})", id);
1062     let id_str = if include_id { &id_str[..] } else { "" };
1063
1064     let path_str = || {
1065         // This functionality is used for debugging, try to use TyCtxt to get
1066         // the user-friendly path, otherwise fall back to stringifying DefPath.
1067         ::ty::tls::with_opt(|tcx| {
1068             if let Some(tcx) = tcx {
1069                 tcx.node_path_str(id)
1070             } else if let Some(path) = map.def_path_from_id(id) {
1071                 path.data.into_iter().map(|elem| {
1072                     elem.data.to_string()
1073                 }).collect::<Vec<_>>().join("::")
1074             } else {
1075                 String::from("<missing path>")
1076             }
1077         })
1078     };
1079
1080     match map.find(id) {
1081         Some(NodeItem(item)) => {
1082             let item_str = match item.node {
1083                 ItemExternCrate(..) => "extern crate",
1084                 ItemUse(..) => "use",
1085                 ItemStatic(..) => "static",
1086                 ItemConst(..) => "const",
1087                 ItemFn(..) => "fn",
1088                 ItemMod(..) => "mod",
1089                 ItemForeignMod(..) => "foreign mod",
1090                 ItemGlobalAsm(..) => "global asm",
1091                 ItemTy(..) => "ty",
1092                 ItemEnum(..) => "enum",
1093                 ItemStruct(..) => "struct",
1094                 ItemUnion(..) => "union",
1095                 ItemTrait(..) => "trait",
1096                 ItemImpl(..) => "impl",
1097                 ItemDefaultImpl(..) => "default impl",
1098             };
1099             format!("{} {}{}", item_str, path_str(), id_str)
1100         }
1101         Some(NodeForeignItem(_)) => {
1102             format!("foreign item {}{}", path_str(), id_str)
1103         }
1104         Some(NodeImplItem(ii)) => {
1105             match ii.node {
1106                 ImplItemKind::Const(..) => {
1107                     format!("assoc const {} in {}{}", ii.name, path_str(), id_str)
1108                 }
1109                 ImplItemKind::Method(..) => {
1110                     format!("method {} in {}{}", ii.name, path_str(), id_str)
1111                 }
1112                 ImplItemKind::Type(_) => {
1113                     format!("assoc type {} in {}{}", ii.name, path_str(), id_str)
1114                 }
1115             }
1116         }
1117         Some(NodeTraitItem(ti)) => {
1118             let kind = match ti.node {
1119                 TraitItemKind::Const(..) => "assoc constant",
1120                 TraitItemKind::Method(..) => "trait method",
1121                 TraitItemKind::Type(..) => "assoc type",
1122             };
1123
1124             format!("{} {} in {}{}", kind, ti.name, path_str(), id_str)
1125         }
1126         Some(NodeVariant(ref variant)) => {
1127             format!("variant {} in {}{}",
1128                     variant.node.name,
1129                     path_str(), id_str)
1130         }
1131         Some(NodeField(ref field)) => {
1132             format!("field {} in {}{}",
1133                     field.name,
1134                     path_str(), id_str)
1135         }
1136         Some(NodeExpr(_)) => {
1137             format!("expr {}{}", map.node_to_pretty_string(id), id_str)
1138         }
1139         Some(NodeStmt(_)) => {
1140             format!("stmt {}{}", map.node_to_pretty_string(id), id_str)
1141         }
1142         Some(NodeTy(_)) => {
1143             format!("type {}{}", map.node_to_pretty_string(id), id_str)
1144         }
1145         Some(NodeTraitRef(_)) => {
1146             format!("trait_ref {}{}", map.node_to_pretty_string(id), id_str)
1147         }
1148         Some(NodeLocal(_)) => {
1149             format!("local {}{}", map.node_to_pretty_string(id), id_str)
1150         }
1151         Some(NodePat(_)) => {
1152             format!("pat {}{}", map.node_to_pretty_string(id), id_str)
1153         }
1154         Some(NodeBlock(_)) => {
1155             format!("block {}{}", map.node_to_pretty_string(id), id_str)
1156         }
1157         Some(NodeStructCtor(_)) => {
1158             format!("struct_ctor {}{}", path_str(), id_str)
1159         }
1160         Some(NodeLifetime(_)) => {
1161             format!("lifetime {}{}", map.node_to_pretty_string(id), id_str)
1162         }
1163         Some(NodeTyParam(ref ty_param)) => {
1164             format!("typaram {:?}{}", ty_param, id_str)
1165         }
1166         Some(NodeVisibility(ref vis)) => {
1167             format!("visibility {:?}{}", vis, id_str)
1168         }
1169         None => {
1170             format!("unknown node{}", id_str)
1171         }
1172     }
1173 }