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.
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.
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};
18 use dep_graph::{DepGraph, DepNode};
20 use hir::def_id::{CRATE_DEF_INDEX, DefId, DefIndex, DefIndexAddressSpace};
23 use syntax::ast::{self, Name, NodeId, CRATE_NODE_ID};
24 use syntax::codemap::Spanned;
28 use hir::print::Nested;
29 use util::nodemap::DefIdMap;
31 use arena::TypedArena;
32 use std::cell::RefCell;
41 pub const ITEM_LIKE_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::Low;
42 pub const REGULAR_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::High;
44 #[derive(Copy, Clone, Debug)]
47 NodeForeignItem(&'hir ForeignItem),
48 NodeTraitItem(&'hir TraitItem),
49 NodeImplItem(&'hir ImplItem),
50 NodeVariant(&'hir Variant),
51 NodeField(&'hir StructField),
55 NodeTraitRef(&'hir TraitRef),
58 NodeBlock(&'hir Block),
60 /// NodeStructCtor represents a tuple struct.
61 NodeStructCtor(&'hir VariantData),
63 NodeLifetime(&'hir Lifetime),
64 NodeTyParam(&'hir TyParam),
65 NodeVisibility(&'hir Visibility),
68 /// Represents an entry and its parent NodeID.
69 /// The odd layout is to bring down the total size.
70 #[derive(Copy, Debug)]
72 /// Placeholder for holes in the map.
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),
94 /// Roots for node trees.
98 impl<'hir> Clone for MapEntry<'hir> {
99 fn clone(&self) -> MapEntry<'hir> {
104 impl<'hir> MapEntry<'hir> {
105 fn from_node(p: NodeId, node: Node<'hir>) -> MapEntry<'hir> {
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),
127 fn parent_node(self) -> Option<NodeId> {
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,
148 RootCrate => return None,
152 fn to_node(self) -> Option<Node<'hir>> {
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),
175 fn associated_body(self) -> Option<BodyId> {
177 EntryItem(_, item) => {
180 ItemStatic(.., body) |
181 ItemFn(_, _, _, _, _, body) => Some(body),
186 EntryTraitItem(_, item) => {
188 TraitItemKind::Const(_, Some(body)) |
189 TraitItemKind::Method(_, TraitMethod::Provided(body)) => Some(body),
194 EntryImplItem(_, item) => {
196 ImplItemKind::Const(_, body) |
197 ImplItemKind::Method(_, body) => Some(body),
202 EntryExpr(_, expr) => {
204 ExprClosure(.., body, _) => Some(body),
213 fn is_body_owner(self, node_id: NodeId) -> bool {
214 match self.associated_body() {
215 Some(b) => b.node_id == node_id,
221 /// Stores a crate and any number of inlined items from other crates.
224 pub dep_graph: DepGraph,
225 inlined_bodies: TypedArena<Body>
229 pub fn new(krate: Crate, dep_graph: &DepGraph) -> Forest {
232 dep_graph: dep_graph.clone(),
233 inlined_bodies: TypedArena::new()
237 pub fn krate<'hir>(&'hir self) -> &'hir Crate {
238 self.dep_graph.read(DepNode::Krate);
243 /// Represents a mapping from Node IDs to AST elements and their parent
246 pub struct Map<'hir> {
247 /// The backing storage for all the AST nodes.
248 pub forest: &'hir Forest,
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,
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).
261 /// Also, indexing is pretty quick when you've got a vector and
262 /// plain old integers.
263 map: Vec<MapEntry<'hir>>,
265 definitions: Definitions,
267 /// Bodies inlined from other crates are cached here.
268 inlined_bodies: RefCell<DefIdMap<&'hir Body>>,
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));
283 fn dep_node(&self, id0: NodeId) -> DepNode<DefId> {
285 let mut last_expr = None;
287 let entry = self.map[id.as_usize()];
291 EntryImplItem(..) => {
292 if let Some(last_id) = last_expr {
293 // The body may have a separate dep node
294 if entry.is_body_owner(last_id) {
295 let def_id = self.local_def_id(id);
296 return DepNode::HirBody(def_id);
299 return DepNode::Hir(self.local_def_id(id));
302 EntryVariant(p, v) => {
305 if last_expr.is_some() {
306 if v.node.disr_expr.map(|e| e.node_id) == last_expr {
307 // The enum parent holds both Hir and HirBody nodes.
308 let def_id = self.local_def_id(id);
309 return DepNode::HirBody(def_id);
314 EntryForeignItem(p, _) |
318 EntryTraitRef(p, _) |
322 EntryStructCtor(p, _) |
323 EntryLifetime(p, _) |
325 EntryVisibility(p, _) =>
329 last_expr = Some(id);
334 return DepNode::Hir(DefId::local(CRATE_DEF_INDEX));
338 // Some nodes, notably macro definitions, are not
339 // present in the map for whatever reason, but
340 // they *do* have def-ids. So if we encounter an
341 // empty hole, check for that case.
342 return self.opt_local_def_id(id)
343 .map(|def_id| DepNode::Hir(def_id))
345 bug!("Walking parents from `{}` \
346 led to `NotPresent` at `{}`",
353 pub fn definitions(&self) -> &Definitions {
357 pub fn def_key(&self, def_id: DefId) -> DefKey {
358 assert!(def_id.is_local());
359 self.definitions.def_key(def_id.index)
362 pub fn def_path_from_id(&self, id: NodeId) -> Option<DefPath> {
363 self.opt_local_def_id(id).map(|def_id| {
364 self.def_path(def_id)
368 pub fn def_path(&self, def_id: DefId) -> DefPath {
369 assert!(def_id.is_local());
370 self.definitions.def_path(def_id.index)
373 pub fn def_index_for_def_key(&self, def_key: DefKey) -> Option<DefIndex> {
374 self.definitions.def_index_for_def_key(def_key)
377 pub fn local_def_id(&self, node: NodeId) -> DefId {
378 self.opt_local_def_id(node).unwrap_or_else(|| {
379 bug!("local_def_id: no entry for `{}`, which has a map of `{:?}`",
380 node, self.find_entry(node))
384 pub fn opt_local_def_id(&self, node: NodeId) -> Option<DefId> {
385 self.definitions.opt_local_def_id(node)
388 pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
389 self.definitions.as_local_node_id(def_id)
392 fn entry_count(&self) -> usize {
396 fn find_entry(&self, id: NodeId) -> Option<MapEntry<'hir>> {
397 self.map.get(id.as_usize()).cloned()
400 pub fn krate(&self) -> &'hir Crate {
404 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem {
405 self.read(id.node_id);
407 // NB: intentionally bypass `self.forest.krate()` so that we
408 // do not trigger a read of the whole krate here
409 self.forest.krate.trait_item(id)
412 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem {
413 self.read(id.node_id);
415 // NB: intentionally bypass `self.forest.krate()` so that we
416 // do not trigger a read of the whole krate here
417 self.forest.krate.impl_item(id)
420 pub fn body(&self, id: BodyId) -> &'hir Body {
421 self.read(id.node_id);
423 // NB: intentionally bypass `self.forest.krate()` so that we
424 // do not trigger a read of the whole krate here
425 self.forest.krate.body(id)
428 /// Returns the `NodeId` that corresponds to the definition of
429 /// which this is the body of, i.e. a `fn`, `const` or `static`
430 /// item (possibly associated), or a closure, or the body itself
431 /// for embedded constant expressions (e.g. `N` in `[T; N]`).
432 pub fn body_owner(&self, BodyId { node_id }: BodyId) -> NodeId {
433 let parent = self.get_parent_node(node_id);
434 if self.map[parent.as_usize()].is_body_owner(node_id) {
441 pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
442 self.local_def_id(self.body_owner(id))
445 pub fn ty_param_owner(&self, id: NodeId) -> NodeId {
447 NodeItem(&Item { node: ItemTrait(..), .. }) => id,
448 NodeTyParam(_) => self.get_parent_node(id),
450 bug!("ty_param_owner: {} not a type parameter",
451 self.node_to_string(id))
456 pub fn ty_param_name(&self, id: NodeId) -> Name {
458 NodeItem(&Item { node: ItemTrait(..), .. }) => {
459 keywords::SelfType.name()
461 NodeTyParam(tp) => tp.name,
463 bug!("ty_param_name: {} not a type parameter",
464 self.node_to_string(id))
469 pub fn trait_impls(&self, trait_did: DefId) -> &'hir [NodeId] {
470 self.dep_graph.read(DepNode::TraitImpls(trait_did));
472 // NB: intentionally bypass `self.forest.krate()` so that we
473 // do not trigger a read of the whole krate here
474 self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
477 pub fn trait_default_impl(&self, trait_did: DefId) -> Option<NodeId> {
478 self.dep_graph.read(DepNode::TraitImpls(trait_did));
480 // NB: intentionally bypass `self.forest.krate()` so that we
481 // do not trigger a read of the whole krate here
482 self.forest.krate.trait_default_impl.get(&trait_did).cloned()
485 pub fn trait_is_auto(&self, trait_did: DefId) -> bool {
486 self.trait_default_impl(trait_did).is_some()
489 /// Get the attributes on the krate. This is preferable to
490 /// invoking `krate.attrs` because it registers a tighter
491 /// dep-graph access.
492 pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
493 let crate_root_def_id = DefId::local(CRATE_DEF_INDEX);
494 self.dep_graph.read(DepNode::Hir(crate_root_def_id));
495 &self.forest.krate.attrs
498 /// Retrieve the Node corresponding to `id`, panicking if it cannot
500 pub fn get(&self, id: NodeId) -> Node<'hir> {
501 match self.find(id) {
502 Some(node) => node, // read recorded by `find`
503 None => bug!("couldn't find node id {} in the AST map", id)
507 pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
508 self.as_local_node_id(id).map(|id| self.get(id)) // read recorded by `get`
511 /// Retrieve the Node corresponding to `id`, returning None if
513 pub fn find(&self, id: NodeId) -> Option<Node<'hir>> {
514 let result = self.find_entry(id).and_then(|x| x.to_node());
515 if result.is_some() {
521 /// Similar to get_parent, returns the parent node id or id if there is no
523 /// This function returns the immediate parent in the AST, whereas get_parent
524 /// returns the enclosing item. Note that this might not be the actual parent
525 /// node in the AST - some kinds of nodes are not in the map and these will
526 /// never appear as the parent_node. So you can always walk the parent_nodes
527 /// from a node to the root of the ast (unless you get the same id back here
528 /// that can happen if the id is not in the map itself or is just weird).
529 pub fn get_parent_node(&self, id: NodeId) -> NodeId {
530 self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
533 /// Check if the node is an argument. An argument is a local variable whose
534 /// immediate parent is an item or a closure.
535 pub fn is_argument(&self, id: NodeId) -> bool {
536 match self.find(id) {
537 Some(NodeLocal(_)) => (),
540 match self.find(self.get_parent_node(id)) {
542 Some(NodeTraitItem(_)) |
543 Some(NodeImplItem(_)) => true,
544 Some(NodeExpr(e)) => {
546 ExprClosure(..) => true,
554 /// If there is some error when walking the parents (e.g., a node does not
555 /// have a parent in the map or a node can't be found), then we return the
556 /// last good node id we found. Note that reaching the crate root (id == 0),
557 /// is not an error, since items in the crate module have the crate root as
559 fn walk_parent_nodes<F>(&self, start_id: NodeId, found: F) -> Result<NodeId, NodeId>
560 where F: Fn(&Node<'hir>) -> bool
562 let mut id = start_id;
564 let parent_node = self.get_parent_node(id);
565 if parent_node == CRATE_NODE_ID {
566 return Ok(CRATE_NODE_ID);
568 if parent_node == id {
572 let node = self.find_entry(parent_node);
576 let node = node.unwrap().to_node();
580 return Ok(parent_node);
584 return Err(parent_node);
591 /// Retrieve the NodeId for `id`'s parent item, or `id` itself if no
592 /// parent item is in this map. The "parent item" is the closest parent node
593 /// in the AST which is recorded by the map and is an item, either an item
594 /// in a module, trait, or impl.
595 pub fn get_parent(&self, id: NodeId) -> NodeId {
596 match self.walk_parent_nodes(id, |node| match *node {
600 NodeImplItem(_) => true,
608 /// Returns the NodeId of `id`'s nearest module parent, or `id` itself if no
609 /// module parent is in this map.
610 pub fn get_module_parent(&self, id: NodeId) -> NodeId {
611 match self.walk_parent_nodes(id, |node| match *node {
612 NodeItem(&Item { node: Item_::ItemMod(_), .. }) => true,
620 /// Returns the nearest enclosing scope. A scope is an item or block.
621 /// FIXME it is not clear to me that all items qualify as scopes - statics
622 /// and associated types probably shouldn't, for example. Behaviour in this
623 /// regard should be expected to be highly unstable.
624 pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
625 match self.walk_parent_nodes(id, |node| match *node {
630 NodeBlock(_) => true,
638 pub fn get_parent_did(&self, id: NodeId) -> DefId {
639 self.local_def_id(self.get_parent(id))
642 pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
643 let parent = self.get_parent(id);
644 let abi = match self.find_entry(parent) {
645 Some(EntryItem(_, i)) => {
647 ItemForeignMod(ref nm) => Some(nm.abi),
655 self.read(id); // reveals some of the content of a node
658 None => bug!("expected foreign mod or inlined parent, found {}",
659 self.node_to_string(parent))
663 pub fn expect_item(&self, id: NodeId) -> &'hir Item {
664 match self.find(id) { // read recorded by `find`
665 Some(NodeItem(item)) => item,
666 _ => bug!("expected item, found {}", self.node_to_string(id))
670 pub fn expect_impl_item(&self, id: NodeId) -> &'hir ImplItem {
671 match self.find(id) {
672 Some(NodeImplItem(item)) => item,
673 _ => bug!("expected impl item, found {}", self.node_to_string(id))
677 pub fn expect_trait_item(&self, id: NodeId) -> &'hir TraitItem {
678 match self.find(id) {
679 Some(NodeTraitItem(item)) => item,
680 _ => bug!("expected trait item, found {}", self.node_to_string(id))
684 pub fn expect_variant_data(&self, id: NodeId) -> &'hir VariantData {
685 match self.find(id) {
686 Some(NodeItem(i)) => {
688 ItemStruct(ref struct_def, _) |
689 ItemUnion(ref struct_def, _) => struct_def,
691 bug!("struct ID bound to non-struct {}",
692 self.node_to_string(id));
696 Some(NodeStructCtor(data)) => data,
697 Some(NodeVariant(variant)) => &variant.node.data,
699 bug!("expected struct or variant, found {}",
700 self.node_to_string(id));
705 pub fn expect_variant(&self, id: NodeId) -> &'hir Variant {
706 match self.find(id) {
707 Some(NodeVariant(variant)) => variant,
708 _ => bug!("expected variant, found {}", self.node_to_string(id)),
712 pub fn expect_foreign_item(&self, id: NodeId) -> &'hir ForeignItem {
713 match self.find(id) {
714 Some(NodeForeignItem(item)) => item,
715 _ => bug!("expected foreign item, found {}", self.node_to_string(id))
719 pub fn expect_expr(&self, id: NodeId) -> &'hir Expr {
720 match self.find(id) { // read recorded by find
721 Some(NodeExpr(expr)) => expr,
722 _ => bug!("expected expr, found {}", self.node_to_string(id))
726 pub fn get_inlined_body(&self, def_id: DefId) -> Option<&'hir Body> {
727 self.inlined_bodies.borrow().get(&def_id).map(|&body| {
728 self.dep_graph.read(DepNode::MetaData(def_id));
733 pub fn intern_inlined_body(&self, def_id: DefId, body: Body) -> &'hir Body {
734 let body = self.forest.inlined_bodies.alloc(body);
735 self.inlined_bodies.borrow_mut().insert(def_id, body);
739 /// Returns the name associated with the given NodeId's AST.
740 pub fn name(&self, id: NodeId) -> Name {
742 NodeItem(i) => i.name,
743 NodeForeignItem(i) => i.name,
744 NodeImplItem(ii) => ii.name,
745 NodeTraitItem(ti) => ti.name,
746 NodeVariant(v) => v.node.name,
747 NodeField(f) => f.name,
748 NodeLifetime(lt) => lt.name,
749 NodeTyParam(tp) => tp.name,
750 NodeLocal(&Pat { node: PatKind::Binding(_,_,l,_), .. }) => l.node,
751 NodeStructCtor(_) => self.name(self.get_parent(id)),
752 _ => bug!("no name for {}", self.node_to_string(id))
756 /// Given a node ID, get a list of attributes associated with the AST
757 /// corresponding to the Node ID
758 pub fn attrs(&self, id: NodeId) -> &'hir [ast::Attribute] {
759 self.read(id); // reveals attributes on the node
760 let attrs = match self.find(id) {
761 Some(NodeItem(i)) => Some(&i.attrs[..]),
762 Some(NodeForeignItem(fi)) => Some(&fi.attrs[..]),
763 Some(NodeTraitItem(ref ti)) => Some(&ti.attrs[..]),
764 Some(NodeImplItem(ref ii)) => Some(&ii.attrs[..]),
765 Some(NodeVariant(ref v)) => Some(&v.node.attrs[..]),
766 Some(NodeField(ref f)) => Some(&f.attrs[..]),
767 Some(NodeExpr(ref e)) => Some(&*e.attrs),
768 Some(NodeStmt(ref s)) => Some(s.node.attrs()),
769 // unit/tuple structs take the attributes straight from
770 // the struct definition.
771 Some(NodeStructCtor(_)) => {
772 return self.attrs(self.get_parent(id));
779 /// Returns an iterator that yields the node id's with paths that
780 /// match `parts`. (Requires `parts` is non-empty.)
782 /// For example, if given `parts` equal to `["bar", "quux"]`, then
783 /// the iterator will produce node id's for items with paths
784 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
785 /// any other such items it can find in the map.
786 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
787 -> NodesMatchingSuffix<'a, 'hir> {
788 NodesMatchingSuffix {
790 item_name: parts.last().unwrap(),
791 in_which: &parts[..parts.len() - 1],
796 pub fn span(&self, id: NodeId) -> Span {
797 self.read(id); // reveals span from node
798 match self.find_entry(id) {
799 Some(EntryItem(_, item)) => item.span,
800 Some(EntryForeignItem(_, foreign_item)) => foreign_item.span,
801 Some(EntryTraitItem(_, trait_method)) => trait_method.span,
802 Some(EntryImplItem(_, impl_item)) => impl_item.span,
803 Some(EntryVariant(_, variant)) => variant.span,
804 Some(EntryField(_, field)) => field.span,
805 Some(EntryExpr(_, expr)) => expr.span,
806 Some(EntryStmt(_, stmt)) => stmt.span,
807 Some(EntryTy(_, ty)) => ty.span,
808 Some(EntryTraitRef(_, tr)) => tr.path.span,
809 Some(EntryLocal(_, pat)) => pat.span,
810 Some(EntryPat(_, pat)) => pat.span,
811 Some(EntryBlock(_, block)) => block.span,
812 Some(EntryStructCtor(_, _)) => self.expect_item(self.get_parent(id)).span,
813 Some(EntryLifetime(_, lifetime)) => lifetime.span,
814 Some(EntryTyParam(_, ty_param)) => ty_param.span,
815 Some(EntryVisibility(_, &Visibility::Restricted { ref path, .. })) => path.span,
816 Some(EntryVisibility(_, v)) => bug!("unexpected Visibility {:?}", v),
818 Some(RootCrate) => self.forest.krate.span,
819 Some(NotPresent) | None => {
820 bug!("hir::map::Map::span: id not in map: {:?}", id)
825 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
826 self.as_local_node_id(id).map(|id| self.span(id))
829 pub fn node_to_string(&self, id: NodeId) -> String {
830 node_id_to_string(self, id, true)
833 pub fn node_to_user_string(&self, id: NodeId) -> String {
834 node_id_to_string(self, id, false)
837 pub fn node_to_pretty_string(&self, id: NodeId) -> String {
838 print::to_string(self, |s| s.print_node(self.get(id)))
842 pub struct NodesMatchingSuffix<'a, 'hir:'a> {
844 item_name: &'a String,
845 in_which: &'a [String],
849 impl<'a, 'hir> NodesMatchingSuffix<'a, 'hir> {
850 /// Returns true only if some suffix of the module path for parent
851 /// matches `self.in_which`.
853 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
854 /// returns true if parent's path ends with the suffix
855 /// `x_0::x_1::...::x_k`.
856 fn suffix_matches(&self, parent: NodeId) -> bool {
857 let mut cursor = parent;
858 for part in self.in_which.iter().rev() {
859 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
860 None => return false,
861 Some((node_id, name)) => (node_id, name),
863 if mod_name != &**part {
866 cursor = self.map.get_parent(mod_id);
870 // Finds the first mod in parent chain for `id`, along with
873 // If `id` itself is a mod named `m` with parent `p`, then
874 // returns `Some(id, m, p)`. If `id` has no mod in its parent
875 // chain, then returns `None`.
876 fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
880 Some(NodeItem(item)) if item_is_mod(&item) =>
881 return Some((id, item.name)),
884 let parent = map.get_parent(id);
885 if parent == id { return None }
889 fn item_is_mod(item: &Item) -> bool {
898 // We are looking at some node `n` with a given name and parent
899 // id; do their names match what I am seeking?
900 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
901 name == &**self.item_name && self.suffix_matches(parent_of_n)
905 impl<'a, 'hir> Iterator for NodesMatchingSuffix<'a, 'hir> {
908 fn next(&mut self) -> Option<NodeId> {
911 if idx.as_usize() >= self.map.entry_count() {
914 self.idx = NodeId::from_u32(self.idx.as_u32() + 1);
915 let name = match self.map.find_entry(idx) {
916 Some(EntryItem(_, n)) => n.name(),
917 Some(EntryForeignItem(_, n))=> n.name(),
918 Some(EntryTraitItem(_, n)) => n.name(),
919 Some(EntryImplItem(_, n)) => n.name(),
920 Some(EntryVariant(_, n)) => n.name(),
921 Some(EntryField(_, n)) => n.name(),
924 if self.matches_names(self.map.get_parent(idx), name) {
932 fn name(&self) -> Name;
935 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
937 impl Named for Item { fn name(&self) -> Name { self.name } }
938 impl Named for ForeignItem { fn name(&self) -> Name { self.name } }
939 impl Named for Variant_ { fn name(&self) -> Name { self.name } }
940 impl Named for StructField { fn name(&self) -> Name { self.name } }
941 impl Named for TraitItem { fn name(&self) -> Name { self.name } }
942 impl Named for ImplItem { fn name(&self) -> Name { self.name } }
944 pub fn map_crate<'hir>(forest: &'hir mut Forest,
945 definitions: Definitions)
947 let mut collector = NodeCollector::root(&forest.krate);
948 intravisit::walk_crate(&mut collector, &forest.krate);
949 let map = collector.map;
951 if log_enabled!(::log::LogLevel::Debug) {
952 // This only makes sense for ordered stores; note the
953 // enumerate to count the number of entries.
954 let (entries_less_1, _) = map.iter().filter(|&x| {
959 }).enumerate().last().expect("AST map was empty after folding?");
961 let entries = entries_less_1 + 1;
962 let vector_length = map.len();
963 debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
964 entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
969 dep_graph: forest.dep_graph.clone(),
971 definitions: definitions,
972 inlined_bodies: RefCell::new(DefIdMap()),
975 hir_id_validator::check_crate(&map);
980 /// Identical to the `PpAnn` implementation for `hir::Crate`,
981 /// except it avoids creating a dependency on the whole crate.
982 impl<'hir> print::PpAnn for Map<'hir> {
983 fn nested(&self, state: &mut print::State, nested: print::Nested) -> io::Result<()> {
985 Nested::Item(id) => state.print_item(self.expect_item(id.id)),
986 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
987 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
988 Nested::Body(id) => state.print_expr(&self.body(id).value),
989 Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
994 impl<'a> print::State<'a> {
995 pub fn print_node(&mut self, node: Node) -> io::Result<()> {
997 NodeItem(a) => self.print_item(&a),
998 NodeForeignItem(a) => self.print_foreign_item(&a),
999 NodeTraitItem(a) => self.print_trait_item(a),
1000 NodeImplItem(a) => self.print_impl_item(a),
1001 NodeVariant(a) => self.print_variant(&a),
1002 NodeExpr(a) => self.print_expr(&a),
1003 NodeStmt(a) => self.print_stmt(&a),
1004 NodeTy(a) => self.print_type(&a),
1005 NodeTraitRef(a) => self.print_trait_ref(&a),
1007 NodePat(a) => self.print_pat(&a),
1009 use syntax::print::pprust::PrintState;
1011 // containing cbox, will be closed by print-block at }
1012 self.cbox(print::indent_unit)?;
1013 // head-ibox, will be closed by print-block after {
1015 self.print_block(&a)
1017 NodeLifetime(a) => self.print_lifetime(&a),
1018 NodeVisibility(a) => self.print_visibility(&a),
1019 NodeTyParam(_) => bug!("cannot print TyParam"),
1020 NodeField(_) => bug!("cannot print StructField"),
1021 // these cases do not carry enough information in the
1022 // hir_map to reconstruct their full structure for pretty
1024 NodeStructCtor(_) => bug!("cannot print isolated StructCtor"),
1029 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
1030 let id_str = format!(" (id={})", id);
1031 let id_str = if include_id { &id_str[..] } else { "" };
1034 // This functionality is used for debugging, try to use TyCtxt to get
1035 // the user-friendly path, otherwise fall back to stringifying DefPath.
1036 ::ty::tls::with_opt(|tcx| {
1037 if let Some(tcx) = tcx {
1038 tcx.node_path_str(id)
1039 } else if let Some(path) = map.def_path_from_id(id) {
1040 path.data.into_iter().map(|elem| {
1041 elem.data.to_string()
1042 }).collect::<Vec<_>>().join("::")
1044 String::from("<missing path>")
1049 match map.find(id) {
1050 Some(NodeItem(item)) => {
1051 let item_str = match item.node {
1052 ItemExternCrate(..) => "extern crate",
1053 ItemUse(..) => "use",
1054 ItemStatic(..) => "static",
1055 ItemConst(..) => "const",
1057 ItemMod(..) => "mod",
1058 ItemForeignMod(..) => "foreign mod",
1060 ItemEnum(..) => "enum",
1061 ItemStruct(..) => "struct",
1062 ItemUnion(..) => "union",
1063 ItemTrait(..) => "trait",
1064 ItemImpl(..) => "impl",
1065 ItemDefaultImpl(..) => "default impl",
1067 format!("{} {}{}", item_str, path_str(), id_str)
1069 Some(NodeForeignItem(_)) => {
1070 format!("foreign item {}{}", path_str(), id_str)
1072 Some(NodeImplItem(ii)) => {
1074 ImplItemKind::Const(..) => {
1075 format!("assoc const {} in {}{}", ii.name, path_str(), id_str)
1077 ImplItemKind::Method(..) => {
1078 format!("method {} in {}{}", ii.name, path_str(), id_str)
1080 ImplItemKind::Type(_) => {
1081 format!("assoc type {} in {}{}", ii.name, path_str(), id_str)
1085 Some(NodeTraitItem(ti)) => {
1086 let kind = match ti.node {
1087 TraitItemKind::Const(..) => "assoc constant",
1088 TraitItemKind::Method(..) => "trait method",
1089 TraitItemKind::Type(..) => "assoc type",
1092 format!("{} {} in {}{}", kind, ti.name, path_str(), id_str)
1094 Some(NodeVariant(ref variant)) => {
1095 format!("variant {} in {}{}",
1099 Some(NodeField(ref field)) => {
1100 format!("field {} in {}{}",
1104 Some(NodeExpr(_)) => {
1105 format!("expr {}{}", map.node_to_pretty_string(id), id_str)
1107 Some(NodeStmt(_)) => {
1108 format!("stmt {}{}", map.node_to_pretty_string(id), id_str)
1110 Some(NodeTy(_)) => {
1111 format!("type {}{}", map.node_to_pretty_string(id), id_str)
1113 Some(NodeTraitRef(_)) => {
1114 format!("trait_ref {}{}", map.node_to_pretty_string(id), id_str)
1116 Some(NodeLocal(_)) => {
1117 format!("local {}{}", map.node_to_pretty_string(id), id_str)
1119 Some(NodePat(_)) => {
1120 format!("pat {}{}", map.node_to_pretty_string(id), id_str)
1122 Some(NodeBlock(_)) => {
1123 format!("block {}{}", map.node_to_pretty_string(id), id_str)
1125 Some(NodeStructCtor(_)) => {
1126 format!("struct_ctor {}{}", path_str(), id_str)
1128 Some(NodeLifetime(_)) => {
1129 format!("lifetime {}{}", map.node_to_pretty_string(id), id_str)
1131 Some(NodeTyParam(ref ty_param)) => {
1132 format!("typaram {:?}{}", ty_param, id_str)
1134 Some(NodeVisibility(ref vis)) => {
1135 format!("visibility {:?}{}", vis, id_str)
1138 format!("unknown node{}", id_str)