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 use self::collector::NodeCollector;
12 pub use self::def_collector::{DefCollector, MacroInvocationData};
13 pub use self::definitions::{Definitions, DefKey, DefPath, DefPathData,
14 DisambiguatedDefPathData, DefPathHash};
16 use dep_graph::{DepGraph, DepNode, DepKind, DepNodeIndex};
18 use hir::def_id::{CRATE_DEF_INDEX, DefId, LocalDefId, DefIndexAddressSpace};
20 use middle::cstore::CrateStore;
22 use rustc_target::spec::abi::Abi;
23 use rustc_data_structures::svh::Svh;
24 use syntax::ast::{self, Name, NodeId, CRATE_NODE_ID};
25 use syntax::source_map::Spanned;
26 use syntax::ext::base::MacroKind;
27 use syntax_pos::{Span, DUMMY_SP};
30 use hir::print::Nested;
31 use util::nodemap::FxHashMap;
34 use std::result::Result::Err;
43 pub const ITEM_LIKE_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::Low;
44 pub const REGULAR_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::High;
46 /// Represents an entry and its parent NodeId.
47 #[derive(Copy, Clone, Debug)]
48 pub struct Entry<'hir> {
50 dep_node: DepNodeIndex,
54 impl<'hir> Entry<'hir> {
55 fn parent_node(self) -> Option<NodeId> {
57 Node::Crate | Node::MacroDef(_) => None,
58 _ => Some(self.parent),
62 fn fn_decl(&self) -> Option<&FnDecl> {
64 Node::Item(ref item) => {
66 ItemKind::Fn(ref fn_decl, _, _, _) => Some(&fn_decl),
71 Node::TraitItem(ref item) => {
73 TraitItemKind::Method(ref method_sig, _) => Some(&method_sig.decl),
78 Node::ImplItem(ref item) => {
80 ImplItemKind::Method(ref method_sig, _) => Some(&method_sig.decl),
85 Node::Expr(ref expr) => {
87 ExprKind::Closure(_, ref fn_decl, ..) => Some(&fn_decl),
96 fn associated_body(self) -> Option<BodyId> {
100 ItemKind::Const(_, body) |
101 ItemKind::Static(.., body) |
102 ItemKind::Fn(_, _, _, body) => Some(body),
107 Node::TraitItem(item) => {
109 TraitItemKind::Const(_, Some(body)) |
110 TraitItemKind::Method(_, TraitMethod::Provided(body)) => Some(body),
115 Node::ImplItem(item) => {
117 ImplItemKind::Const(_, body) |
118 ImplItemKind::Method(_, body) => Some(body),
123 Node::AnonConst(constant) => Some(constant.body),
125 Node::Expr(expr) => {
127 ExprKind::Closure(.., body, _, _) => Some(body),
136 fn is_body_owner(self, node_id: NodeId) -> bool {
137 match self.associated_body() {
138 Some(b) => b.node_id == node_id,
144 /// Stores a crate and any number of inlined items from other crates.
147 pub dep_graph: DepGraph,
151 pub fn new(krate: Crate, dep_graph: &DepGraph) -> Forest {
154 dep_graph: dep_graph.clone(),
158 pub fn krate<'hir>(&'hir self) -> &'hir Crate {
159 self.dep_graph.read(DepNode::new_no_params(DepKind::Krate));
164 /// Represents a mapping from Node IDs to AST elements and their parent
167 pub struct Map<'hir> {
168 /// The backing storage for all the AST nodes.
169 pub forest: &'hir Forest,
171 /// Same as the dep_graph in forest, just available with one fewer
172 /// deref. This is a gratuitous micro-optimization.
173 pub dep_graph: DepGraph,
175 /// The SVH of the local crate.
178 /// `NodeId`s are sequential integers from 0, so we can be
179 /// super-compact by storing them in a vector. Not everything with
180 /// a `NodeId` is in the map, but empirically the occupancy is about
181 /// 75-80%, so there's not too much overhead (certainly less than
182 /// a hashmap, since they (at the time of writing) have a maximum
183 /// of 75% occupancy).
185 /// Also, indexing is pretty quick when you've got a vector and
186 /// plain old integers.
187 map: Vec<Option<Entry<'hir>>>,
189 definitions: &'hir Definitions,
191 /// The reverse mapping of `node_to_hir_id`.
192 hir_to_node_id: FxHashMap<HirId, NodeId>,
195 impl<'hir> Map<'hir> {
196 /// Registers a read in the dependency graph of the AST node with
197 /// the given `id`. This needs to be called each time a public
198 /// function returns the HIR for a node -- in other words, when it
199 /// "reveals" the content of a node to the caller (who might not
200 /// otherwise have had access to those contents, and hence needs a
201 /// read recorded). If the function just returns a DefId or
202 /// NodeId, no actual content was returned, so no read is needed.
203 pub fn read(&self, id: NodeId) {
204 if let Some(entry) = self.map[id.as_usize()] {
205 self.dep_graph.read_index(entry.dep_node);
207 bug!("called `HirMap::read()` with invalid `NodeId`: {:?}", id)
212 pub fn definitions(&self) -> &'hir Definitions {
216 pub fn def_key(&self, def_id: DefId) -> DefKey {
217 assert!(def_id.is_local());
218 self.definitions.def_key(def_id.index)
221 pub fn def_path_from_id(&self, id: NodeId) -> Option<DefPath> {
222 self.opt_local_def_id(id).map(|def_id| {
223 self.def_path(def_id)
227 pub fn def_path(&self, def_id: DefId) -> DefPath {
228 assert!(def_id.is_local());
229 self.definitions.def_path(def_id.index)
233 pub fn local_def_id(&self, node: NodeId) -> DefId {
234 self.opt_local_def_id(node).unwrap_or_else(|| {
235 bug!("local_def_id: no entry for `{}`, which has a map of `{:?}`",
236 node, self.find_entry(node))
241 pub fn opt_local_def_id(&self, node: NodeId) -> Option<DefId> {
242 self.definitions.opt_local_def_id(node)
246 pub fn as_local_node_id(&self, def_id: DefId) -> Option<NodeId> {
247 self.definitions.as_local_node_id(def_id)
251 pub fn hir_to_node_id(&self, hir_id: HirId) -> NodeId {
252 self.hir_to_node_id[&hir_id]
256 pub fn node_to_hir_id(&self, node_id: NodeId) -> HirId {
257 self.definitions.node_to_hir_id(node_id)
261 pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> HirId {
262 self.definitions.def_index_to_hir_id(def_index)
266 pub fn def_index_to_node_id(&self, def_index: DefIndex) -> NodeId {
267 self.definitions.as_local_node_id(DefId::local(def_index)).unwrap()
271 pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
272 self.definitions.def_index_to_hir_id(def_id.to_def_id().index)
276 pub fn local_def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
277 self.definitions.as_local_node_id(def_id.to_def_id()).unwrap()
280 pub fn describe_def(&self, node_id: NodeId) -> Option<Def> {
281 let node = if let Some(node) = self.find(node_id) {
288 Node::Item(item) => {
290 self.local_def_id(item.id)
294 ItemKind::Static(_, m, _) => Some(Def::Static(def_id(), m == MutMutable)),
295 ItemKind::Const(..) => Some(Def::Const(def_id())),
296 ItemKind::Fn(..) => Some(Def::Fn(def_id())),
297 ItemKind::Mod(..) => Some(Def::Mod(def_id())),
298 ItemKind::Existential(..) => Some(Def::Existential(def_id())),
299 ItemKind::Ty(..) => Some(Def::TyAlias(def_id())),
300 ItemKind::Enum(..) => Some(Def::Enum(def_id())),
301 ItemKind::Struct(..) => Some(Def::Struct(def_id())),
302 ItemKind::Union(..) => Some(Def::Union(def_id())),
303 ItemKind::Trait(..) => Some(Def::Trait(def_id())),
304 ItemKind::TraitAlias(..) => {
305 bug!("trait aliases are not yet implemented (see issue #41517)")
307 ItemKind::ExternCrate(_) |
309 ItemKind::ForeignMod(..) |
310 ItemKind::GlobalAsm(..) |
311 ItemKind::Impl(..) => None,
314 Node::ForeignItem(item) => {
315 let def_id = self.local_def_id(item.id);
317 ForeignItemKind::Fn(..) => Some(Def::Fn(def_id)),
318 ForeignItemKind::Static(_, m) => Some(Def::Static(def_id, m)),
319 ForeignItemKind::Type => Some(Def::ForeignTy(def_id)),
322 Node::TraitItem(item) => {
323 let def_id = self.local_def_id(item.id);
325 TraitItemKind::Const(..) => Some(Def::AssociatedConst(def_id)),
326 TraitItemKind::Method(..) => Some(Def::Method(def_id)),
327 TraitItemKind::Type(..) => Some(Def::AssociatedTy(def_id)),
330 Node::ImplItem(item) => {
331 let def_id = self.local_def_id(item.id);
333 ImplItemKind::Const(..) => Some(Def::AssociatedConst(def_id)),
334 ImplItemKind::Method(..) => Some(Def::Method(def_id)),
335 ImplItemKind::Type(..) => Some(Def::AssociatedTy(def_id)),
336 ImplItemKind::Existential(..) => Some(Def::AssociatedExistential(def_id)),
339 Node::Variant(variant) => {
340 let def_id = self.local_def_id(variant.node.data.id());
341 Some(Def::Variant(def_id))
347 Node::PathSegment(_) |
352 Node::StructCtor(_) |
354 Node::Visibility(_) |
357 Node::Local(local) => {
358 Some(Def::Local(local.id))
360 Node::MacroDef(macro_def) => {
361 Some(Def::Macro(self.local_def_id(macro_def.id),
364 Node::GenericParam(param) => {
365 Some(match param.kind {
366 GenericParamKind::Lifetime { .. } => Def::Local(param.id),
367 GenericParamKind::Type { .. } => Def::TyParam(self.local_def_id(param.id)),
373 fn entry_count(&self) -> usize {
377 fn find_entry(&self, id: NodeId) -> Option<Entry<'hir>> {
378 self.map.get(id.as_usize()).cloned().unwrap_or(None)
381 pub fn krate(&self) -> &'hir Crate {
385 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem {
386 self.read(id.node_id);
388 // NB: intentionally bypass `self.forest.krate()` so that we
389 // do not trigger a read of the whole krate here
390 self.forest.krate.trait_item(id)
393 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem {
394 self.read(id.node_id);
396 // NB: intentionally bypass `self.forest.krate()` so that we
397 // do not trigger a read of the whole krate here
398 self.forest.krate.impl_item(id)
401 pub fn body(&self, id: BodyId) -> &'hir Body {
402 self.read(id.node_id);
404 // NB: intentionally bypass `self.forest.krate()` so that we
405 // do not trigger a read of the whole krate here
406 self.forest.krate.body(id)
409 pub fn fn_decl(&self, node_id: ast::NodeId) -> Option<FnDecl> {
410 if let Some(entry) = self.find_entry(node_id) {
411 entry.fn_decl().cloned()
413 bug!("no entry for node_id `{}`", node_id)
417 /// Returns the `NodeId` that corresponds to the definition of
418 /// which this is the body of, i.e. a `fn`, `const` or `static`
419 /// item (possibly associated), a closure, or a `hir::AnonConst`.
420 pub fn body_owner(&self, BodyId { node_id }: BodyId) -> NodeId {
421 let parent = self.get_parent_node(node_id);
422 assert!(self.map[parent.as_usize()].map_or(false, |e| e.is_body_owner(node_id)));
426 pub fn body_owner_def_id(&self, id: BodyId) -> DefId {
427 self.local_def_id(self.body_owner(id))
430 /// Given a node id, returns the `BodyId` associated with it,
431 /// if the node is a body owner, otherwise returns `None`.
432 pub fn maybe_body_owned_by(&self, id: NodeId) -> Option<BodyId> {
433 if let Some(entry) = self.find_entry(id) {
434 if self.dep_graph.is_fully_enabled() {
435 let hir_id_owner = self.node_to_hir_id(id).owner;
436 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
437 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
440 entry.associated_body()
442 bug!("no entry for id `{}`", id)
446 /// Given a body owner's id, returns the `BodyId` associated with it.
447 pub fn body_owned_by(&self, id: NodeId) -> BodyId {
448 self.maybe_body_owned_by(id).unwrap_or_else(|| {
449 span_bug!(self.span(id), "body_owned_by: {} has no associated body",
450 self.node_to_string(id));
454 pub fn body_owner_kind(&self, id: NodeId) -> BodyOwnerKind {
456 Node::Item(&Item { node: ItemKind::Const(..), .. }) |
457 Node::TraitItem(&TraitItem { node: TraitItemKind::Const(..), .. }) |
458 Node::ImplItem(&ImplItem { node: ImplItemKind::Const(..), .. }) |
459 Node::AnonConst(_) => {
462 Node::Item(&Item { node: ItemKind::Static(_, m, _), .. }) => {
463 BodyOwnerKind::Static(m)
465 // Default to function if it's not a constant or static.
466 _ => BodyOwnerKind::Fn
470 pub fn ty_param_owner(&self, id: NodeId) -> NodeId {
472 Node::Item(&Item { node: ItemKind::Trait(..), .. }) => id,
473 Node::GenericParam(_) => self.get_parent_node(id),
474 _ => bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id))
478 pub fn ty_param_name(&self, id: NodeId) -> Name {
480 Node::Item(&Item { node: ItemKind::Trait(..), .. }) => keywords::SelfType.name(),
481 Node::GenericParam(param) => param.name.ident().name,
482 _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
486 pub fn trait_impls(&self, trait_did: DefId) -> &'hir [NodeId] {
487 self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
489 // NB: intentionally bypass `self.forest.krate()` so that we
490 // do not trigger a read of the whole krate here
491 self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..])
494 pub fn trait_auto_impl(&self, trait_did: DefId) -> Option<NodeId> {
495 self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls));
497 // NB: intentionally bypass `self.forest.krate()` so that we
498 // do not trigger a read of the whole krate here
499 self.forest.krate.trait_auto_impl.get(&trait_did).cloned()
502 pub fn trait_is_auto(&self, trait_did: DefId) -> bool {
503 self.trait_auto_impl(trait_did).is_some()
506 /// Get the attributes on the krate. This is preferable to
507 /// invoking `krate.attrs` because it registers a tighter
508 /// dep-graph access.
509 pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
510 let def_path_hash = self.definitions.def_path_hash(CRATE_DEF_INDEX);
512 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::Hir));
513 &self.forest.krate.attrs
516 /// Retrieve the Node corresponding to `id`, panicking if it cannot
518 pub fn get(&self, id: NodeId) -> Node<'hir> {
519 // read recorded by `find`
520 self.find(id).unwrap_or_else(|| bug!("couldn't find node id {} in the AST map", id))
523 pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
524 self.as_local_node_id(id).map(|id| self.get(id)) // read recorded by `get`
527 pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics> {
528 self.get_if_local(id).and_then(|node| {
530 Node::ImplItem(ref impl_item) => Some(&impl_item.generics),
531 Node::TraitItem(ref trait_item) => Some(&trait_item.generics),
532 Node::Item(ref item) => {
534 ItemKind::Fn(_, _, ref generics, _) |
535 ItemKind::Ty(_, ref generics) |
536 ItemKind::Enum(_, ref generics) |
537 ItemKind::Struct(_, ref generics) |
538 ItemKind::Union(_, ref generics) |
539 ItemKind::Trait(_, _, ref generics, ..) |
540 ItemKind::TraitAlias(ref generics, _) |
541 ItemKind::Impl(_, _, _, ref generics, ..) => Some(generics),
550 pub fn get_generics_span(&self, id: DefId) -> Option<Span> {
551 self.get_generics(id).map(|generics| generics.span).filter(|sp| *sp != DUMMY_SP)
554 /// Retrieve the Node corresponding to `id`, returning None if
556 pub fn find(&self, id: NodeId) -> Option<Node<'hir>> {
557 let result = self.find_entry(id).and_then(|entry| {
558 if let Node::Crate = entry.node {
564 if result.is_some() {
570 /// Similar to get_parent, returns the parent node id or id if there is no
571 /// parent. Note that the parent may be CRATE_NODE_ID, which is not itself
572 /// present in the map -- so passing the return value of get_parent_node to
573 /// get may actually panic.
574 /// This function returns the immediate parent in the AST, whereas get_parent
575 /// returns the enclosing item. Note that this might not be the actual parent
576 /// node in the AST - some kinds of nodes are not in the map and these will
577 /// never appear as the parent_node. So you can always walk the parent_nodes
578 /// from a node to the root of the ast (unless you get the same id back here
579 /// that can happen if the id is not in the map itself or is just weird).
580 pub fn get_parent_node(&self, id: NodeId) -> NodeId {
581 if self.dep_graph.is_fully_enabled() {
582 let hir_id_owner = self.node_to_hir_id(id).owner;
583 let def_path_hash = self.definitions.def_path_hash(hir_id_owner);
584 self.dep_graph.read(def_path_hash.to_dep_node(DepKind::HirBody));
587 self.find_entry(id).and_then(|x| x.parent_node()).unwrap_or(id)
590 /// Check if the node is an argument. An argument is a local variable whose
591 /// immediate parent is an item or a closure.
592 pub fn is_argument(&self, id: NodeId) -> bool {
593 match self.find(id) {
594 Some(Node::Binding(_)) => (),
597 match self.find(self.get_parent_node(id)) {
598 Some(Node::Item(_)) |
599 Some(Node::TraitItem(_)) |
600 Some(Node::ImplItem(_)) => true,
601 Some(Node::Expr(e)) => {
603 ExprKind::Closure(..) => true,
611 /// If there is some error when walking the parents (e.g., a node does not
612 /// have a parent in the map or a node can't be found), then we return the
613 /// last good node id we found. Note that reaching the crate root (id == 0),
614 /// is not an error, since items in the crate module have the crate root as
616 fn walk_parent_nodes<F, F2>(&self,
620 -> Result<NodeId, NodeId>
621 where F: Fn(&Node<'hir>) -> bool, F2: Fn(&Node<'hir>) -> bool
623 let mut id = start_id;
625 let parent_node = self.get_parent_node(id);
626 if parent_node == CRATE_NODE_ID {
627 return Ok(CRATE_NODE_ID);
629 if parent_node == id {
633 if let Some(entry) = self.find_entry(parent_node) {
634 if let Node::Crate = entry.node {
637 if found(&entry.node) {
638 return Ok(parent_node);
639 } else if bail_early(&entry.node) {
640 return Err(parent_node);
649 /// Retrieve the NodeId for `id`'s enclosing method, unless there's a
650 /// `while` or `loop` before reaching it, as block tail returns are not
651 /// available in them.
654 /// fn foo(x: usize) -> bool {
656 /// true // `get_return_block` gets passed the `id` corresponding
657 /// } else { // to this, it will return `foo`'s `NodeId`.
664 /// fn foo(x: usize) -> bool {
666 /// true // `get_return_block` gets passed the `id` corresponding
667 /// } // to this, it will return `None`.
671 pub fn get_return_block(&self, id: NodeId) -> Option<NodeId> {
672 let match_fn = |node: &Node<'_>| {
675 Node::ForeignItem(_) |
677 Node::ImplItem(_) => true,
681 let match_non_returning_block = |node: &Node<'_>| {
683 Node::Expr(ref expr) => {
685 ExprKind::While(..) | ExprKind::Loop(..) => true,
693 self.walk_parent_nodes(id, match_fn, match_non_returning_block).ok()
696 /// Retrieve the NodeId for `id`'s parent item, or `id` itself if no
697 /// parent item is in this map. The "parent item" is the closest parent node
698 /// in the HIR which is recorded by the map and is an item, either an item
699 /// in a module, trait, or impl.
700 pub fn get_parent(&self, id: NodeId) -> NodeId {
701 match self.walk_parent_nodes(id, |node| match *node {
703 Node::ForeignItem(_) |
705 Node::ImplItem(_) => true,
713 /// Returns the DefId of `id`'s nearest module parent, or `id` itself if no
714 /// module parent is in this map.
715 pub fn get_module_parent(&self, id: NodeId) -> DefId {
716 self.local_def_id(self.get_module_parent_node(id))
719 /// Returns the NodeId of `id`'s nearest module parent, or `id` itself if no
720 /// module parent is in this map.
721 pub fn get_module_parent_node(&self, id: NodeId) -> NodeId {
722 match self.walk_parent_nodes(id, |node| match *node {
723 Node::Item(&Item { node: ItemKind::Mod(_), .. }) => true,
731 /// Returns the nearest enclosing scope. A scope is an item or block.
732 /// FIXME it is not clear to me that all items qualify as scopes - statics
733 /// and associated types probably shouldn't, for example. Behavior in this
734 /// regard should be expected to be highly unstable.
735 pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
736 self.walk_parent_nodes(id, |node| match *node {
738 Node::ForeignItem(_) |
741 Node::Block(_) => true,
746 pub fn get_parent_did(&self, id: NodeId) -> DefId {
747 self.local_def_id(self.get_parent(id))
750 pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
751 let parent = self.get_parent(id);
752 if let Some(entry) = self.find_entry(parent) {
754 node: Node::Item(Item { node: ItemKind::ForeignMod(ref nm), .. }), .. } = entry
756 self.read(id); // reveals some of the content of a node
760 bug!("expected foreign mod or inlined parent, found {}", self.node_to_string(parent))
763 pub fn expect_item(&self, id: NodeId) -> &'hir Item {
764 match self.find(id) { // read recorded by `find`
765 Some(Node::Item(item)) => item,
766 _ => bug!("expected item, found {}", self.node_to_string(id))
770 pub fn expect_impl_item(&self, id: NodeId) -> &'hir ImplItem {
771 match self.find(id) {
772 Some(Node::ImplItem(item)) => item,
773 _ => bug!("expected impl item, found {}", self.node_to_string(id))
777 pub fn expect_trait_item(&self, id: NodeId) -> &'hir TraitItem {
778 match self.find(id) {
779 Some(Node::TraitItem(item)) => item,
780 _ => bug!("expected trait item, found {}", self.node_to_string(id))
784 pub fn expect_variant_data(&self, id: NodeId) -> &'hir VariantData {
785 match self.find(id) {
786 Some(Node::Item(i)) => {
788 ItemKind::Struct(ref struct_def, _) |
789 ItemKind::Union(ref struct_def, _) => struct_def,
790 _ => bug!("struct ID bound to non-struct {}", self.node_to_string(id))
793 Some(Node::StructCtor(data)) => data,
794 Some(Node::Variant(variant)) => &variant.node.data,
795 _ => bug!("expected struct or variant, found {}", self.node_to_string(id))
799 pub fn expect_variant(&self, id: NodeId) -> &'hir Variant {
800 match self.find(id) {
801 Some(Node::Variant(variant)) => variant,
802 _ => bug!("expected variant, found {}", self.node_to_string(id)),
806 pub fn expect_foreign_item(&self, id: NodeId) -> &'hir ForeignItem {
807 match self.find(id) {
808 Some(Node::ForeignItem(item)) => item,
809 _ => bug!("expected foreign item, found {}", self.node_to_string(id))
813 pub fn expect_expr(&self, id: NodeId) -> &'hir Expr {
814 match self.find(id) { // read recorded by find
815 Some(Node::Expr(expr)) => expr,
816 _ => bug!("expected expr, found {}", self.node_to_string(id))
820 /// Returns the name associated with the given NodeId's AST.
821 pub fn name(&self, id: NodeId) -> Name {
823 Node::Item(i) => i.name,
824 Node::ForeignItem(i) => i.name,
825 Node::ImplItem(ii) => ii.ident.name,
826 Node::TraitItem(ti) => ti.ident.name,
827 Node::Variant(v) => v.node.name,
828 Node::Field(f) => f.ident.name,
829 Node::Lifetime(lt) => lt.name.ident().name,
830 Node::GenericParam(param) => param.name.ident().name,
831 Node::Binding(&Pat { node: PatKind::Binding(_,_,l,_), .. }) => l.name,
832 Node::StructCtor(_) => self.name(self.get_parent(id)),
833 _ => bug!("no name for {}", self.node_to_string(id))
837 /// Given a node ID, get a list of attributes associated with the AST
838 /// corresponding to the Node ID
839 pub fn attrs(&self, id: NodeId) -> &'hir [ast::Attribute] {
840 self.read(id); // reveals attributes on the node
841 let attrs = match self.find(id) {
842 Some(Node::Item(i)) => Some(&i.attrs[..]),
843 Some(Node::ForeignItem(fi)) => Some(&fi.attrs[..]),
844 Some(Node::TraitItem(ref ti)) => Some(&ti.attrs[..]),
845 Some(Node::ImplItem(ref ii)) => Some(&ii.attrs[..]),
846 Some(Node::Variant(ref v)) => Some(&v.node.attrs[..]),
847 Some(Node::Field(ref f)) => Some(&f.attrs[..]),
848 Some(Node::Expr(ref e)) => Some(&*e.attrs),
849 Some(Node::Stmt(ref s)) => Some(s.node.attrs()),
850 Some(Node::GenericParam(param)) => Some(¶m.attrs[..]),
851 // unit/tuple structs take the attributes straight from
852 // the struct definition.
853 Some(Node::StructCtor(_)) => return self.attrs(self.get_parent(id)),
859 /// Returns an iterator that yields the node id's with paths that
860 /// match `parts`. (Requires `parts` is non-empty.)
862 /// For example, if given `parts` equal to `["bar", "quux"]`, then
863 /// the iterator will produce node id's for items with paths
864 /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
865 /// any other such items it can find in the map.
866 pub fn nodes_matching_suffix<'a>(&'a self, parts: &'a [String])
867 -> NodesMatchingSuffix<'a, 'hir> {
868 NodesMatchingSuffix {
870 item_name: parts.last().unwrap(),
871 in_which: &parts[..parts.len() - 1],
876 pub fn span(&self, id: NodeId) -> Span {
877 self.read(id); // reveals span from node
878 match self.find_entry(id).map(|entry| entry.node) {
879 Some(Node::Item(item)) => item.span,
880 Some(Node::ForeignItem(foreign_item)) => foreign_item.span,
881 Some(Node::TraitItem(trait_method)) => trait_method.span,
882 Some(Node::ImplItem(impl_item)) => impl_item.span,
883 Some(Node::Variant(variant)) => variant.span,
884 Some(Node::Field(field)) => field.span,
885 Some(Node::AnonConst(constant)) => self.body(constant.body).value.span,
886 Some(Node::Expr(expr)) => expr.span,
887 Some(Node::Stmt(stmt)) => stmt.span,
888 Some(Node::PathSegment(seg)) => seg.ident.span,
889 Some(Node::Ty(ty)) => ty.span,
890 Some(Node::TraitRef(tr)) => tr.path.span,
891 Some(Node::Binding(pat)) => pat.span,
892 Some(Node::Pat(pat)) => pat.span,
893 Some(Node::Block(block)) => block.span,
894 Some(Node::StructCtor(_)) => self.expect_item(self.get_parent(id)).span,
895 Some(Node::Lifetime(lifetime)) => lifetime.span,
896 Some(Node::GenericParam(param)) => param.span,
897 Some(Node::Visibility(&Spanned {
898 node: VisibilityKind::Restricted { ref path, .. }, ..
900 Some(Node::Visibility(v)) => bug!("unexpected Visibility {:?}", v),
901 Some(Node::Local(local)) => local.span,
902 Some(Node::MacroDef(macro_def)) => macro_def.span,
903 Some(Node::Crate) => self.forest.krate.span,
904 None => bug!("hir::map::Map::span: id not in map: {:?}", id),
908 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
909 self.as_local_node_id(id).map(|id| self.span(id))
912 pub fn node_to_string(&self, id: NodeId) -> String {
913 node_id_to_string(self, id, true)
916 pub fn node_to_user_string(&self, id: NodeId) -> String {
917 node_id_to_string(self, id, false)
920 pub fn node_to_pretty_string(&self, id: NodeId) -> String {
921 print::to_string(self, |s| s.print_node(self.get(id)))
925 pub struct NodesMatchingSuffix<'a, 'hir:'a> {
927 item_name: &'a String,
928 in_which: &'a [String],
932 impl<'a, 'hir> NodesMatchingSuffix<'a, 'hir> {
933 /// Returns true only if some suffix of the module path for parent
934 /// matches `self.in_which`.
936 /// In other words: let `[x_0,x_1,...,x_k]` be `self.in_which`;
937 /// returns true if parent's path ends with the suffix
938 /// `x_0::x_1::...::x_k`.
939 fn suffix_matches(&self, parent: NodeId) -> bool {
940 let mut cursor = parent;
941 for part in self.in_which.iter().rev() {
942 let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
943 None => return false,
944 Some((node_id, name)) => (node_id, name),
946 if mod_name != &**part {
949 cursor = self.map.get_parent(mod_id);
953 // Finds the first mod in parent chain for `id`, along with
956 // If `id` itself is a mod named `m` with parent `p`, then
957 // returns `Some(id, m, p)`. If `id` has no mod in its parent
958 // chain, then returns `None`.
959 fn find_first_mod_parent<'a>(map: &'a Map<'_>, mut id: NodeId) -> Option<(NodeId, Name)> {
961 if let Node::Item(item) = map.find(id)? {
962 if item_is_mod(&item) {
963 return Some((id, item.name))
966 let parent = map.get_parent(id);
967 if parent == id { return None }
971 fn item_is_mod(item: &Item) -> bool {
973 ItemKind::Mod(_) => true,
980 // We are looking at some node `n` with a given name and parent
981 // id; do their names match what I am seeking?
982 fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
983 name == &**self.item_name && self.suffix_matches(parent_of_n)
987 impl<'a, 'hir> Iterator for NodesMatchingSuffix<'a, 'hir> {
990 fn next(&mut self) -> Option<NodeId> {
993 if idx.as_usize() >= self.map.entry_count() {
996 self.idx = NodeId::from_u32(self.idx.as_u32() + 1);
997 let name = match self.map.find_entry(idx).map(|entry| entry.node) {
998 Some(Node::Item(n)) => n.name(),
999 Some(Node::ForeignItem(n)) => n.name(),
1000 Some(Node::TraitItem(n)) => n.name(),
1001 Some(Node::ImplItem(n)) => n.name(),
1002 Some(Node::Variant(n)) => n.name(),
1003 Some(Node::Field(n)) => n.name(),
1006 if self.matches_names(self.map.get_parent(idx), name) {
1014 fn name(&self) -> Name;
1017 impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
1019 impl Named for Item { fn name(&self) -> Name { self.name } }
1020 impl Named for ForeignItem { fn name(&self) -> Name { self.name } }
1021 impl Named for VariantKind { fn name(&self) -> Name { self.name } }
1022 impl Named for StructField { fn name(&self) -> Name { self.ident.name } }
1023 impl Named for TraitItem { fn name(&self) -> Name { self.ident.name } }
1024 impl Named for ImplItem { fn name(&self) -> Name { self.ident.name } }
1026 pub fn map_crate<'hir>(sess: &::session::Session,
1027 cstore: &dyn CrateStore,
1028 forest: &'hir mut Forest,
1029 definitions: &'hir Definitions)
1031 let (map, crate_hash) = {
1032 let hcx = ::ich::StableHashingContext::new(sess, &forest.krate, definitions, cstore);
1034 let mut collector = NodeCollector::root(&forest.krate,
1038 intravisit::walk_crate(&mut collector, &forest.krate);
1040 let crate_disambiguator = sess.local_crate_disambiguator();
1041 let cmdline_args = sess.opts.dep_tracking_hash();
1042 collector.finalize_and_compute_crate_hash(crate_disambiguator,
1048 if log_enabled!(::log::Level::Debug) {
1049 // This only makes sense for ordered stores; note the
1050 // enumerate to count the number of entries.
1051 let (entries_less_1, _) = map.iter().filter_map(|x| *x).enumerate().last()
1052 .expect("AST map was empty after folding?");
1054 let entries = entries_less_1 + 1;
1055 let vector_length = map.len();
1056 debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%",
1057 entries, vector_length, (entries as f64 / vector_length as f64) * 100.);
1060 // Build the reverse mapping of `node_to_hir_id`.
1061 let hir_to_node_id = definitions.node_to_hir_id.iter_enumerated()
1062 .map(|(node_id, &hir_id)| (hir_id, node_id)).collect();
1066 dep_graph: forest.dep_graph.clone(),
1073 hir_id_validator::check_crate(&map);
1078 /// Identical to the `PpAnn` implementation for `hir::Crate`,
1079 /// except it avoids creating a dependency on the whole crate.
1080 impl<'hir> print::PpAnn for Map<'hir> {
1081 fn nested(&self, state: &mut print::State<'_>, nested: print::Nested) -> io::Result<()> {
1083 Nested::Item(id) => state.print_item(self.expect_item(id.id)),
1084 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
1085 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
1086 Nested::Body(id) => state.print_expr(&self.body(id).value),
1087 Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
1092 impl<'a> print::State<'a> {
1093 pub fn print_node(&mut self, node: Node<'_>) -> io::Result<()> {
1095 Node::Item(a) => self.print_item(&a),
1096 Node::ForeignItem(a) => self.print_foreign_item(&a),
1097 Node::TraitItem(a) => self.print_trait_item(a),
1098 Node::ImplItem(a) => self.print_impl_item(a),
1099 Node::Variant(a) => self.print_variant(&a),
1100 Node::AnonConst(a) => self.print_anon_const(&a),
1101 Node::Expr(a) => self.print_expr(&a),
1102 Node::Stmt(a) => self.print_stmt(&a),
1103 Node::PathSegment(a) => self.print_path_segment(&a),
1104 Node::Ty(a) => self.print_type(&a),
1105 Node::TraitRef(a) => self.print_trait_ref(&a),
1107 Node::Pat(a) => self.print_pat(&a),
1109 use syntax::print::pprust::PrintState;
1111 // containing cbox, will be closed by print-block at }
1112 self.cbox(print::indent_unit)?;
1113 // head-ibox, will be closed by print-block after {
1115 self.print_block(&a)
1117 Node::Lifetime(a) => self.print_lifetime(&a),
1118 Node::Visibility(a) => self.print_visibility(&a),
1119 Node::GenericParam(_) => bug!("cannot print Node::GenericParam"),
1120 Node::Field(_) => bug!("cannot print StructField"),
1121 // these cases do not carry enough information in the
1122 // hir_map to reconstruct their full structure for pretty
1124 Node::StructCtor(_) => bug!("cannot print isolated StructCtor"),
1125 Node::Local(a) => self.print_local_decl(&a),
1126 Node::MacroDef(_) => bug!("cannot print MacroDef"),
1127 Node::Crate => bug!("cannot print Crate"),
1132 fn node_id_to_string(map: &Map<'_>, id: NodeId, include_id: bool) -> String {
1133 let id_str = format!(" (id={})", id);
1134 let id_str = if include_id { &id_str[..] } else { "" };
1137 // This functionality is used for debugging, try to use TyCtxt to get
1138 // the user-friendly path, otherwise fall back to stringifying DefPath.
1139 ::ty::tls::with_opt(|tcx| {
1140 if let Some(tcx) = tcx {
1141 tcx.node_path_str(id)
1142 } else if let Some(path) = map.def_path_from_id(id) {
1143 path.data.into_iter().map(|elem| {
1144 elem.data.to_string()
1145 }).collect::<Vec<_>>().join("::")
1147 String::from("<missing path>")
1152 match map.find(id) {
1153 Some(Node::Item(item)) => {
1154 let item_str = match item.node {
1155 ItemKind::ExternCrate(..) => "extern crate",
1156 ItemKind::Use(..) => "use",
1157 ItemKind::Static(..) => "static",
1158 ItemKind::Const(..) => "const",
1159 ItemKind::Fn(..) => "fn",
1160 ItemKind::Mod(..) => "mod",
1161 ItemKind::ForeignMod(..) => "foreign mod",
1162 ItemKind::GlobalAsm(..) => "global asm",
1163 ItemKind::Ty(..) => "ty",
1164 ItemKind::Existential(..) => "existential type",
1165 ItemKind::Enum(..) => "enum",
1166 ItemKind::Struct(..) => "struct",
1167 ItemKind::Union(..) => "union",
1168 ItemKind::Trait(..) => "trait",
1169 ItemKind::TraitAlias(..) => "trait alias",
1170 ItemKind::Impl(..) => "impl",
1172 format!("{} {}{}", item_str, path_str(), id_str)
1174 Some(Node::ForeignItem(_)) => {
1175 format!("foreign item {}{}", path_str(), id_str)
1177 Some(Node::ImplItem(ii)) => {
1179 ImplItemKind::Const(..) => {
1180 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1182 ImplItemKind::Method(..) => {
1183 format!("method {} in {}{}", ii.ident, path_str(), id_str)
1185 ImplItemKind::Type(_) => {
1186 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1188 ImplItemKind::Existential(_) => {
1189 format!("assoc existential type {} in {}{}", ii.ident, path_str(), id_str)
1193 Some(Node::TraitItem(ti)) => {
1194 let kind = match ti.node {
1195 TraitItemKind::Const(..) => "assoc constant",
1196 TraitItemKind::Method(..) => "trait method",
1197 TraitItemKind::Type(..) => "assoc type",
1200 format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1202 Some(Node::Variant(ref variant)) => {
1203 format!("variant {} in {}{}",
1207 Some(Node::Field(ref field)) => {
1208 format!("field {} in {}{}",
1212 Some(Node::AnonConst(_)) => {
1213 format!("const {}{}", map.node_to_pretty_string(id), id_str)
1215 Some(Node::Expr(_)) => {
1216 format!("expr {}{}", map.node_to_pretty_string(id), id_str)
1218 Some(Node::Stmt(_)) => {
1219 format!("stmt {}{}", map.node_to_pretty_string(id), id_str)
1221 Some(Node::PathSegment(_)) => {
1222 format!("path segment {}{}", map.node_to_pretty_string(id), id_str)
1224 Some(Node::Ty(_)) => {
1225 format!("type {}{}", map.node_to_pretty_string(id), id_str)
1227 Some(Node::TraitRef(_)) => {
1228 format!("trait_ref {}{}", map.node_to_pretty_string(id), id_str)
1230 Some(Node::Binding(_)) => {
1231 format!("local {}{}", map.node_to_pretty_string(id), id_str)
1233 Some(Node::Pat(_)) => {
1234 format!("pat {}{}", map.node_to_pretty_string(id), id_str)
1236 Some(Node::Block(_)) => {
1237 format!("block {}{}", map.node_to_pretty_string(id), id_str)
1239 Some(Node::Local(_)) => {
1240 format!("local {}{}", map.node_to_pretty_string(id), id_str)
1242 Some(Node::StructCtor(_)) => {
1243 format!("struct_ctor {}{}", path_str(), id_str)
1245 Some(Node::Lifetime(_)) => {
1246 format!("lifetime {}{}", map.node_to_pretty_string(id), id_str)
1248 Some(Node::GenericParam(ref param)) => {
1249 format!("generic_param {:?}{}", param, id_str)
1251 Some(Node::Visibility(ref vis)) => {
1252 format!("visibility {:?}{}", vis, id_str)
1254 Some(Node::MacroDef(_)) => {
1255 format!("macro {}{}", path_str(), id_str)
1257 Some(Node::Crate) => format!("root_crate"),
1258 None => format!("unknown node{}", id_str),
1262 pub fn describe_def(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> Option<Def> {
1263 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1264 tcx.hir.describe_def(node_id)
1266 bug!("Calling local describe_def query provider for upstream DefId: {:?}",