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 use self::def_collector::DefCollector;
15 pub use self::definitions::{Definitions, DefKey, DefPath, DefPathData,
16 DisambiguatedDefPathData, InlinedRootPath};
18 use dep_graph::{DepGraph, DepNode};
20 use middle::cstore::InlinedItem;
21 use middle::cstore::InlinedItem as II;
22 use hir::def_id::{CRATE_DEF_INDEX, DefId, DefIndex};
25 use syntax::ast::{self, Name, NodeId, DUMMY_NODE_ID, };
26 use syntax::codemap::Spanned;
30 use hir::fold::Folder;
31 use hir::print as pprust;
33 use arena::TypedArena;
34 use std::cell::RefCell;
44 #[derive(Copy, Clone, Debug)]
47 NodeForeignItem(&'ast ForeignItem),
48 NodeTraitItem(&'ast TraitItem),
49 NodeImplItem(&'ast ImplItem),
50 NodeVariant(&'ast Variant),
55 NodeBlock(&'ast Block),
57 /// NodeStructCtor represents a tuple struct.
58 NodeStructCtor(&'ast VariantData),
60 NodeLifetime(&'ast Lifetime),
61 NodeTyParam(&'ast TyParam)
64 /// Represents an entry and its parent NodeID.
65 /// The odd layout is to bring down the total size.
66 #[derive(Copy, Debug)]
67 pub enum MapEntry<'ast> {
68 /// Placeholder for holes in the map.
71 /// All the node types, with a parent ID.
72 EntryItem(NodeId, &'ast Item),
73 EntryForeignItem(NodeId, &'ast ForeignItem),
74 EntryTraitItem(NodeId, &'ast TraitItem),
75 EntryImplItem(NodeId, &'ast ImplItem),
76 EntryVariant(NodeId, &'ast Variant),
77 EntryExpr(NodeId, &'ast Expr),
78 EntryStmt(NodeId, &'ast Stmt),
79 EntryLocal(NodeId, &'ast Pat),
80 EntryPat(NodeId, &'ast Pat),
81 EntryBlock(NodeId, &'ast Block),
82 EntryStructCtor(NodeId, &'ast VariantData),
83 EntryLifetime(NodeId, &'ast Lifetime),
84 EntryTyParam(NodeId, &'ast TyParam),
86 /// Roots for node trees.
88 RootInlinedParent(&'ast InlinedItem)
91 impl<'ast> Clone for MapEntry<'ast> {
92 fn clone(&self) -> MapEntry<'ast> {
97 impl<'ast> MapEntry<'ast> {
98 fn from_node(p: NodeId, node: Node<'ast>) -> MapEntry<'ast> {
100 NodeItem(n) => EntryItem(p, n),
101 NodeForeignItem(n) => EntryForeignItem(p, n),
102 NodeTraitItem(n) => EntryTraitItem(p, n),
103 NodeImplItem(n) => EntryImplItem(p, n),
104 NodeVariant(n) => EntryVariant(p, n),
105 NodeExpr(n) => EntryExpr(p, n),
106 NodeStmt(n) => EntryStmt(p, n),
107 NodeLocal(n) => EntryLocal(p, n),
108 NodePat(n) => EntryPat(p, n),
109 NodeBlock(n) => EntryBlock(p, n),
110 NodeStructCtor(n) => EntryStructCtor(p, n),
111 NodeLifetime(n) => EntryLifetime(p, n),
112 NodeTyParam(n) => EntryTyParam(p, n),
116 fn parent_node(self) -> Option<NodeId> {
118 EntryItem(id, _) => id,
119 EntryForeignItem(id, _) => id,
120 EntryTraitItem(id, _) => id,
121 EntryImplItem(id, _) => id,
122 EntryVariant(id, _) => id,
123 EntryExpr(id, _) => id,
124 EntryStmt(id, _) => id,
125 EntryLocal(id, _) => id,
126 EntryPat(id, _) => id,
127 EntryBlock(id, _) => id,
128 EntryStructCtor(id, _) => id,
129 EntryLifetime(id, _) => id,
130 EntryTyParam(id, _) => id,
134 RootInlinedParent(_) => return None,
138 fn to_node(self) -> Option<Node<'ast>> {
140 EntryItem(_, n) => NodeItem(n),
141 EntryForeignItem(_, n) => NodeForeignItem(n),
142 EntryTraitItem(_, n) => NodeTraitItem(n),
143 EntryImplItem(_, n) => NodeImplItem(n),
144 EntryVariant(_, n) => NodeVariant(n),
145 EntryExpr(_, n) => NodeExpr(n),
146 EntryStmt(_, n) => NodeStmt(n),
147 EntryLocal(_, n) => NodeLocal(n),
148 EntryPat(_, n) => NodePat(n),
149 EntryBlock(_, n) => NodeBlock(n),
150 EntryStructCtor(_, n) => NodeStructCtor(n),
151 EntryLifetime(_, n) => NodeLifetime(n),
152 EntryTyParam(_, n) => NodeTyParam(n),
158 /// Stores a crate and any number of inlined items from other crates.
161 pub dep_graph: DepGraph,
162 inlined_items: TypedArena<InlinedItem>
166 pub fn new(krate: Crate, dep_graph: &DepGraph) -> Forest {
169 dep_graph: dep_graph.clone(),
170 inlined_items: TypedArena::new()
174 pub fn krate<'ast>(&'ast self) -> &'ast Crate {
175 self.dep_graph.read(DepNode::Krate);
180 /// Represents a mapping from Node IDs to AST elements and their parent
183 pub struct Map<'ast> {
184 /// The backing storage for all the AST nodes.
185 pub forest: &'ast Forest,
187 /// Same as the dep_graph in forest, just available with one fewer
188 /// deref. This is a gratuitious micro-optimization.
189 pub dep_graph: DepGraph,
191 /// NodeIds are sequential integers from 0, so we can be
192 /// super-compact by storing them in a vector. Not everything with
193 /// a NodeId is in the map, but empirically the occupancy is about
194 /// 75-80%, so there's not too much overhead (certainly less than
195 /// a hashmap, since they (at the time of writing) have a maximum
196 /// of 75% occupancy).
198 /// Also, indexing is pretty quick when you've got a vector and
199 /// plain old integers.
200 map: RefCell<Vec<MapEntry<'ast>>>,
202 definitions: RefCell<Definitions>,
204 /// All NodeIds that are numerically greater or equal to this value come
205 /// from inlined items.
206 local_node_id_watermark: NodeId,
209 impl<'ast> Map<'ast> {
210 /// Registers a read in the dependency graph of the AST node with
211 /// the given `id`. This needs to be called each time a public
212 /// function returns the HIR for a node -- in other words, when it
213 /// "reveals" the content of a node to the caller (who might not
214 /// otherwise have had access to those contents, and hence needs a
215 /// read recorded). If the function just returns a DefId or
216 /// NodeId, no actual content was returned, so no read is needed.
217 fn read(&self, id: NodeId) {
218 self.dep_graph.read(self.dep_node(id));
221 fn dep_node(&self, id0: NodeId) -> DepNode<DefId> {
222 let map = self.map.borrow();
225 match map[id as usize] {
226 EntryItem(_, item) => {
227 let def_id = self.local_def_id(item.id);
230 // You would expect that `item.id == id`, but this
231 // is not always the case. In particular, for a
232 // ViewPath item like `use self::{mem, foo}`, we
233 // map the ids for `mem` and `foo` to the
234 // enclosing view path item. This seems mega super
235 // ultra wrong, but then who am I to judge?
237 return DepNode::Hir(def_id);
240 EntryForeignItem(p, _) |
241 EntryTraitItem(p, _) |
242 EntryImplItem(p, _) |
249 EntryStructCtor(p, _) |
250 EntryLifetime(p, _) |
251 EntryTyParam(p, _) =>
255 RootInlinedParent(_) =>
256 // FIXME(#32015) clarify story about cross-crate dep tracking
257 return DepNode::Krate,
260 // Some nodes, notably struct fields, are not
261 // present in the map for whatever reason, but
262 // they *do* have def-ids. So if we encounter an
263 // empty hole, check for that case.
264 return self.opt_local_def_id(id)
265 .map(|def_id| DepNode::Hir(def_id))
267 bug!("Walking parents from `{}` \
268 led to `NotPresent` at `{}`",
275 pub fn num_local_def_ids(&self) -> usize {
276 self.definitions.borrow().len()
279 pub fn def_key(&self, def_id: DefId) -> DefKey {
280 assert!(def_id.is_local());
281 self.definitions.borrow().def_key(def_id.index)
284 pub fn def_path_from_id(&self, id: NodeId) -> Option<DefPath> {
285 self.opt_local_def_id(id).map(|def_id| {
286 self.def_path(def_id)
290 pub fn def_path(&self, def_id: DefId) -> DefPath {
291 assert!(def_id.is_local());
292 self.definitions.borrow().def_path(def_id.index)
295 pub fn def_index_for_def_key(&self, def_key: DefKey) -> Option<DefIndex> {
296 self.definitions.borrow().def_index_for_def_key(def_key)
299 pub fn local_def_id(&self, node: NodeId) -> DefId {
300 self.opt_local_def_id(node).unwrap_or_else(|| {
301 bug!("local_def_id: no entry for `{}`, which has a map of `{:?}`",
302 node, self.find_entry(node))
306 pub fn opt_local_def_id(&self, node: NodeId) -> Option<DefId> {
307 self.definitions.borrow().opt_local_def_id(node)
310 pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
311 self.definitions.borrow().as_local_node_id(def_id)
314 fn entry_count(&self) -> usize {
315 self.map.borrow().len()
318 fn find_entry(&self, id: NodeId) -> Option<MapEntry<'ast>> {
319 self.map.borrow().get(id as usize).cloned()
322 pub fn krate(&self) -> &'ast Crate {
326 /// Get the attributes on the krate. This is preferable to
327 /// invoking `krate.attrs` because it registers a tighter
328 /// dep-graph access.
329 pub fn krate_attrs(&self) -> &'ast [ast::Attribute] {
330 let crate_root_def_id = DefId::local(CRATE_DEF_INDEX);
331 self.dep_graph.read(DepNode::Hir(crate_root_def_id));
332 &self.forest.krate.attrs
335 /// Retrieve the Node corresponding to `id`, panicking if it cannot
337 pub fn get(&self, id: NodeId) -> Node<'ast> {
338 match self.find(id) {
339 Some(node) => node, // read recorded by `find`
340 None => bug!("couldn't find node id {} in the AST map", id)
344 pub fn get_if_local(&self, id: DefId) -> Option<Node<'ast>> {
345 self.as_local_node_id(id).map(|id| self.get(id)) // read recorded by `get`
348 /// Retrieve the Node corresponding to `id`, returning None if
350 pub fn find(&self, id: NodeId) -> Option<Node<'ast>> {
351 let result = self.find_entry(id).and_then(|x| x.to_node());
352 if result.is_some() {
358 /// Similar to get_parent, returns the parent node id or id if there is no
360 /// This function returns the immediate parent in the AST, whereas get_parent
361 /// returns the enclosing item. Note that this might not be the actual parent
362 /// node in the AST - some kinds of nodes are not in the map and these will
363 /// never appear as the parent_node. So you can always walk the parent_nodes
364 /// from a node to the root of the ast (unless you get the same id back here
365 /// that can happen if the id is not in the map itself or is just weird).
366 pub fn get_parent_node(&self, id: NodeId) -> NodeId {
367 self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
370 /// Check if the node is an argument. An argument is a local variable whose
371 /// immediate parent is an item or a closure.
372 pub fn is_argument(&self, id: NodeId) -> bool {
373 match self.find(id) {
374 Some(NodeLocal(_)) => (),
377 match self.find(self.get_parent_node(id)) {
379 Some(NodeTraitItem(_)) |
380 Some(NodeImplItem(_)) => true,
381 Some(NodeExpr(e)) => {
383 ExprClosure(..) => true,
391 /// If there is some error when walking the parents (e.g., a node does not
392 /// have a parent in the map or a node can't be found), then we return the
393 /// last good node id we found. Note that reaching the crate root (id == 0),
394 /// is not an error, since items in the crate module have the crate root as
396 fn walk_parent_nodes<F>(&self, start_id: NodeId, found: F) -> Result<NodeId, NodeId>
397 where F: Fn(&Node<'ast>) -> bool
399 let mut id = start_id;
401 let parent_node = self.get_parent_node(id);
402 if parent_node == 0 {
405 if parent_node == id {
409 let node = self.find_entry(parent_node);
413 let node = node.unwrap().to_node();
417 return Ok(parent_node);
421 return Err(parent_node);
428 /// Retrieve the NodeId for `id`'s parent item, or `id` itself if no
429 /// parent item is in this map. The "parent item" is the closest parent node
430 /// in the AST which is recorded by the map and is an item, either an item
431 /// in a module, trait, or impl.
432 pub fn get_parent(&self, id: NodeId) -> NodeId {
433 match self.walk_parent_nodes(id, |node| match *node {
437 NodeImplItem(_) => true,
445 /// Returns the NodeId of `id`'s nearest module parent, or `id` itself if no
446 /// module parent is in this map.
447 pub fn get_module_parent(&self, id: NodeId) -> NodeId {
448 match self.walk_parent_nodes(id, |node| match *node {
449 NodeItem(&Item { node: Item_::ItemMod(_), .. }) => true,
457 /// Returns the nearest enclosing scope. A scope is an item or block.
458 /// FIXME it is not clear to me that all items qualify as scopes - statics
459 /// and associated types probably shouldn't, for example. Behaviour in this
460 /// regard should be expected to be highly unstable.
461 pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
462 match self.walk_parent_nodes(id, |node| match *node {
467 NodeBlock(_) => true,
475 pub fn get_parent_did(&self, id: NodeId) -> DefId {
476 let parent = self.get_parent(id);
477 match self.find_entry(parent) {
478 Some(RootInlinedParent(&II::TraitItem(did, _))) |
479 Some(RootInlinedParent(&II::ImplItem(did, _))) => did,
480 _ => self.local_def_id(parent)
484 pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
485 let parent = self.get_parent(id);
486 let abi = match self.find_entry(parent) {
487 Some(EntryItem(_, i)) => {
489 ItemForeignMod(ref nm) => Some(nm.abi),
493 /// Wrong but OK, because the only inlined foreign items are intrinsics.
494 Some(RootInlinedParent(_)) => Some(Abi::RustIntrinsic),
499 self.read(id); // reveals some of the content of a node
502 None => bug!("expected foreign mod or inlined parent, found {}",
503 self.node_to_string(parent))
507 pub fn expect_item(&self, id: NodeId) -> &'ast Item {
508 match self.find(id) { // read recorded by `find`
509 Some(NodeItem(item)) => item,
510 _ => bug!("expected item, found {}", self.node_to_string(id))
514 pub fn expect_trait_item(&self, id: NodeId) -> &'ast TraitItem {
515 match self.find(id) {
516 Some(NodeTraitItem(item)) => item,
517 _ => bug!("expected trait item, found {}", self.node_to_string(id))
521 pub fn expect_struct(&self, id: NodeId) -> &'ast VariantData {
522 match self.find(id) {
523 Some(NodeItem(i)) => {
525 ItemStruct(ref struct_def, _) => struct_def,
526 _ => bug!("struct ID bound to non-struct")
529 Some(NodeVariant(variant)) => {
530 if variant.node.data.is_struct() {
533 bug!("struct ID bound to enum variant that isn't struct-like")
536 _ => bug!("expected struct, found {}", self.node_to_string(id)),
540 pub fn expect_variant(&self, id: NodeId) -> &'ast Variant {
541 match self.find(id) {
542 Some(NodeVariant(variant)) => variant,
543 _ => bug!("expected variant, found {}", self.node_to_string(id)),
547 pub fn expect_foreign_item(&self, id: NodeId) -> &'ast ForeignItem {
548 match self.find(id) {
549 Some(NodeForeignItem(item)) => item,
550 _ => bug!("expected foreign item, found {}", self.node_to_string(id))
554 pub fn expect_expr(&self, id: NodeId) -> &'ast Expr {
555 match self.find(id) { // read recorded by find
556 Some(NodeExpr(expr)) => expr,
557 _ => bug!("expected expr, found {}", self.node_to_string(id))
561 pub fn expect_inlined_item(&self, id: NodeId) -> &'ast InlinedItem {
562 match self.find_entry(id) {
563 Some(RootInlinedParent(inlined_item)) => inlined_item,
564 _ => bug!("expected inlined item, found {}", self.node_to_string(id)),
568 /// Returns the name associated with the given NodeId's AST.
569 pub fn name(&self, id: NodeId) -> Name {
571 NodeItem(i) => i.name,
572 NodeForeignItem(i) => i.name,
573 NodeImplItem(ii) => ii.name,
574 NodeTraitItem(ti) => ti.name,
575 NodeVariant(v) => v.node.name,
576 NodeLifetime(lt) => lt.name,
577 NodeTyParam(tp) => tp.name,
578 NodeLocal(&Pat { node: PatKind::Binding(_,l,_), .. }) => l.node,
579 NodeStructCtor(_) => self.name(self.get_parent(id)),
580 _ => bug!("no name for {}", self.node_to_string(id))
584 /// Given a node ID, get a list of attributes associated with the AST
585 /// corresponding to the Node ID
586 pub fn attrs(&self, id: NodeId) -> &'ast [ast::Attribute] {
587 self.read(id); // reveals attributes on the node
588 let attrs = match self.find(id) {
589 Some(NodeItem(i)) => Some(&i.attrs[..]),
590 Some(NodeForeignItem(fi)) => Some(&fi.attrs[..]),
591 Some(NodeTraitItem(ref ti)) => Some(&ti.attrs[..]),
592 Some(NodeImplItem(ref ii)) => Some(&ii.attrs[..]),
593 Some(NodeVariant(ref v)) => Some(&v.node.attrs[..]),
594 Some(NodeExpr(ref e)) => Some(&*e.attrs),
595 Some(NodeStmt(ref s)) => Some(s.node.attrs()),
596 // unit/tuple structs take the attributes straight from
597 // the struct definition.
598 Some(NodeStructCtor(_)) => {
599 return self.attrs(self.get_parent(id));
606 /// Returns an iterator that yields the node id's with paths that
607 /// match `parts`. (Requires `parts` is non-empty.)
609 /// For example, if given `parts` equal to `["bar", "quux"]`, then
610 /// the iterator will produce node id's for items with paths
611 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
612 /// any other such items it can find in the map.
613 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
614 -> NodesMatchingSuffix<'a, 'ast> {
615 NodesMatchingSuffix {
617 item_name: parts.last().unwrap(),
618 in_which: &parts[..parts.len() - 1],
623 pub fn opt_span(&self, id: NodeId) -> Option<Span> {
624 let sp = match self.find(id) {
625 Some(NodeItem(item)) => item.span,
626 Some(NodeForeignItem(foreign_item)) => foreign_item.span,
627 Some(NodeTraitItem(trait_method)) => trait_method.span,
628 Some(NodeImplItem(ref impl_item)) => impl_item.span,
629 Some(NodeVariant(variant)) => variant.span,
630 Some(NodeExpr(expr)) => expr.span,
631 Some(NodeStmt(stmt)) => stmt.span,
632 Some(NodeLocal(pat)) => pat.span,
633 Some(NodePat(pat)) => pat.span,
634 Some(NodeBlock(block)) => block.span,
635 Some(NodeStructCtor(_)) => self.expect_item(self.get_parent(id)).span,
636 Some(NodeTyParam(ty_param)) => ty_param.span,
642 pub fn span(&self, id: NodeId) -> Span {
643 self.read(id); // reveals span from node
645 .unwrap_or_else(|| bug!("AstMap.span: could not find span for id {:?}", id))
648 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
649 self.as_local_node_id(id).map(|id| self.span(id))
652 pub fn def_id_span(&self, def_id: DefId, fallback: Span) -> Span {
653 if let Some(node_id) = self.as_local_node_id(def_id) {
654 self.opt_span(node_id).unwrap_or(fallback)
660 pub fn node_to_string(&self, id: NodeId) -> String {
661 node_id_to_string(self, id, true)
664 pub fn node_to_user_string(&self, id: NodeId) -> String {
665 node_id_to_string(self, id, false)
668 pub fn is_inlined(&self, id: NodeId) -> bool {
669 id >= self.local_node_id_watermark
673 pub struct NodesMatchingSuffix<'a, 'ast:'a> {
675 item_name: &'a String,
676 in_which: &'a [String],
680 impl<'a, 'ast> NodesMatchingSuffix<'a, 'ast> {
681 /// Returns true only if some suffix of the module path for parent
682 /// matches `self.in_which`.
684 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
685 /// returns true if parent's path ends with the suffix
686 /// `x_0::x_1::...::x_k`.
687 fn suffix_matches(&self, parent: NodeId) -> bool {
688 let mut cursor = parent;
689 for part in self.in_which.iter().rev() {
690 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
691 None => return false,
692 Some((node_id, name)) => (node_id, name),
694 if &part[..] != mod_name.as_str() {
697 cursor = self.map.get_parent(mod_id);
701 // Finds the first mod in parent chain for `id`, along with
704 // If `id` itself is a mod named `m` with parent `p`, then
705 // returns `Some(id, m, p)`. If `id` has no mod in its parent
706 // chain, then returns `None`.
707 fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
711 Some(NodeItem(item)) if item_is_mod(&item) =>
712 return Some((id, item.name)),
715 let parent = map.get_parent(id);
716 if parent == id { return None }
720 fn item_is_mod(item: &Item) -> bool {
729 // We are looking at some node `n` with a given name and parent
730 // id; do their names match what I am seeking?
731 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
732 name.as_str() == &self.item_name[..] &&
733 self.suffix_matches(parent_of_n)
737 impl<'a, 'ast> Iterator for NodesMatchingSuffix<'a, 'ast> {
740 fn next(&mut self) -> Option<NodeId> {
743 if idx as usize >= self.map.entry_count() {
747 let name = match self.map.find_entry(idx) {
748 Some(EntryItem(_, n)) => n.name(),
749 Some(EntryForeignItem(_, n))=> n.name(),
750 Some(EntryTraitItem(_, n)) => n.name(),
751 Some(EntryImplItem(_, n)) => n.name(),
752 Some(EntryVariant(_, n)) => n.name(),
755 if self.matches_names(self.map.get_parent(idx), name) {
763 fn name(&self) -> Name;
766 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
768 impl Named for Item { fn name(&self) -> Name { self.name } }
769 impl Named for ForeignItem { fn name(&self) -> Name { self.name } }
770 impl Named for Variant_ { fn name(&self) -> Name { self.name } }
771 impl Named for TraitItem { fn name(&self) -> Name { self.name } }
772 impl Named for ImplItem { fn name(&self) -> Name { self.name } }
775 fn new_id(&self, id: NodeId) -> NodeId {
778 fn new_def_id(&self, def_id: DefId) -> DefId {
781 fn new_span(&self, span: Span) -> Span {
786 /// A Folder that updates IDs and Span's according to fold_ops.
787 pub struct IdAndSpanUpdater<F> {
789 min_id_assigned: NodeId,
790 max_id_assigned: NodeId,
793 impl<F: FoldOps> IdAndSpanUpdater<F> {
794 pub fn new(fold_ops: F) -> IdAndSpanUpdater<F> {
797 min_id_assigned: ::std::u32::MAX,
798 max_id_assigned: ::std::u32::MIN,
802 pub fn id_range(&self) -> intravisit::IdRange {
803 intravisit::IdRange {
804 min: self.min_id_assigned,
805 max: self.max_id_assigned + 1,
810 impl<F: FoldOps> Folder for IdAndSpanUpdater<F> {
811 fn new_id(&mut self, id: NodeId) -> NodeId {
812 let id = self.fold_ops.new_id(id);
814 self.min_id_assigned = cmp::min(self.min_id_assigned, id);
815 self.max_id_assigned = cmp::max(self.max_id_assigned, id);
820 fn new_span(&mut self, span: Span) -> Span {
821 self.fold_ops.new_span(span)
825 pub fn map_crate<'ast>(forest: &'ast mut Forest,
826 definitions: Definitions)
828 let mut collector = NodeCollector::root(&forest.krate);
829 intravisit::walk_crate(&mut collector, &forest.krate);
830 let map = collector.map;
832 if log_enabled!(::log::DEBUG) {
833 // This only makes sense for ordered stores; note the
834 // enumerate to count the number of entries.
835 let (entries_less_1, _) = map.iter().filter(|&x| {
840 }).enumerate().last().expect("AST map was empty after folding?");
842 let entries = entries_less_1 + 1;
843 let vector_length = map.len();
844 debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
845 entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
848 let local_node_id_watermark = map.len() as NodeId;
852 dep_graph: forest.dep_graph.clone(),
853 map: RefCell::new(map),
854 definitions: RefCell::new(definitions),
855 local_node_id_watermark: local_node_id_watermark
859 /// Used for items loaded from external crate that are being inlined into this
861 pub fn map_decoded_item<'ast, F: FoldOps>(map: &Map<'ast>,
862 parent_def_path: DefPath,
863 parent_def_id: DefId,
866 -> &'ast InlinedItem {
867 let mut fld = IdAndSpanUpdater::new(fold_ops);
869 II::Item(i) => II::Item(i.map(|i| fld.fold_item(i))),
870 II::TraitItem(d, ti) => {
871 II::TraitItem(fld.fold_ops.new_def_id(d),
872 ti.map(|ti| fld.fold_trait_item(ti)))
874 II::ImplItem(d, ii) => {
875 II::ImplItem(fld.fold_ops.new_def_id(d),
876 ii.map(|ii| fld.fold_impl_item(ii)))
878 II::Foreign(i) => II::Foreign(i.map(|i| fld.fold_foreign_item(i)))
881 let ii = map.forest.inlined_items.alloc(ii);
882 let ii_parent_id = fld.new_id(DUMMY_NODE_ID);
884 // Assert that the ii_parent_id is the last NodeId in our reserved range
885 assert!(ii_parent_id == fld.max_id_assigned);
886 // Assert that we did not violate the invariant that all inlined HIR items
887 // have NodeIds greater than or equal to `local_node_id_watermark`
888 assert!(fld.min_id_assigned >= map.local_node_id_watermark);
890 let defs = &mut *map.definitions.borrow_mut();
891 let mut def_collector = DefCollector::extend(ii_parent_id,
892 parent_def_path.clone(),
895 def_collector.walk_item(ii, map.krate());
897 let mut collector = NodeCollector::extend(map.krate(),
902 mem::replace(&mut *map.map.borrow_mut(), vec![]));
903 ii.visit(&mut collector);
904 *map.map.borrow_mut() = collector.map;
909 pub trait NodePrinter {
910 fn print_node(&mut self, node: &Node) -> io::Result<()>;
913 impl<'a> NodePrinter for pprust::State<'a> {
914 fn print_node(&mut self, node: &Node) -> io::Result<()> {
916 NodeItem(a) => self.print_item(&a),
917 NodeForeignItem(a) => self.print_foreign_item(&a),
918 NodeTraitItem(a) => self.print_trait_item(a),
919 NodeImplItem(a) => self.print_impl_item(a),
920 NodeVariant(a) => self.print_variant(&a),
921 NodeExpr(a) => self.print_expr(&a),
922 NodeStmt(a) => self.print_stmt(&a),
923 NodePat(a) => self.print_pat(&a),
924 NodeBlock(a) => self.print_block(&a),
925 NodeLifetime(a) => self.print_lifetime(&a),
926 NodeTyParam(_) => bug!("cannot print TyParam"),
927 // these cases do not carry enough information in the
928 // ast_map to reconstruct their full structure for pretty
930 NodeLocal(_) => bug!("cannot print isolated Local"),
931 NodeStructCtor(_) => bug!("cannot print isolated StructCtor"),
936 fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
937 let id_str = format!(" (id={})", id);
938 let id_str = if include_id { &id_str[..] } else { "" };
941 // This functionality is used for debugging, try to use TyCtxt to get
942 // the user-friendly path, otherwise fall back to stringifying DefPath.
943 ::ty::tls::with_opt(|tcx| {
944 if let Some(tcx) = tcx {
945 tcx.node_path_str(id)
946 } else if let Some(path) = map.def_path_from_id(id) {
947 path.data.into_iter().map(|elem| {
948 elem.data.to_string()
949 }).collect::<Vec<_>>().join("::")
951 String::from("<missing path>")
957 Some(NodeItem(item)) => {
958 let item_str = match item.node {
959 ItemExternCrate(..) => "extern crate",
960 ItemUse(..) => "use",
961 ItemStatic(..) => "static",
962 ItemConst(..) => "const",
964 ItemMod(..) => "mod",
965 ItemForeignMod(..) => "foreign mod",
967 ItemEnum(..) => "enum",
968 ItemStruct(..) => "struct",
969 ItemTrait(..) => "trait",
970 ItemImpl(..) => "impl",
971 ItemDefaultImpl(..) => "default impl",
973 format!("{} {}{}", item_str, path_str(), id_str)
975 Some(NodeForeignItem(_)) => {
976 format!("foreign item {}{}", path_str(), id_str)
978 Some(NodeImplItem(ii)) => {
980 ImplItemKind::Const(..) => {
981 format!("assoc const {} in {}{}", ii.name, path_str(), id_str)
983 ImplItemKind::Method(..) => {
984 format!("method {} in {}{}", ii.name, path_str(), id_str)
986 ImplItemKind::Type(_) => {
987 format!("assoc type {} in {}{}", ii.name, path_str(), id_str)
991 Some(NodeTraitItem(ti)) => {
992 let kind = match ti.node {
993 ConstTraitItem(..) => "assoc constant",
994 MethodTraitItem(..) => "trait method",
995 TypeTraitItem(..) => "assoc type",
998 format!("{} {} in {}{}", kind, ti.name, path_str(), id_str)
1000 Some(NodeVariant(ref variant)) => {
1001 format!("variant {} in {}{}",
1005 Some(NodeExpr(ref expr)) => {
1006 format!("expr {}{}", pprust::expr_to_string(&expr), id_str)
1008 Some(NodeStmt(ref stmt)) => {
1009 format!("stmt {}{}", pprust::stmt_to_string(&stmt), id_str)
1011 Some(NodeLocal(ref pat)) => {
1012 format!("local {}{}", pprust::pat_to_string(&pat), id_str)
1014 Some(NodePat(ref pat)) => {
1015 format!("pat {}{}", pprust::pat_to_string(&pat), id_str)
1017 Some(NodeBlock(ref block)) => {
1018 format!("block {}{}", pprust::block_to_string(&block), id_str)
1020 Some(NodeStructCtor(_)) => {
1021 format!("struct_ctor {}{}", path_str(), id_str)
1023 Some(NodeLifetime(ref l)) => {
1024 format!("lifetime {}{}",
1025 pprust::lifetime_to_string(&l), id_str)
1027 Some(NodeTyParam(ref ty_param)) => {
1028 format!("typaram {:?}{}", ty_param, id_str)
1031 format!("unknown node{}", id_str)