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