]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/map/mod.rs
libsyntax/parse: improve associated item error reporting
[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     pub fn ty_param_owner(&self, id: NodeId) -> NodeId {
446         match self.get(id) {
447             NodeItem(&Item { node: ItemTrait(..), .. }) => id,
448             NodeTyParam(_) => self.get_parent_node(id),
449             _ => {
450                 bug!("ty_param_owner: {} not a type parameter",
451                     self.node_to_string(id))
452             }
453         }
454     }
455
456     pub fn ty_param_name(&self, id: NodeId) -> Name {
457         match self.get(id) {
458             NodeItem(&Item { node: ItemTrait(..), .. }) => {
459                 keywords::SelfType.name()
460             }
461             NodeTyParam(tp) => tp.name,
462             _ => {
463                 bug!("ty_param_name: {} not a type parameter",
464                     self.node_to_string(id))
465             }
466         }
467     }
468
469     pub fn trait_impls(&self, trait_did: DefId) -> &'hir [NodeId] {
470         self.dep_graph.read(DepNode::TraitImpls(trait_did));
471
472         // NB: intentionally bypass `self.forest.krate()` so that we
473         // do not trigger a read of the whole krate here
474         self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
475     }
476
477     pub fn trait_default_impl(&self, trait_did: DefId) -> Option<NodeId> {
478         self.dep_graph.read(DepNode::TraitImpls(trait_did));
479
480         // NB: intentionally bypass `self.forest.krate()` so that we
481         // do not trigger a read of the whole krate here
482         self.forest.krate.trait_default_impl.get(&trait_did).cloned()
483     }
484
485     pub fn trait_is_auto(&self, trait_did: DefId) -> bool {
486         self.trait_default_impl(trait_did).is_some()
487     }
488
489     /// Get the attributes on the krate. This is preferable to
490     /// invoking `krate.attrs` because it registers a tighter
491     /// dep-graph access.
492     pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
493         let crate_root_def_id = DefId::local(CRATE_DEF_INDEX);
494         self.dep_graph.read(DepNode::Hir(crate_root_def_id));
495         &self.forest.krate.attrs
496     }
497
498     /// Retrieve the Node corresponding to `id`, panicking if it cannot
499     /// be found.
500     pub fn get(&self, id: NodeId) -> Node<'hir> {
501         match self.find(id) {
502             Some(node) => node, // read recorded by `find`
503             None => bug!("couldn't find node id {} in the AST map", id)
504         }
505     }
506
507     pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
508         self.as_local_node_id(id).map(|id| self.get(id)) // read recorded by `get`
509     }
510
511     /// Retrieve the Node corresponding to `id`, returning None if
512     /// cannot be found.
513     pub fn find(&self, id: NodeId) -> Option<Node<'hir>> {
514         let result = self.find_entry(id).and_then(|x| x.to_node());
515         if result.is_some() {
516             self.read(id);
517         }
518         result
519     }
520
521     /// Similar to get_parent, returns the parent node id or id if there is no
522     /// parent.
523     /// This function returns the immediate parent in the AST, whereas get_parent
524     /// returns the enclosing item. Note that this might not be the actual parent
525     /// node in the AST - some kinds of nodes are not in the map and these will
526     /// never appear as the parent_node. So you can always walk the parent_nodes
527     /// from a node to the root of the ast (unless you get the same id back here
528     /// that can happen if the id is not in the map itself or is just weird).
529     pub fn get_parent_node(&self, id: NodeId) -> NodeId {
530         self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
531     }
532
533     /// Check if the node is an argument. An argument is a local variable whose
534     /// immediate parent is an item or a closure.
535     pub fn is_argument(&self, id: NodeId) -> bool {
536         match self.find(id) {
537             Some(NodeLocal(_)) => (),
538             _ => return false,
539         }
540         match self.find(self.get_parent_node(id)) {
541             Some(NodeItem(_)) |
542             Some(NodeTraitItem(_)) |
543             Some(NodeImplItem(_)) => true,
544             Some(NodeExpr(e)) => {
545                 match e.node {
546                     ExprClosure(..) => true,
547                     _ => false,
548                 }
549             }
550             _ => false,
551         }
552     }
553
554     /// If there is some error when walking the parents (e.g., a node does not
555     /// have a parent in the map or a node can't be found), then we return the
556     /// last good node id we found. Note that reaching the crate root (id == 0),
557     /// is not an error, since items in the crate module have the crate root as
558     /// parent.
559     fn walk_parent_nodes<F>(&self, start_id: NodeId, found: F) -> Result<NodeId, NodeId>
560         where F: Fn(&Node<'hir>) -> bool
561     {
562         let mut id = start_id;
563         loop {
564             let parent_node = self.get_parent_node(id);
565             if parent_node == CRATE_NODE_ID {
566                 return Ok(CRATE_NODE_ID);
567             }
568             if parent_node == id {
569                 return Err(id);
570             }
571
572             let node = self.find_entry(parent_node);
573             if node.is_none() {
574                 return Err(id);
575             }
576             let node = node.unwrap().to_node();
577             match node {
578                 Some(ref node) => {
579                     if found(node) {
580                         return Ok(parent_node);
581                     }
582                 }
583                 None => {
584                     return Err(parent_node);
585                 }
586             }
587             id = parent_node;
588         }
589     }
590
591     /// Retrieve the NodeId for `id`'s parent item, or `id` itself if no
592     /// parent item is in this map. The "parent item" is the closest parent node
593     /// in the AST which is recorded by the map and is an item, either an item
594     /// in a module, trait, or impl.
595     pub fn get_parent(&self, id: NodeId) -> NodeId {
596         match self.walk_parent_nodes(id, |node| match *node {
597             NodeItem(_) |
598             NodeForeignItem(_) |
599             NodeTraitItem(_) |
600             NodeImplItem(_) => true,
601             _ => false,
602         }) {
603             Ok(id) => id,
604             Err(id) => id,
605         }
606     }
607
608     /// Returns the NodeId of `id`'s nearest module parent, or `id` itself if no
609     /// module parent is in this map.
610     pub fn get_module_parent(&self, id: NodeId) -> NodeId {
611         match self.walk_parent_nodes(id, |node| match *node {
612             NodeItem(&Item { node: Item_::ItemMod(_), .. }) => true,
613             _ => false,
614         }) {
615             Ok(id) => id,
616             Err(id) => id,
617         }
618     }
619
620     /// Returns the nearest enclosing scope. A scope is an item or block.
621     /// FIXME it is not clear to me that all items qualify as scopes - statics
622     /// and associated types probably shouldn't, for example. Behaviour in this
623     /// regard should be expected to be highly unstable.
624     pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
625         match self.walk_parent_nodes(id, |node| match *node {
626             NodeItem(_) |
627             NodeForeignItem(_) |
628             NodeTraitItem(_) |
629             NodeImplItem(_) |
630             NodeBlock(_) => true,
631             _ => false,
632         }) {
633             Ok(id) => Some(id),
634             Err(_) => None,
635         }
636     }
637
638     pub fn get_parent_did(&self, id: NodeId) -> DefId {
639         self.local_def_id(self.get_parent(id))
640     }
641
642     pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
643         let parent = self.get_parent(id);
644         let abi = match self.find_entry(parent) {
645             Some(EntryItem(_, i)) => {
646                 match i.node {
647                     ItemForeignMod(ref nm) => Some(nm.abi),
648                     _ => None
649                 }
650             }
651             _ => None
652         };
653         match abi {
654             Some(abi) => {
655                 self.read(id); // reveals some of the content of a node
656                 abi
657             }
658             None => bug!("expected foreign mod or inlined parent, found {}",
659                           self.node_to_string(parent))
660         }
661     }
662
663     pub fn expect_item(&self, id: NodeId) -> &'hir Item {
664         match self.find(id) { // read recorded by `find`
665             Some(NodeItem(item)) => item,
666             _ => bug!("expected item, found {}", self.node_to_string(id))
667         }
668     }
669
670     pub fn expect_impl_item(&self, id: NodeId) -> &'hir ImplItem {
671         match self.find(id) {
672             Some(NodeImplItem(item)) => item,
673             _ => bug!("expected impl item, found {}", self.node_to_string(id))
674         }
675     }
676
677     pub fn expect_trait_item(&self, id: NodeId) -> &'hir TraitItem {
678         match self.find(id) {
679             Some(NodeTraitItem(item)) => item,
680             _ => bug!("expected trait item, found {}", self.node_to_string(id))
681         }
682     }
683
684     pub fn expect_variant_data(&self, id: NodeId) -> &'hir VariantData {
685         match self.find(id) {
686             Some(NodeItem(i)) => {
687                 match i.node {
688                     ItemStruct(ref struct_def, _) |
689                     ItemUnion(ref struct_def, _) => struct_def,
690                     _ => {
691                         bug!("struct ID bound to non-struct {}",
692                              self.node_to_string(id));
693                     }
694                 }
695             }
696             Some(NodeStructCtor(data)) => data,
697             Some(NodeVariant(variant)) => &variant.node.data,
698             _ => {
699                 bug!("expected struct or variant, found {}",
700                      self.node_to_string(id));
701             }
702         }
703     }
704
705     pub fn expect_variant(&self, id: NodeId) -> &'hir Variant {
706         match self.find(id) {
707             Some(NodeVariant(variant)) => variant,
708             _ => bug!("expected variant, found {}", self.node_to_string(id)),
709         }
710     }
711
712     pub fn expect_foreign_item(&self, id: NodeId) -> &'hir ForeignItem {
713         match self.find(id) {
714             Some(NodeForeignItem(item)) => item,
715             _ => bug!("expected foreign item, found {}", self.node_to_string(id))
716         }
717     }
718
719     pub fn expect_expr(&self, id: NodeId) -> &'hir Expr {
720         match self.find(id) { // read recorded by find
721             Some(NodeExpr(expr)) => expr,
722             _ => bug!("expected expr, found {}", self.node_to_string(id))
723         }
724     }
725
726     pub fn get_inlined_body(&self, def_id: DefId) -> Option<&'hir Body> {
727         self.inlined_bodies.borrow().get(&def_id).map(|&body| {
728             self.dep_graph.read(DepNode::MetaData(def_id));
729             body
730         })
731     }
732
733     pub fn intern_inlined_body(&self, def_id: DefId, body: Body) -> &'hir Body {
734         let body = self.forest.inlined_bodies.alloc(body);
735         self.inlined_bodies.borrow_mut().insert(def_id, body);
736         body
737     }
738
739     /// Returns the name associated with the given NodeId's AST.
740     pub fn name(&self, id: NodeId) -> Name {
741         match self.get(id) {
742             NodeItem(i) => i.name,
743             NodeForeignItem(i) => i.name,
744             NodeImplItem(ii) => ii.name,
745             NodeTraitItem(ti) => ti.name,
746             NodeVariant(v) => v.node.name,
747             NodeField(f) => f.name,
748             NodeLifetime(lt) => lt.name,
749             NodeTyParam(tp) => tp.name,
750             NodeLocal(&Pat { node: PatKind::Binding(_,_,l,_), .. }) => l.node,
751             NodeStructCtor(_) => self.name(self.get_parent(id)),
752             _ => bug!("no name for {}", self.node_to_string(id))
753         }
754     }
755
756     /// Given a node ID, get a list of attributes associated with the AST
757     /// corresponding to the Node ID
758     pub fn attrs(&self, id: NodeId) -> &'hir [ast::Attribute] {
759         self.read(id); // reveals attributes on the node
760         let attrs = match self.find(id) {
761             Some(NodeItem(i)) => Some(&i.attrs[..]),
762             Some(NodeForeignItem(fi)) => Some(&fi.attrs[..]),
763             Some(NodeTraitItem(ref ti)) => Some(&ti.attrs[..]),
764             Some(NodeImplItem(ref ii)) => Some(&ii.attrs[..]),
765             Some(NodeVariant(ref v)) => Some(&v.node.attrs[..]),
766             Some(NodeField(ref f)) => Some(&f.attrs[..]),
767             Some(NodeExpr(ref e)) => Some(&*e.attrs),
768             Some(NodeStmt(ref s)) => Some(s.node.attrs()),
769             // unit/tuple structs take the attributes straight from
770             // the struct definition.
771             Some(NodeStructCtor(_)) => {
772                 return self.attrs(self.get_parent(id));
773             }
774             _ => None
775         };
776         attrs.unwrap_or(&[])
777     }
778
779     /// Returns an iterator that yields the node id's with paths that
780     /// match `parts`.  (Requires `parts` is non-empty.)
781     ///
782     /// For example, if given `parts` equal to `["bar", "quux"]`, then
783     /// the iterator will produce node id's for items with paths
784     /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
785     /// any other such items it can find in the map.
786     pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
787                                  -> NodesMatchingSuffix<'a, 'hir> {
788         NodesMatchingSuffix {
789             map: self,
790             item_name: parts.last().unwrap(),
791             in_which: &parts[..parts.len() - 1],
792             idx: CRATE_NODE_ID,
793         }
794     }
795
796     pub fn span(&self, id: NodeId) -> Span {
797         self.read(id); // reveals span from node
798         match self.find_entry(id) {
799             Some(EntryItem(_, item)) => item.span,
800             Some(EntryForeignItem(_, foreign_item)) => foreign_item.span,
801             Some(EntryTraitItem(_, trait_method)) => trait_method.span,
802             Some(EntryImplItem(_, impl_item)) => impl_item.span,
803             Some(EntryVariant(_, variant)) => variant.span,
804             Some(EntryField(_, field)) => field.span,
805             Some(EntryExpr(_, expr)) => expr.span,
806             Some(EntryStmt(_, stmt)) => stmt.span,
807             Some(EntryTy(_, ty)) => ty.span,
808             Some(EntryTraitRef(_, tr)) => tr.path.span,
809             Some(EntryLocal(_, pat)) => pat.span,
810             Some(EntryPat(_, pat)) => pat.span,
811             Some(EntryBlock(_, block)) => block.span,
812             Some(EntryStructCtor(_, _)) => self.expect_item(self.get_parent(id)).span,
813             Some(EntryLifetime(_, lifetime)) => lifetime.span,
814             Some(EntryTyParam(_, ty_param)) => ty_param.span,
815             Some(EntryVisibility(_, &Visibility::Restricted { ref path, .. })) => path.span,
816             Some(EntryVisibility(_, v)) => bug!("unexpected Visibility {:?}", v),
817
818             Some(RootCrate) => self.forest.krate.span,
819             Some(NotPresent) | None => {
820                 bug!("hir::map::Map::span: id not in map: {:?}", id)
821             }
822         }
823     }
824
825     pub fn span_if_local(&self, id: DefId) -> Option<Span> {
826         self.as_local_node_id(id).map(|id| self.span(id))
827     }
828
829     pub fn node_to_string(&self, id: NodeId) -> String {
830         node_id_to_string(self, id, true)
831     }
832
833     pub fn node_to_user_string(&self, id: NodeId) -> String {
834         node_id_to_string(self, id, false)
835     }
836
837     pub fn node_to_pretty_string(&self, id: NodeId) -> String {
838         print::to_string(self, |s| s.print_node(self.get(id)))
839     }
840 }
841
842 pub struct NodesMatchingSuffix<'a, 'hir:'a> {
843     map: &'a Map<'hir>,
844     item_name: &'a String,
845     in_which: &'a [String],
846     idx: NodeId,
847 }
848
849 impl<'a, 'hir> NodesMatchingSuffix<'a, 'hir> {
850     /// Returns true only if some suffix of the module path for parent
851     /// matches `self.in_which`.
852     ///
853     /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
854     /// returns true if parent's path ends with the suffix
855     /// `x_0::x_1::...::x_k`.
856     fn suffix_matches(&self, parent: NodeId) -> bool {
857         let mut cursor = parent;
858         for part in self.in_which.iter().rev() {
859             let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
860                 None => return false,
861                 Some((node_id, name)) => (node_id, name),
862             };
863             if mod_name != &**part {
864                 return false;
865             }
866             cursor = self.map.get_parent(mod_id);
867         }
868         return true;
869
870         // Finds the first mod in parent chain for `id`, along with
871         // that mod's name.
872         //
873         // If `id` itself is a mod named `m` with parent `p`, then
874         // returns `Some(id, m, p)`.  If `id` has no mod in its parent
875         // chain, then returns `None`.
876         fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
877             loop {
878                 match map.find(id) {
879                     None => return None,
880                     Some(NodeItem(item)) if item_is_mod(&item) =>
881                         return Some((id, item.name)),
882                     _ => {}
883                 }
884                 let parent = map.get_parent(id);
885                 if parent == id { return None }
886                 id = parent;
887             }
888
889             fn item_is_mod(item: &Item) -> bool {
890                 match item.node {
891                     ItemMod(_) => true,
892                     _ => false,
893                 }
894             }
895         }
896     }
897
898     // We are looking at some node `n` with a given name and parent
899     // id; do their names match what I am seeking?
900     fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
901         name == &**self.item_name && self.suffix_matches(parent_of_n)
902     }
903 }
904
905 impl<'a, 'hir> Iterator for NodesMatchingSuffix<'a, 'hir> {
906     type Item = NodeId;
907
908     fn next(&mut self) -> Option<NodeId> {
909         loop {
910             let idx = self.idx;
911             if idx.as_usize() >= self.map.entry_count() {
912                 return None;
913             }
914             self.idx = NodeId::from_u32(self.idx.as_u32() + 1);
915             let name = match self.map.find_entry(idx) {
916                 Some(EntryItem(_, n))       => n.name(),
917                 Some(EntryForeignItem(_, n))=> n.name(),
918                 Some(EntryTraitItem(_, n))  => n.name(),
919                 Some(EntryImplItem(_, n))   => n.name(),
920                 Some(EntryVariant(_, n))    => n.name(),
921                 Some(EntryField(_, n))      => n.name(),
922                 _ => continue,
923             };
924             if self.matches_names(self.map.get_parent(idx), name) {
925                 return Some(idx)
926             }
927         }
928     }
929 }
930
931 trait Named {
932     fn name(&self) -> Name;
933 }
934
935 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
936
937 impl Named for Item { fn name(&self) -> Name { self.name } }
938 impl Named for ForeignItem { fn name(&self) -> Name { self.name } }
939 impl Named for Variant_ { fn name(&self) -> Name { self.name } }
940 impl Named for StructField { fn name(&self) -> Name { self.name } }
941 impl Named for TraitItem { fn name(&self) -> Name { self.name } }
942 impl Named for ImplItem { fn name(&self) -> Name { self.name } }
943
944 pub fn map_crate<'hir>(forest: &'hir mut Forest,
945                        definitions: Definitions)
946                        -> Map<'hir> {
947     let mut collector = NodeCollector::root(&forest.krate);
948     intravisit::walk_crate(&mut collector, &forest.krate);
949     let map = collector.map;
950
951     if log_enabled!(::log::LogLevel::Debug) {
952         // This only makes sense for ordered stores; note the
953         // enumerate to count the number of entries.
954         let (entries_less_1, _) = map.iter().filter(|&x| {
955             match *x {
956                 NotPresent => false,
957                 _ => true
958             }
959         }).enumerate().last().expect("AST map was empty after folding?");
960
961         let entries = entries_less_1 + 1;
962         let vector_length = map.len();
963         debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
964               entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
965     }
966
967     let map = Map {
968         forest: forest,
969         dep_graph: forest.dep_graph.clone(),
970         map: map,
971         definitions: definitions,
972         inlined_bodies: RefCell::new(DefIdMap()),
973     };
974
975     hir_id_validator::check_crate(&map);
976
977     map
978 }
979
980 /// Identical to the `PpAnn` implementation for `hir::Crate`,
981 /// except it avoids creating a dependency on the whole crate.
982 impl<'hir> print::PpAnn for Map<'hir> {
983     fn nested(&self, state: &mut print::State, nested: print::Nested) -> io::Result<()> {
984         match nested {
985             Nested::Item(id) => state.print_item(self.expect_item(id.id)),
986             Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
987             Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
988             Nested::Body(id) => state.print_expr(&self.body(id).value),
989             Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
990         }
991     }
992 }
993
994 impl<'a> print::State<'a> {
995     pub fn print_node(&mut self, node: Node) -> io::Result<()> {
996         match node {
997             NodeItem(a)        => self.print_item(&a),
998             NodeForeignItem(a) => self.print_foreign_item(&a),
999             NodeTraitItem(a)   => self.print_trait_item(a),
1000             NodeImplItem(a)    => self.print_impl_item(a),
1001             NodeVariant(a)     => self.print_variant(&a),
1002             NodeExpr(a)        => self.print_expr(&a),
1003             NodeStmt(a)        => self.print_stmt(&a),
1004             NodeTy(a)          => self.print_type(&a),
1005             NodeTraitRef(a)    => self.print_trait_ref(&a),
1006             NodeLocal(a)       |
1007             NodePat(a)         => self.print_pat(&a),
1008             NodeBlock(a)       => {
1009                 use syntax::print::pprust::PrintState;
1010
1011                 // containing cbox, will be closed by print-block at }
1012                 self.cbox(print::indent_unit)?;
1013                 // head-ibox, will be closed by print-block after {
1014                 self.ibox(0)?;
1015                 self.print_block(&a)
1016             }
1017             NodeLifetime(a)    => self.print_lifetime(&a),
1018             NodeVisibility(a)  => self.print_visibility(&a),
1019             NodeTyParam(_)     => bug!("cannot print TyParam"),
1020             NodeField(_)       => bug!("cannot print StructField"),
1021             // these cases do not carry enough information in the
1022             // hir_map to reconstruct their full structure for pretty
1023             // printing.
1024             NodeStructCtor(_)  => bug!("cannot print isolated StructCtor"),
1025         }
1026     }
1027 }
1028
1029 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
1030     let id_str = format!(" (id={})", id);
1031     let id_str = if include_id { &id_str[..] } else { "" };
1032
1033     let path_str = || {
1034         // This functionality is used for debugging, try to use TyCtxt to get
1035         // the user-friendly path, otherwise fall back to stringifying DefPath.
1036         ::ty::tls::with_opt(|tcx| {
1037             if let Some(tcx) = tcx {
1038                 tcx.node_path_str(id)
1039             } else if let Some(path) = map.def_path_from_id(id) {
1040                 path.data.into_iter().map(|elem| {
1041                     elem.data.to_string()
1042                 }).collect::<Vec<_>>().join("::")
1043             } else {
1044                 String::from("<missing path>")
1045             }
1046         })
1047     };
1048
1049     match map.find(id) {
1050         Some(NodeItem(item)) => {
1051             let item_str = match item.node {
1052                 ItemExternCrate(..) => "extern crate",
1053                 ItemUse(..) => "use",
1054                 ItemStatic(..) => "static",
1055                 ItemConst(..) => "const",
1056                 ItemFn(..) => "fn",
1057                 ItemMod(..) => "mod",
1058                 ItemForeignMod(..) => "foreign mod",
1059                 ItemTy(..) => "ty",
1060                 ItemEnum(..) => "enum",
1061                 ItemStruct(..) => "struct",
1062                 ItemUnion(..) => "union",
1063                 ItemTrait(..) => "trait",
1064                 ItemImpl(..) => "impl",
1065                 ItemDefaultImpl(..) => "default impl",
1066             };
1067             format!("{} {}{}", item_str, path_str(), id_str)
1068         }
1069         Some(NodeForeignItem(_)) => {
1070             format!("foreign item {}{}", path_str(), id_str)
1071         }
1072         Some(NodeImplItem(ii)) => {
1073             match ii.node {
1074                 ImplItemKind::Const(..) => {
1075                     format!("assoc const {} in {}{}", ii.name, path_str(), id_str)
1076                 }
1077                 ImplItemKind::Method(..) => {
1078                     format!("method {} in {}{}", ii.name, path_str(), id_str)
1079                 }
1080                 ImplItemKind::Type(_) => {
1081                     format!("assoc type {} in {}{}", ii.name, path_str(), id_str)
1082                 }
1083             }
1084         }
1085         Some(NodeTraitItem(ti)) => {
1086             let kind = match ti.node {
1087                 TraitItemKind::Const(..) => "assoc constant",
1088                 TraitItemKind::Method(..) => "trait method",
1089                 TraitItemKind::Type(..) => "assoc type",
1090             };
1091
1092             format!("{} {} in {}{}", kind, ti.name, path_str(), id_str)
1093         }
1094         Some(NodeVariant(ref variant)) => {
1095             format!("variant {} in {}{}",
1096                     variant.node.name,
1097                     path_str(), id_str)
1098         }
1099         Some(NodeField(ref field)) => {
1100             format!("field {} in {}{}",
1101                     field.name,
1102                     path_str(), id_str)
1103         }
1104         Some(NodeExpr(_)) => {
1105             format!("expr {}{}", map.node_to_pretty_string(id), id_str)
1106         }
1107         Some(NodeStmt(_)) => {
1108             format!("stmt {}{}", map.node_to_pretty_string(id), id_str)
1109         }
1110         Some(NodeTy(_)) => {
1111             format!("type {}{}", map.node_to_pretty_string(id), id_str)
1112         }
1113         Some(NodeTraitRef(_)) => {
1114             format!("trait_ref {}{}", map.node_to_pretty_string(id), id_str)
1115         }
1116         Some(NodeLocal(_)) => {
1117             format!("local {}{}", map.node_to_pretty_string(id), id_str)
1118         }
1119         Some(NodePat(_)) => {
1120             format!("pat {}{}", map.node_to_pretty_string(id), id_str)
1121         }
1122         Some(NodeBlock(_)) => {
1123             format!("block {}{}", map.node_to_pretty_string(id), id_str)
1124         }
1125         Some(NodeStructCtor(_)) => {
1126             format!("struct_ctor {}{}", path_str(), id_str)
1127         }
1128         Some(NodeLifetime(_)) => {
1129             format!("lifetime {}{}", map.node_to_pretty_string(id), id_str)
1130         }
1131         Some(NodeTyParam(ref ty_param)) => {
1132             format!("typaram {:?}{}", ty_param, id_str)
1133         }
1134         Some(NodeVisibility(ref vis)) => {
1135             format!("visibility {:?}{}", vis, id_str)
1136         }
1137         None => {
1138             format!("unknown node{}", id_str)
1139         }
1140     }
1141 }