]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/map/mod.rs
Rollup merge of #42496 - Razaekel:feature/integer_max-min, r=BurntSushi
[rust.git] / src / librustc / hir / map / mod.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 pub use self::Node::*;
12 use self::MapEntry::*;
13 use self::collector::NodeCollector;
14 pub use self::def_collector::{DefCollector, MacroInvocationData};
15 pub use self::definitions::{Definitions, DefKey, DefPath, DefPathData,
16                             DisambiguatedDefPathData, DefPathHash};
17
18 use dep_graph::{DepGraph, DepNode, DepKind};
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::new_no_params(DepKind::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 {
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                     let def_index = self.definitions.opt_def_index(id).unwrap();
293                     let def_path_hash = self.definitions.def_path_hash(def_index);
294
295                     if let Some(last_id) = last_expr {
296                         // The body may have a separate dep node
297                         if entry.is_body_owner(last_id) {
298                             return def_path_hash.to_dep_node(DepKind::HirBody);
299                         }
300                     }
301                     return def_path_hash.to_dep_node(DepKind::Hir);
302                 }
303
304                 EntryVariant(p, v) => {
305                     id = p;
306
307                     if last_expr.is_some() {
308                         if v.node.disr_expr.map(|e| e.node_id) == last_expr {
309                             // The enum parent holds both Hir and HirBody nodes.
310                             let def_index = self.definitions.opt_def_index(id).unwrap();
311                             let def_path_hash = self.definitions.def_path_hash(def_index);
312                             return def_path_hash.to_dep_node(DepKind::HirBody);
313                         }
314                     }
315                 }
316
317                 EntryForeignItem(p, _) |
318                 EntryField(p, _) |
319                 EntryStmt(p, _) |
320                 EntryTy(p, _) |
321                 EntryTraitRef(p, _) |
322                 EntryLocal(p, _) |
323                 EntryPat(p, _) |
324                 EntryBlock(p, _) |
325                 EntryStructCtor(p, _) |
326                 EntryLifetime(p, _) |
327                 EntryTyParam(p, _) |
328                 EntryVisibility(p, _) =>
329                     id = p,
330
331                 EntryExpr(p, _) => {
332                     last_expr = Some(id);
333                     id = p;
334                 }
335
336                 RootCrate => {
337                     let def_path_hash = self.definitions.def_path_hash(CRATE_DEF_INDEX);
338                     return def_path_hash.to_dep_node(DepKind::Hir);
339                 }
340
341                 NotPresent =>
342                     // Some nodes, notably macro definitions, are not
343                     // present in the map for whatever reason, but
344                     // they *do* have def-ids. So if we encounter an
345                     // empty hole, check for that case.
346                     return self.definitions.opt_def_index(id)
347                                .map(|def_index| {
348                                     let def_path_hash = self.definitions.def_path_hash(def_index);
349                                     def_path_hash.to_dep_node(DepKind::Hir)
350                                 })
351                                .unwrap_or_else(|| {
352                                    bug!("Walking parents from `{}` \
353                                          led to `NotPresent` at `{}`",
354                                         id0, id)
355                                }),
356             }
357         }
358     }
359
360     pub fn definitions(&self) -> &Definitions {
361         &self.definitions
362     }
363
364     pub fn def_key(&self, def_id: DefId) -> DefKey {
365         assert!(def_id.is_local());
366         self.definitions.def_key(def_id.index)
367     }
368
369     pub fn def_path_from_id(&self, id: NodeId) -> Option<DefPath> {
370         self.opt_local_def_id(id).map(|def_id| {
371             self.def_path(def_id)
372         })
373     }
374
375     pub fn def_path(&self, def_id: DefId) -> DefPath {
376         assert!(def_id.is_local());
377         self.definitions.def_path(def_id.index)
378     }
379
380     pub fn def_index_for_def_key(&self, def_key: DefKey) -> Option<DefIndex> {
381         self.definitions.def_index_for_def_key(def_key)
382     }
383
384     pub fn local_def_id(&self, node: NodeId) -> DefId {
385         self.opt_local_def_id(node).unwrap_or_else(|| {
386             bug!("local_def_id: no entry for `{}`, which has a map of `{:?}`",
387                  node, self.find_entry(node))
388         })
389     }
390
391     pub fn opt_local_def_id(&self, node: NodeId) -> Option<DefId> {
392         self.definitions.opt_local_def_id(node)
393     }
394
395     pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
396         self.definitions.as_local_node_id(def_id)
397     }
398
399     fn entry_count(&self) -> usize {
400         self.map.len()
401     }
402
403     fn find_entry(&self, id: NodeId) -> Option<MapEntry<'hir>> {
404         self.map.get(id.as_usize()).cloned()
405     }
406
407     pub fn krate(&self) -> &'hir Crate {
408         self.forest.krate()
409     }
410
411     pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem {
412         self.read(id.node_id);
413
414         // NB: intentionally bypass `self.forest.krate()` so that we
415         // do not trigger a read of the whole krate here
416         self.forest.krate.trait_item(id)
417     }
418
419     pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem {
420         self.read(id.node_id);
421
422         // NB: intentionally bypass `self.forest.krate()` so that we
423         // do not trigger a read of the whole krate here
424         self.forest.krate.impl_item(id)
425     }
426
427     pub fn body(&self, id: BodyId) -> &'hir Body {
428         self.read(id.node_id);
429
430         // NB: intentionally bypass `self.forest.krate()` so that we
431         // do not trigger a read of the whole krate here
432         self.forest.krate.body(id)
433     }
434
435     /// Returns the `NodeId` that corresponds to the definition of
436     /// which this is the body of, i.e. a `fn`, `const` or `static`
437     /// item (possibly associated), or a closure, or the body itself
438     /// for embedded constant expressions (e.g. `N` in `[T; N]`).
439     pub fn body_owner(&self, BodyId { node_id }: BodyId) -> NodeId {
440         let parent = self.get_parent_node(node_id);
441         if self.map[parent.as_usize()].is_body_owner(node_id) {
442             parent
443         } else {
444             node_id
445         }
446     }
447
448     pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
449         self.local_def_id(self.body_owner(id))
450     }
451
452     /// Given a node id, returns the `BodyId` associated with it,
453     /// if the node is a body owner, otherwise returns `None`.
454     pub fn maybe_body_owned_by(&self, id: NodeId) -> Option<BodyId> {
455         if let Some(entry) = self.find_entry(id) {
456             if let Some(body_id) = entry.associated_body() {
457                 // For item-like things and closures, the associated
458                 // body has its own distinct id, and that is returned
459                 // by `associated_body`.
460                 Some(body_id)
461             } else {
462                 // For some expressions, the expression is its own body.
463                 if let EntryExpr(_, expr) = entry {
464                     Some(BodyId { node_id: expr.id })
465                 } else {
466                     None
467                 }
468             }
469         } else {
470             bug!("no entry for id `{}`", id)
471         }
472     }
473
474     /// Given a body owner's id, returns the `BodyId` associated with it.
475     pub fn body_owned_by(&self, id: NodeId) -> BodyId {
476         self.maybe_body_owned_by(id).unwrap_or_else(|| {
477             span_bug!(self.span(id), "body_owned_by: {} has no associated body",
478                       self.node_to_string(id));
479         })
480     }
481
482     pub fn ty_param_owner(&self, id: NodeId) -> NodeId {
483         match self.get(id) {
484             NodeItem(&Item { node: ItemTrait(..), .. }) => id,
485             NodeTyParam(_) => self.get_parent_node(id),
486             _ => {
487                 bug!("ty_param_owner: {} not a type parameter",
488                     self.node_to_string(id))
489             }
490         }
491     }
492
493     pub fn ty_param_name(&self, id: NodeId) -> Name {
494         match self.get(id) {
495             NodeItem(&Item { node: ItemTrait(..), .. }) => {
496                 keywords::SelfType.name()
497             }
498             NodeTyParam(tp) => tp.name,
499             _ => {
500                 bug!("ty_param_name: {} not a type parameter",
501                     self.node_to_string(id))
502             }
503         }
504     }
505
506     pub fn trait_impls(&self, trait_did: DefId) -> &'hir [NodeId] {
507         self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
508
509         // NB: intentionally bypass `self.forest.krate()` so that we
510         // do not trigger a read of the whole krate here
511         self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
512     }
513
514     pub fn trait_default_impl(&self, trait_did: DefId) -> Option<NodeId> {
515         self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
516
517         // NB: intentionally bypass `self.forest.krate()` so that we
518         // do not trigger a read of the whole krate here
519         self.forest.krate.trait_default_impl.get(&trait_did).cloned()
520     }
521
522     pub fn trait_is_auto(&self, trait_did: DefId) -> bool {
523         self.trait_default_impl(trait_did).is_some()
524     }
525
526     /// Get the attributes on the krate. This is preferable to
527     /// invoking `krate.attrs` because it registers a tighter
528     /// dep-graph access.
529     pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
530         let def_path_hash = self.definitions.def_path_hash(CRATE_DEF_INDEX);
531
532         self.dep_graph.read(def_path_hash.to_dep_node(DepKind::Hir));
533         &self.forest.krate.attrs
534     }
535
536     /// Retrieve the Node corresponding to `id`, panicking if it cannot
537     /// be found.
538     pub fn get(&self, id: NodeId) -> Node<'hir> {
539         match self.find(id) {
540             Some(node) => node, // read recorded by `find`
541             None => bug!("couldn't find node id {} in the AST map", id)
542         }
543     }
544
545     pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
546         self.as_local_node_id(id).map(|id| self.get(id)) // read recorded by `get`
547     }
548
549     /// Retrieve the Node corresponding to `id`, returning None if
550     /// cannot be found.
551     pub fn find(&self, id: NodeId) -> Option<Node<'hir>> {
552         let result = self.find_entry(id).and_then(|x| x.to_node());
553         if result.is_some() {
554             self.read(id);
555         }
556         result
557     }
558
559     /// Similar to get_parent, returns the parent node id or id if there is no
560     /// parent.
561     /// This function returns the immediate parent in the AST, whereas get_parent
562     /// returns the enclosing item. Note that this might not be the actual parent
563     /// node in the AST - some kinds of nodes are not in the map and these will
564     /// never appear as the parent_node. So you can always walk the parent_nodes
565     /// from a node to the root of the ast (unless you get the same id back here
566     /// that can happen if the id is not in the map itself or is just weird).
567     pub fn get_parent_node(&self, id: NodeId) -> NodeId {
568         self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
569     }
570
571     /// Check if the node is an argument. An argument is a local variable whose
572     /// immediate parent is an item or a closure.
573     pub fn is_argument(&self, id: NodeId) -> bool {
574         match self.find(id) {
575             Some(NodeLocal(_)) => (),
576             _ => return false,
577         }
578         match self.find(self.get_parent_node(id)) {
579             Some(NodeItem(_)) |
580             Some(NodeTraitItem(_)) |
581             Some(NodeImplItem(_)) => true,
582             Some(NodeExpr(e)) => {
583                 match e.node {
584                     ExprClosure(..) => true,
585                     _ => false,
586                 }
587             }
588             _ => false,
589         }
590     }
591
592     /// If there is some error when walking the parents (e.g., a node does not
593     /// have a parent in the map or a node can't be found), then we return the
594     /// last good node id we found. Note that reaching the crate root (id == 0),
595     /// is not an error, since items in the crate module have the crate root as
596     /// parent.
597     fn walk_parent_nodes<F>(&self, start_id: NodeId, found: F) -> Result<NodeId, NodeId>
598         where F: Fn(&Node<'hir>) -> bool
599     {
600         let mut id = start_id;
601         loop {
602             let parent_node = self.get_parent_node(id);
603             if parent_node == CRATE_NODE_ID {
604                 return Ok(CRATE_NODE_ID);
605             }
606             if parent_node == id {
607                 return Err(id);
608             }
609
610             let node = self.find_entry(parent_node);
611             if node.is_none() {
612                 return Err(id);
613             }
614             let node = node.unwrap().to_node();
615             match node {
616                 Some(ref node) => {
617                     if found(node) {
618                         return Ok(parent_node);
619                     }
620                 }
621                 None => {
622                     return Err(parent_node);
623                 }
624             }
625             id = parent_node;
626         }
627     }
628
629     /// Retrieve the NodeId for `id`'s parent item, or `id` itself if no
630     /// parent item is in this map. The "parent item" is the closest parent node
631     /// in the AST which is recorded by the map and is an item, either an item
632     /// in a module, trait, or impl.
633     pub fn get_parent(&self, id: NodeId) -> NodeId {
634         match self.walk_parent_nodes(id, |node| match *node {
635             NodeItem(_) |
636             NodeForeignItem(_) |
637             NodeTraitItem(_) |
638             NodeImplItem(_) => true,
639             _ => false,
640         }) {
641             Ok(id) => id,
642             Err(id) => id,
643         }
644     }
645
646     /// Returns the NodeId of `id`'s nearest module parent, or `id` itself if no
647     /// module parent is in this map.
648     pub fn get_module_parent(&self, id: NodeId) -> DefId {
649         let id = match self.walk_parent_nodes(id, |node| match *node {
650             NodeItem(&Item { node: Item_::ItemMod(_), .. }) => true,
651             _ => false,
652         }) {
653             Ok(id) => id,
654             Err(id) => id,
655         };
656         self.local_def_id(id)
657     }
658
659     /// Returns the nearest enclosing scope. A scope is an item or block.
660     /// FIXME it is not clear to me that all items qualify as scopes - statics
661     /// and associated types probably shouldn't, for example. Behaviour in this
662     /// regard should be expected to be highly unstable.
663     pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
664         match self.walk_parent_nodes(id, |node| match *node {
665             NodeItem(_) |
666             NodeForeignItem(_) |
667             NodeTraitItem(_) |
668             NodeImplItem(_) |
669             NodeBlock(_) => true,
670             _ => false,
671         }) {
672             Ok(id) => Some(id),
673             Err(_) => None,
674         }
675     }
676
677     pub fn get_parent_did(&self, id: NodeId) -> DefId {
678         self.local_def_id(self.get_parent(id))
679     }
680
681     pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
682         let parent = self.get_parent(id);
683         let abi = match self.find_entry(parent) {
684             Some(EntryItem(_, i)) => {
685                 match i.node {
686                     ItemForeignMod(ref nm) => Some(nm.abi),
687                     _ => None
688                 }
689             }
690             _ => None
691         };
692         match abi {
693             Some(abi) => {
694                 self.read(id); // reveals some of the content of a node
695                 abi
696             }
697             None => bug!("expected foreign mod or inlined parent, found {}",
698                           self.node_to_string(parent))
699         }
700     }
701
702     pub fn expect_item(&self, id: NodeId) -> &'hir Item {
703         match self.find(id) { // read recorded by `find`
704             Some(NodeItem(item)) => item,
705             _ => bug!("expected item, found {}", self.node_to_string(id))
706         }
707     }
708
709     pub fn expect_impl_item(&self, id: NodeId) -> &'hir ImplItem {
710         match self.find(id) {
711             Some(NodeImplItem(item)) => item,
712             _ => bug!("expected impl item, found {}", self.node_to_string(id))
713         }
714     }
715
716     pub fn expect_trait_item(&self, id: NodeId) -> &'hir TraitItem {
717         match self.find(id) {
718             Some(NodeTraitItem(item)) => item,
719             _ => bug!("expected trait item, found {}", self.node_to_string(id))
720         }
721     }
722
723     pub fn expect_variant_data(&self, id: NodeId) -> &'hir VariantData {
724         match self.find(id) {
725             Some(NodeItem(i)) => {
726                 match i.node {
727                     ItemStruct(ref struct_def, _) |
728                     ItemUnion(ref struct_def, _) => struct_def,
729                     _ => {
730                         bug!("struct ID bound to non-struct {}",
731                              self.node_to_string(id));
732                     }
733                 }
734             }
735             Some(NodeStructCtor(data)) => data,
736             Some(NodeVariant(variant)) => &variant.node.data,
737             _ => {
738                 bug!("expected struct or variant, found {}",
739                      self.node_to_string(id));
740             }
741         }
742     }
743
744     pub fn expect_variant(&self, id: NodeId) -> &'hir Variant {
745         match self.find(id) {
746             Some(NodeVariant(variant)) => variant,
747             _ => bug!("expected variant, found {}", self.node_to_string(id)),
748         }
749     }
750
751     pub fn expect_foreign_item(&self, id: NodeId) -> &'hir ForeignItem {
752         match self.find(id) {
753             Some(NodeForeignItem(item)) => item,
754             _ => bug!("expected foreign item, found {}", self.node_to_string(id))
755         }
756     }
757
758     pub fn expect_expr(&self, id: NodeId) -> &'hir Expr {
759         match self.find(id) { // read recorded by find
760             Some(NodeExpr(expr)) => expr,
761             _ => bug!("expected expr, found {}", self.node_to_string(id))
762         }
763     }
764
765     pub fn get_inlined_body_untracked(&self, def_id: DefId) -> Option<&'hir Body> {
766         self.inlined_bodies.borrow().get(&def_id).cloned()
767     }
768
769     pub fn intern_inlined_body(&self, def_id: DefId, body: Body) -> &'hir Body {
770         let body = self.forest.inlined_bodies.alloc(body);
771         self.inlined_bodies.borrow_mut().insert(def_id, body);
772         body
773     }
774
775     /// Returns the name associated with the given NodeId's AST.
776     pub fn name(&self, id: NodeId) -> Name {
777         match self.get(id) {
778             NodeItem(i) => i.name,
779             NodeForeignItem(i) => i.name,
780             NodeImplItem(ii) => ii.name,
781             NodeTraitItem(ti) => ti.name,
782             NodeVariant(v) => v.node.name,
783             NodeField(f) => f.name,
784             NodeLifetime(lt) => lt.name,
785             NodeTyParam(tp) => tp.name,
786             NodeLocal(&Pat { node: PatKind::Binding(_,_,l,_), .. }) => l.node,
787             NodeStructCtor(_) => self.name(self.get_parent(id)),
788             _ => bug!("no name for {}", self.node_to_string(id))
789         }
790     }
791
792     /// Given a node ID, get a list of attributes associated with the AST
793     /// corresponding to the Node ID
794     pub fn attrs(&self, id: NodeId) -> &'hir [ast::Attribute] {
795         self.read(id); // reveals attributes on the node
796         let attrs = match self.find(id) {
797             Some(NodeItem(i)) => Some(&i.attrs[..]),
798             Some(NodeForeignItem(fi)) => Some(&fi.attrs[..]),
799             Some(NodeTraitItem(ref ti)) => Some(&ti.attrs[..]),
800             Some(NodeImplItem(ref ii)) => Some(&ii.attrs[..]),
801             Some(NodeVariant(ref v)) => Some(&v.node.attrs[..]),
802             Some(NodeField(ref f)) => Some(&f.attrs[..]),
803             Some(NodeExpr(ref e)) => Some(&*e.attrs),
804             Some(NodeStmt(ref s)) => Some(s.node.attrs()),
805             // unit/tuple structs take the attributes straight from
806             // the struct definition.
807             Some(NodeStructCtor(_)) => {
808                 return self.attrs(self.get_parent(id));
809             }
810             _ => None
811         };
812         attrs.unwrap_or(&[])
813     }
814
815     /// Returns an iterator that yields the node id's with paths that
816     /// match `parts`.  (Requires `parts` is non-empty.)
817     ///
818     /// For example, if given `parts` equal to `["bar", "quux"]`, then
819     /// the iterator will produce node id's for items with paths
820     /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
821     /// any other such items it can find in the map.
822     pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
823                                  -> NodesMatchingSuffix<'a, 'hir> {
824         NodesMatchingSuffix {
825             map: self,
826             item_name: parts.last().unwrap(),
827             in_which: &parts[..parts.len() - 1],
828             idx: CRATE_NODE_ID,
829         }
830     }
831
832     pub fn span(&self, id: NodeId) -> Span {
833         self.read(id); // reveals span from node
834         match self.find_entry(id) {
835             Some(EntryItem(_, item)) => item.span,
836             Some(EntryForeignItem(_, foreign_item)) => foreign_item.span,
837             Some(EntryTraitItem(_, trait_method)) => trait_method.span,
838             Some(EntryImplItem(_, impl_item)) => impl_item.span,
839             Some(EntryVariant(_, variant)) => variant.span,
840             Some(EntryField(_, field)) => field.span,
841             Some(EntryExpr(_, expr)) => expr.span,
842             Some(EntryStmt(_, stmt)) => stmt.span,
843             Some(EntryTy(_, ty)) => ty.span,
844             Some(EntryTraitRef(_, tr)) => tr.path.span,
845             Some(EntryLocal(_, pat)) => pat.span,
846             Some(EntryPat(_, pat)) => pat.span,
847             Some(EntryBlock(_, block)) => block.span,
848             Some(EntryStructCtor(_, _)) => self.expect_item(self.get_parent(id)).span,
849             Some(EntryLifetime(_, lifetime)) => lifetime.span,
850             Some(EntryTyParam(_, ty_param)) => ty_param.span,
851             Some(EntryVisibility(_, &Visibility::Restricted { ref path, .. })) => path.span,
852             Some(EntryVisibility(_, v)) => bug!("unexpected Visibility {:?}", v),
853
854             Some(RootCrate) => self.forest.krate.span,
855             Some(NotPresent) | None => {
856                 bug!("hir::map::Map::span: id not in map: {:?}", id)
857             }
858         }
859     }
860
861     pub fn span_if_local(&self, id: DefId) -> Option<Span> {
862         self.as_local_node_id(id).map(|id| self.span(id))
863     }
864
865     pub fn node_to_string(&self, id: NodeId) -> String {
866         node_id_to_string(self, id, true)
867     }
868
869     pub fn node_to_user_string(&self, id: NodeId) -> String {
870         node_id_to_string(self, id, false)
871     }
872
873     pub fn node_to_pretty_string(&self, id: NodeId) -> String {
874         print::to_string(self, |s| s.print_node(self.get(id)))
875     }
876 }
877
878 pub struct NodesMatchingSuffix<'a, 'hir:'a> {
879     map: &'a Map<'hir>,
880     item_name: &'a String,
881     in_which: &'a [String],
882     idx: NodeId,
883 }
884
885 impl<'a, 'hir> NodesMatchingSuffix<'a, 'hir> {
886     /// Returns true only if some suffix of the module path for parent
887     /// matches `self.in_which`.
888     ///
889     /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
890     /// returns true if parent's path ends with the suffix
891     /// `x_0::x_1::...::x_k`.
892     fn suffix_matches(&self, parent: NodeId) -> bool {
893         let mut cursor = parent;
894         for part in self.in_which.iter().rev() {
895             let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
896                 None => return false,
897                 Some((node_id, name)) => (node_id, name),
898             };
899             if mod_name != &**part {
900                 return false;
901             }
902             cursor = self.map.get_parent(mod_id);
903         }
904         return true;
905
906         // Finds the first mod in parent chain for `id`, along with
907         // that mod's name.
908         //
909         // If `id` itself is a mod named `m` with parent `p`, then
910         // returns `Some(id, m, p)`.  If `id` has no mod in its parent
911         // chain, then returns `None`.
912         fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
913             loop {
914                 match map.find(id) {
915                     None => return None,
916                     Some(NodeItem(item)) if item_is_mod(&item) =>
917                         return Some((id, item.name)),
918                     _ => {}
919                 }
920                 let parent = map.get_parent(id);
921                 if parent == id { return None }
922                 id = parent;
923             }
924
925             fn item_is_mod(item: &Item) -> bool {
926                 match item.node {
927                     ItemMod(_) => true,
928                     _ => false,
929                 }
930             }
931         }
932     }
933
934     // We are looking at some node `n` with a given name and parent
935     // id; do their names match what I am seeking?
936     fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
937         name == &**self.item_name && self.suffix_matches(parent_of_n)
938     }
939 }
940
941 impl<'a, 'hir> Iterator for NodesMatchingSuffix<'a, 'hir> {
942     type Item = NodeId;
943
944     fn next(&mut self) -> Option<NodeId> {
945         loop {
946             let idx = self.idx;
947             if idx.as_usize() >= self.map.entry_count() {
948                 return None;
949             }
950             self.idx = NodeId::from_u32(self.idx.as_u32() + 1);
951             let name = match self.map.find_entry(idx) {
952                 Some(EntryItem(_, n))       => n.name(),
953                 Some(EntryForeignItem(_, n))=> n.name(),
954                 Some(EntryTraitItem(_, n))  => n.name(),
955                 Some(EntryImplItem(_, n))   => n.name(),
956                 Some(EntryVariant(_, n))    => n.name(),
957                 Some(EntryField(_, n))      => n.name(),
958                 _ => continue,
959             };
960             if self.matches_names(self.map.get_parent(idx), name) {
961                 return Some(idx)
962             }
963         }
964     }
965 }
966
967 trait Named {
968     fn name(&self) -> Name;
969 }
970
971 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
972
973 impl Named for Item { fn name(&self) -> Name { self.name } }
974 impl Named for ForeignItem { fn name(&self) -> Name { self.name } }
975 impl Named for Variant_ { fn name(&self) -> Name { self.name } }
976 impl Named for StructField { fn name(&self) -> Name { self.name } }
977 impl Named for TraitItem { fn name(&self) -> Name { self.name } }
978 impl Named for ImplItem { fn name(&self) -> Name { self.name } }
979
980 pub fn map_crate<'hir>(forest: &'hir mut Forest,
981                        definitions: Definitions)
982                        -> Map<'hir> {
983     let mut collector = NodeCollector::root(&forest.krate);
984     intravisit::walk_crate(&mut collector, &forest.krate);
985     let map = collector.map;
986
987     if log_enabled!(::log::LogLevel::Debug) {
988         // This only makes sense for ordered stores; note the
989         // enumerate to count the number of entries.
990         let (entries_less_1, _) = map.iter().filter(|&x| {
991             match *x {
992                 NotPresent => false,
993                 _ => true
994             }
995         }).enumerate().last().expect("AST map was empty after folding?");
996
997         let entries = entries_less_1 + 1;
998         let vector_length = map.len();
999         debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
1000               entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
1001     }
1002
1003     let map = Map {
1004         forest: forest,
1005         dep_graph: forest.dep_graph.clone(),
1006         map: map,
1007         definitions: definitions,
1008         inlined_bodies: RefCell::new(DefIdMap()),
1009     };
1010
1011     hir_id_validator::check_crate(&map);
1012
1013     map
1014 }
1015
1016 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1017 /// except it avoids creating a dependency on the whole crate.
1018 impl<'hir> print::PpAnn for Map<'hir> {
1019     fn nested(&self, state: &mut print::State, nested: print::Nested) -> io::Result<()> {
1020         match nested {
1021             Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1022             Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1023             Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1024             Nested::Body(id) => state.print_expr(&self.body(id).value),
1025             Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
1026         }
1027     }
1028 }
1029
1030 impl<'a> print::State<'a> {
1031     pub fn print_node(&mut self, node: Node) -> io::Result<()> {
1032         match node {
1033             NodeItem(a)        => self.print_item(&a),
1034             NodeForeignItem(a) => self.print_foreign_item(&a),
1035             NodeTraitItem(a)   => self.print_trait_item(a),
1036             NodeImplItem(a)    => self.print_impl_item(a),
1037             NodeVariant(a)     => self.print_variant(&a),
1038             NodeExpr(a)        => self.print_expr(&a),
1039             NodeStmt(a)        => self.print_stmt(&a),
1040             NodeTy(a)          => self.print_type(&a),
1041             NodeTraitRef(a)    => self.print_trait_ref(&a),
1042             NodeLocal(a)       |
1043             NodePat(a)         => self.print_pat(&a),
1044             NodeBlock(a)       => {
1045                 use syntax::print::pprust::PrintState;
1046
1047                 // containing cbox, will be closed by print-block at }
1048                 self.cbox(print::indent_unit)?;
1049                 // head-ibox, will be closed by print-block after {
1050                 self.ibox(0)?;
1051                 self.print_block(&a)
1052             }
1053             NodeLifetime(a)    => self.print_lifetime(&a),
1054             NodeVisibility(a)  => self.print_visibility(&a),
1055             NodeTyParam(_)     => bug!("cannot print TyParam"),
1056             NodeField(_)       => bug!("cannot print StructField"),
1057             // these cases do not carry enough information in the
1058             // hir_map to reconstruct their full structure for pretty
1059             // printing.
1060             NodeStructCtor(_)  => bug!("cannot print isolated StructCtor"),
1061         }
1062     }
1063 }
1064
1065 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
1066     let id_str = format!(" (id={})", id);
1067     let id_str = if include_id { &id_str[..] } else { "" };
1068
1069     let path_str = || {
1070         // This functionality is used for debugging, try to use TyCtxt to get
1071         // the user-friendly path, otherwise fall back to stringifying DefPath.
1072         ::ty::tls::with_opt(|tcx| {
1073             if let Some(tcx) = tcx {
1074                 tcx.node_path_str(id)
1075             } else if let Some(path) = map.def_path_from_id(id) {
1076                 path.data.into_iter().map(|elem| {
1077                     elem.data.to_string()
1078                 }).collect::<Vec<_>>().join("::")
1079             } else {
1080                 String::from("<missing path>")
1081             }
1082         })
1083     };
1084
1085     match map.find(id) {
1086         Some(NodeItem(item)) => {
1087             let item_str = match item.node {
1088                 ItemExternCrate(..) => "extern crate",
1089                 ItemUse(..) => "use",
1090                 ItemStatic(..) => "static",
1091                 ItemConst(..) => "const",
1092                 ItemFn(..) => "fn",
1093                 ItemMod(..) => "mod",
1094                 ItemForeignMod(..) => "foreign mod",
1095                 ItemGlobalAsm(..) => "global asm",
1096                 ItemTy(..) => "ty",
1097                 ItemEnum(..) => "enum",
1098                 ItemStruct(..) => "struct",
1099                 ItemUnion(..) => "union",
1100                 ItemTrait(..) => "trait",
1101                 ItemImpl(..) => "impl",
1102                 ItemDefaultImpl(..) => "default impl",
1103             };
1104             format!("{} {}{}", item_str, path_str(), id_str)
1105         }
1106         Some(NodeForeignItem(_)) => {
1107             format!("foreign item {}{}", path_str(), id_str)
1108         }
1109         Some(NodeImplItem(ii)) => {
1110             match ii.node {
1111                 ImplItemKind::Const(..) => {
1112                     format!("assoc const {} in {}{}", ii.name, path_str(), id_str)
1113                 }
1114                 ImplItemKind::Method(..) => {
1115                     format!("method {} in {}{}", ii.name, path_str(), id_str)
1116                 }
1117                 ImplItemKind::Type(_) => {
1118                     format!("assoc type {} in {}{}", ii.name, path_str(), id_str)
1119                 }
1120             }
1121         }
1122         Some(NodeTraitItem(ti)) => {
1123             let kind = match ti.node {
1124                 TraitItemKind::Const(..) => "assoc constant",
1125                 TraitItemKind::Method(..) => "trait method",
1126                 TraitItemKind::Type(..) => "assoc type",
1127             };
1128
1129             format!("{} {} in {}{}", kind, ti.name, path_str(), id_str)
1130         }
1131         Some(NodeVariant(ref variant)) => {
1132             format!("variant {} in {}{}",
1133                     variant.node.name,
1134                     path_str(), id_str)
1135         }
1136         Some(NodeField(ref field)) => {
1137             format!("field {} in {}{}",
1138                     field.name,
1139                     path_str(), id_str)
1140         }
1141         Some(NodeExpr(_)) => {
1142             format!("expr {}{}", map.node_to_pretty_string(id), id_str)
1143         }
1144         Some(NodeStmt(_)) => {
1145             format!("stmt {}{}", map.node_to_pretty_string(id), id_str)
1146         }
1147         Some(NodeTy(_)) => {
1148             format!("type {}{}", map.node_to_pretty_string(id), id_str)
1149         }
1150         Some(NodeTraitRef(_)) => {
1151             format!("trait_ref {}{}", map.node_to_pretty_string(id), id_str)
1152         }
1153         Some(NodeLocal(_)) => {
1154             format!("local {}{}", map.node_to_pretty_string(id), id_str)
1155         }
1156         Some(NodePat(_)) => {
1157             format!("pat {}{}", map.node_to_pretty_string(id), id_str)
1158         }
1159         Some(NodeBlock(_)) => {
1160             format!("block {}{}", map.node_to_pretty_string(id), id_str)
1161         }
1162         Some(NodeStructCtor(_)) => {
1163             format!("struct_ctor {}{}", path_str(), id_str)
1164         }
1165         Some(NodeLifetime(_)) => {
1166             format!("lifetime {}{}", map.node_to_pretty_string(id), id_str)
1167         }
1168         Some(NodeTyParam(ref ty_param)) => {
1169             format!("typaram {:?}{}", ty_param, id_str)
1170         }
1171         Some(NodeVisibility(ref vis)) => {
1172             format!("visibility {:?}{}", vis, id_str)
1173         }
1174         None => {
1175             format!("unknown node{}", id_str)
1176         }
1177     }
1178 }