rust/compiler/rustc_middle/src/hir/map/mod.rs

1100 lines
41 KiB
Rust
Raw Normal View History

2016-04-14 12:14:03 +12:00
use self::collector::NodeCollector;
2021-02-28 18:58:50 +01:00
use crate::hir::{HirOwnerData, IndexedHir};
use crate::middle::cstore::CrateStore;
2020-02-07 13:13:35 +01:00
use crate::ty::TyCtxt;
2020-04-27 23:26:11 +05:30
use rustc_ast as ast;
2021-02-28 18:58:50 +01:00
use rustc_data_structures::fingerprint::Fingerprint;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
2018-08-03 12:22:22 -06:00
use rustc_data_structures::svh::Svh;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
use rustc_hir::definitions::{DefKey, DefPath, Definitions};
use rustc_hir::intravisit;
use rustc_hir::intravisit::Visitor;
use rustc_hir::itemlikevisit::ItemLikeVisitor;
use rustc_hir::*;
use rustc_index::vec::Idx;
use rustc_span::hygiene::MacroKind;
use rustc_span::source_map::Spanned;
use rustc_span::symbol::{kw, Ident, Symbol};
2020-01-07 14:38:27 +01:00
use rustc_span::Span;
2019-12-22 17:42:04 -05:00
use rustc_target::spec::abi::Abi;
2015-07-31 00:04:06 -07:00
pub mod blocks;
mod collector;
fn fn_decl<'hir>(node: Node<'hir>) -> Option<&'hir FnDecl<'hir>> {
match node {
2020-03-24 06:17:44 +01:00
Node::Item(Item { kind: ItemKind::Fn(sig, _, _), .. })
| Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(sig, _), .. })
| Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(sig, _), .. }) => Some(&sig.decl),
Node::Expr(Expr { kind: ExprKind::Closure(_, fn_decl, ..), .. }) => Some(fn_decl),
_ => None,
}
}
2019-11-06 11:43:33 -08:00
pub fn fn_sig<'hir>(node: Node<'hir>) -> Option<&'hir FnSig<'hir>> {
match &node {
2020-03-24 06:17:44 +01:00
Node::Item(Item { kind: ItemKind::Fn(sig, _, _), .. })
| Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(sig, _), .. })
| Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(sig, _), .. }) => Some(sig),
_ => None,
2019-11-06 11:43:33 -08:00
}
}
2019-11-06 11:43:33 -08:00
2020-06-22 15:54:28 -07:00
pub fn associated_body<'hir>(node: Node<'hir>) -> Option<BodyId> {
match node {
2020-03-24 06:17:44 +01:00
Node::Item(Item {
kind: ItemKind::Const(_, body) | ItemKind::Static(.., body) | ItemKind::Fn(.., body),
..
})
| Node::TraitItem(TraitItem {
kind:
TraitItemKind::Const(_, Some(body)) | TraitItemKind::Fn(_, TraitFn::Provided(body)),
..
})
| Node::ImplItem(ImplItem {
kind: ImplItemKind::Const(_, body) | ImplItemKind::Fn(_, body),
..
})
| Node::Expr(Expr { kind: ExprKind::Closure(.., body, _, _), .. }) => Some(*body),
Node::AnonConst(constant) => Some(constant.body),
_ => None,
}
}
fn is_body_owner<'hir>(node: Node<'hir>, hir_id: HirId) -> bool {
match associated_body(node) {
Some(b) => b.hir_id == hir_id,
None => false,
}
}
2020-02-09 15:32:00 +01:00
#[derive(Copy, Clone)]
2017-01-26 03:21:50 +02:00
pub struct Map<'hir> {
2020-02-07 13:13:35 +01:00
pub(super) tcx: TyCtxt<'hir>,
}
/// An iterator that walks up the ancestor tree of a given `HirId`.
/// Constructed using `tcx.hir().parent_iter(hir_id)`.
pub struct ParentHirIterator<'map, 'hir> {
current_id: HirId,
2019-11-29 14:08:03 +01:00
map: &'map Map<'hir>,
}
2020-01-07 15:06:39 +01:00
impl<'hir> Iterator for ParentHirIterator<'_, 'hir> {
2019-11-29 14:08:03 +01:00
type Item = (HirId, Node<'hir>);
fn next(&mut self) -> Option<Self::Item> {
if self.current_id == CRATE_HIR_ID {
return None;
}
2019-12-22 17:42:04 -05:00
loop {
// There are nodes that do not have entries, so we need to skip them.
let parent_id = self.map.get_parent_node(self.current_id);
if parent_id == self.current_id {
self.current_id = CRATE_HIR_ID;
return None;
}
self.current_id = parent_id;
if let Some(node) = self.map.find(parent_id) {
return Some((parent_id, node));
}
// If this `HirId` doesn't have an entry, skip it and look for its `parent_id`.
}
}
}
/// An iterator that walks up the ancestor tree of a given `HirId`.
/// Constructed using `tcx.hir().parent_owner_iter(hir_id)`.
pub struct ParentOwnerIterator<'map, 'hir> {
current_id: HirId,
map: &'map Map<'hir>,
}
impl<'hir> Iterator for ParentOwnerIterator<'_, 'hir> {
type Item = (HirId, Node<'hir>);
fn next(&mut self) -> Option<Self::Item> {
if self.current_id.local_id.index() != 0 {
self.current_id.local_id = ItemLocalId::new(0);
if let Some(node) = self.map.find(self.current_id) {
return Some((self.current_id, node));
}
}
if self.current_id == CRATE_HIR_ID {
return None;
}
loop {
// There are nodes that do not have entries, so we need to skip them.
let parent_id = self.map.def_key(self.current_id.owner).parent;
let parent_id = parent_id.map_or(CRATE_HIR_ID.owner, |local_def_index| {
let def_id = LocalDefId { local_def_index };
self.map.local_def_id_to_hir_id(def_id).owner
});
self.current_id = HirId::make_owner(parent_id);
// If this `HirId` doesn't have an entry, skip it and look for its `parent_id`.
if let Some(node) = self.map.find(self.current_id) {
return Some((self.current_id, node));
}
}
}
}
2017-01-26 03:21:50 +02:00
impl<'hir> Map<'hir> {
2020-02-09 15:32:00 +01:00
pub fn krate(&self) -> &'hir Crate<'hir> {
self.tcx.hir_crate(LOCAL_CRATE)
2020-02-06 13:41:37 +01:00
}
#[inline]
2020-02-09 15:32:00 +01:00
pub fn definitions(&self) -> &'hir Definitions {
&self.tcx.definitions
}
pub fn def_key(&self, def_id: LocalDefId) -> DefKey {
self.tcx.definitions.def_key(def_id)
}
pub fn def_path_from_hir_id(&self, id: HirId) -> Option<DefPath> {
self.opt_local_def_id(id).map(|def_id| self.def_path(def_id))
}
pub fn def_path(&self, def_id: LocalDefId) -> DefPath {
self.tcx.definitions.def_path(def_id)
}
2019-02-03 09:14:31 +01:00
#[inline]
pub fn local_def_id(&self, hir_id: HirId) -> LocalDefId {
self.opt_local_def_id(hir_id).unwrap_or_else(|| {
bug!(
"local_def_id: no entry for `{:?}`, which has a map of `{:?}`",
hir_id,
self.find(hir_id)
)
})
2019-02-03 09:14:31 +01:00
}
#[inline]
pub fn opt_local_def_id(&self, hir_id: HirId) -> Option<LocalDefId> {
self.tcx.definitions.opt_hir_id_to_local_def_id(hir_id)
}
#[inline]
pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
self.tcx.definitions.local_def_id_to_hir_id(def_id)
}
2020-11-28 22:07:00 +01:00
pub fn iter_local_def_id(&self) -> impl Iterator<Item = LocalDefId> + '_ {
self.tcx.definitions.iter_local_def_id()
}
2021-01-16 14:35:16 +01:00
pub fn opt_def_kind(&self, local_def_id: LocalDefId) -> Option<DefKind> {
// FIXME(eddyb) support `find` on the crate root.
if local_def_id.to_def_id().index == CRATE_DEF_INDEX {
2021-01-16 14:35:16 +01:00
return Some(DefKind::Mod);
}
let hir_id = self.local_def_id_to_hir_id(local_def_id);
2021-01-16 14:35:16 +01:00
let def_kind = match self.find(hir_id)? {
2019-12-22 17:42:04 -05:00
Node::Item(item) => match item.kind {
ItemKind::Static(..) => DefKind::Static,
ItemKind::Const(..) => DefKind::Const,
ItemKind::Fn(..) => DefKind::Fn,
ItemKind::Mod(..) => DefKind::Mod,
ItemKind::OpaqueTy(..) => DefKind::OpaqueTy,
ItemKind::TyAlias(..) => DefKind::TyAlias,
ItemKind::Enum(..) => DefKind::Enum,
ItemKind::Struct(..) => DefKind::Struct,
ItemKind::Union(..) => DefKind::Union,
ItemKind::Trait(..) => DefKind::Trait,
ItemKind::TraitAlias(..) => DefKind::TraitAlias,
ItemKind::ExternCrate(_) => DefKind::ExternCrate,
ItemKind::Use(..) => DefKind::Use,
2020-11-11 22:40:09 +01:00
ItemKind::ForeignMod { .. } => DefKind::ForeignMod,
ItemKind::GlobalAsm(..) => DefKind::GlobalAsm,
ItemKind::Impl { .. } => DefKind::Impl,
2019-12-22 17:42:04 -05:00
},
Node::ForeignItem(item) => match item.kind {
ForeignItemKind::Fn(..) => DefKind::Fn,
ForeignItemKind::Static(..) => DefKind::Static,
ForeignItemKind::Type => DefKind::ForeignTy,
},
Node::TraitItem(item) => match item.kind {
TraitItemKind::Const(..) => DefKind::AssocConst,
2020-03-03 12:46:22 -06:00
TraitItemKind::Fn(..) => DefKind::AssocFn,
2019-12-22 17:42:04 -05:00
TraitItemKind::Type(..) => DefKind::AssocTy,
},
Node::ImplItem(item) => match item.kind {
ImplItemKind::Const(..) => DefKind::AssocConst,
2020-03-05 09:57:34 -06:00
ImplItemKind::Fn(..) => DefKind::AssocFn,
2019-12-22 17:42:04 -05:00
ImplItemKind::TyAlias(..) => DefKind::AssocTy,
},
Node::Variant(_) => DefKind::Variant,
Node::Ctor(variant_data) => {
// FIXME(eddyb) is this even possible, if we have a `Node::Ctor`?
assert_ne!(variant_data.ctor_hir_id(), None);
2019-06-24 09:58:49 +02:00
let ctor_of = match self.find(self.get_parent_node(hir_id)) {
Some(Node::Item(..)) => def::CtorOf::Struct,
Some(Node::Variant(..)) => def::CtorOf::Variant,
_ => unreachable!(),
};
DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data))
}
Node::AnonConst(_) => DefKind::AnonConst,
Node::Field(_) => DefKind::Field,
Node::Expr(expr) => match expr.kind {
ExprKind::Closure(.., None) => DefKind::Closure,
ExprKind::Closure(.., Some(_)) => DefKind::Generator,
_ => bug!("def_kind: unsupported node: {}", self.node_to_string(hir_id)),
},
Node::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
Node::GenericParam(param) => match param.kind {
GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam,
GenericParamKind::Type { .. } => DefKind::TyParam,
GenericParamKind::Const { .. } => DefKind::ConstParam,
},
2021-01-18 19:15:53 +01:00
Node::Crate(_) => DefKind::Mod,
Node::Stmt(_)
2019-12-22 17:42:04 -05:00
| Node::PathSegment(_)
| Node::Ty(_)
| Node::TraitRef(_)
| Node::Pat(_)
| Node::Binding(_)
| Node::Local(_)
| Node::Param(_)
| Node::Arm(_)
| Node::Lifetime(_)
| Node::Visibility(_)
2021-01-18 19:15:53 +01:00
| Node::Block(_) => return None,
2021-01-16 14:35:16 +01:00
};
Some(def_kind)
}
pub fn def_kind(&self, local_def_id: LocalDefId) -> DefKind {
self.opt_def_kind(local_def_id)
.unwrap_or_else(|| bug!("def_kind: unsupported node: {:?}", local_def_id))
2019-02-04 11:09:32 +01:00
}
pub fn find_parent_node(&self, id: HirId) -> Option<HirId> {
2020-03-10 13:44:53 -07:00
if id.local_id == ItemLocalId::from_u32(0) {
2021-03-05 20:09:33 +01:00
let index = self.tcx.index_hir(LOCAL_CRATE);
index.parenting.get(&id.owner).copied()
2020-02-07 16:43:36 +01:00
} else {
let owner = self.tcx.hir_owner_nodes(id.owner)?;
let node = owner.nodes[id.local_id].as_ref()?;
let hir_id = HirId { owner: id.owner, local_id: node.parent };
Some(hir_id)
2020-02-07 16:43:36 +01:00
}
}
pub fn get_parent_node(&self, hir_id: HirId) -> HirId {
2021-03-05 20:09:33 +01:00
self.find_parent_node(hir_id).unwrap_or(CRATE_HIR_ID)
}
/// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
pub fn find(&self, id: HirId) -> Option<Node<'hir>> {
if id.local_id == ItemLocalId::from_u32(0) {
let owner = self.tcx.hir_owner(id.owner)?;
Some(owner.node)
} else {
let owner = self.tcx.hir_owner_nodes(id.owner)?;
let node = owner.nodes[id.local_id].as_ref()?;
Some(node.node)
}
}
/// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found.
pub fn get(&self, id: HirId) -> Node<'hir> {
self.find(id).unwrap_or_else(|| bug!("couldn't find hir id {} in the HIR map", id))
}
pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
id.as_local().and_then(|id| self.find(self.local_def_id_to_hir_id(id)))
}
pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics<'hir>> {
self.get_if_local(id).and_then(|node| match &node {
Node::ImplItem(impl_item) => Some(&impl_item.generics),
Node::TraitItem(trait_item) => Some(&trait_item.generics),
Node::Item(Item {
kind:
ItemKind::Fn(_, generics, _)
| ItemKind::TyAlias(_, generics)
| ItemKind::Enum(_, generics)
| ItemKind::Struct(_, generics)
| ItemKind::Union(_, generics)
| ItemKind::Trait(_, _, generics, ..)
| ItemKind::TraitAlias(generics, _)
| ItemKind::Impl(Impl { generics, .. }),
..
}) => Some(generics),
_ => None,
})
2020-03-16 19:17:40 +01:00
}
2021-01-30 12:06:04 +01:00
pub fn item(&self, id: ItemId) -> &'hir Item<'hir> {
match self.find(id.hir_id()).unwrap() {
2020-02-07 15:17:05 +01:00
Node::Item(item) => item,
_ => bug!(),
}
2020-01-07 15:51:38 +01:00
}
2019-11-28 21:47:10 +01:00
pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
match self.find(id.hir_id()).unwrap() {
2020-02-07 15:17:05 +01:00
Node::TraitItem(item) => item,
_ => bug!(),
}
}
2019-11-28 22:16:44 +01:00
pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
match self.find(id.hir_id()).unwrap() {
2020-02-07 15:17:05 +01:00
Node::ImplItem(item) => item,
_ => bug!(),
}
}
2020-11-11 21:57:54 +01:00
pub fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
match self.find(id.hir_id()).unwrap() {
2020-11-11 21:57:54 +01:00
Node::ForeignItem(item) => item,
_ => bug!(),
}
}
2019-11-29 11:09:23 +01:00
pub fn body(&self, id: BodyId) -> &'hir Body<'hir> {
2020-03-16 19:17:40 +01:00
self.tcx.hir_owner_nodes(id.hir_id.owner).unwrap().bodies.get(&id.hir_id.local_id).unwrap()
}
2019-11-30 17:46:46 +01:00
pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnDecl<'hir>> {
if let Some(node) = self.find(hir_id) {
fn_decl(node)
} else {
bug!("no node for hir_id `{}`", hir_id)
}
2019-02-04 11:09:32 +01:00
}
2019-11-30 15:20:35 +01:00
pub fn fn_sig_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnSig<'hir>> {
if let Some(node) = self.find(hir_id) {
fn_sig(node)
2019-11-06 11:43:33 -08:00
} else {
bug!("no node for hir_id `{}`", hir_id)
2019-11-06 11:43:33 -08:00
}
}
2020-05-20 14:57:16 +02:00
pub fn enclosing_body_owner(&self, hir_id: HirId) -> HirId {
for (parent, _) in self.parent_iter(hir_id) {
if let Some(body) = self.maybe_body_owned_by(parent) {
return self.body_owner(body);
}
}
bug!("no `enclosing_body_owner` for hir_id `{}`", hir_id);
}
/// Returns the `HirId` that corresponds to the definition of
/// which this is the body of, i.e., a `fn`, `const` or `static`
/// item (possibly associated), a closure, or a `hir::AnonConst`.
2019-06-14 12:28:47 +02:00
pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> HirId {
let parent = self.get_parent_node(hir_id);
assert!(self.find(parent).map_or(false, |n| is_body_owner(n, hir_id)));
2019-06-14 12:28:47 +02:00
parent
}
pub fn body_owner_def_id(&self, id: BodyId) -> LocalDefId {
self.local_def_id(self.body_owner(id))
}
2019-06-14 12:28:47 +02:00
/// Given a `HirId`, returns the `BodyId` associated with it,
/// if the node is a body owner, otherwise returns `None`.
pub fn maybe_body_owned_by(&self, hir_id: HirId) -> Option<BodyId> {
2020-05-14 23:07:46 +08:00
self.find(hir_id).map(associated_body).flatten()
2017-04-04 12:06:35 -04:00
}
/// Given a body owner's id, returns the `BodyId` associated with it.
pub fn body_owned_by(&self, id: HirId) -> BodyId {
self.maybe_body_owned_by(id).unwrap_or_else(|| {
2019-12-22 17:42:04 -05:00
span_bug!(
self.span(id),
"body_owned_by: {} has no associated body",
self.node_to_string(id)
);
})
}
pub fn body_param_names(&self, id: BodyId) -> impl Iterator<Item = Ident> + 'hir {
self.body(id).params.iter().map(|arg| match arg.pat.kind {
PatKind::Binding(_, _, ident, _) => ident,
_ => Ident::new(kw::Empty, rustc_span::DUMMY_SP),
})
}
2020-05-07 10:22:35 -07:00
/// Returns the `BodyOwnerKind` of this `LocalDefId`.
///
/// Panics if `LocalDefId` does not have an associated body.
pub fn body_owner_kind(&self, id: HirId) -> BodyOwnerKind {
2019-06-20 10:39:19 +02:00
match self.get(id) {
2019-12-22 17:42:04 -05:00
Node::Item(&Item { kind: ItemKind::Const(..), .. })
| Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. })
| Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. })
| Node::AnonConst(_) => BodyOwnerKind::Const,
Node::Ctor(..)
| Node::Item(&Item { kind: ItemKind::Fn(..), .. })
2020-03-03 12:46:22 -06:00
| Node::TraitItem(&TraitItem { kind: TraitItemKind::Fn(..), .. })
2020-03-05 09:57:34 -06:00
| Node::ImplItem(&ImplItem { kind: ImplItemKind::Fn(..), .. }) => BodyOwnerKind::Fn,
2019-12-22 17:42:04 -05:00
Node::Item(&Item { kind: ItemKind::Static(_, m, _), .. }) => BodyOwnerKind::Static(m),
Node::Expr(&Expr { kind: ExprKind::Closure(..), .. }) => BodyOwnerKind::Closure,
node => bug!("{:#?} is not a body node", node),
}
}
2020-05-07 10:22:35 -07:00
/// Returns the `ConstContext` of the body associated with this `LocalDefId`.
///
/// Panics if `LocalDefId` does not have an associated body.
pub fn body_const_context(&self, did: LocalDefId) -> Option<ConstContext> {
let hir_id = self.local_def_id_to_hir_id(did);
let ccx = match self.body_owner_kind(hir_id) {
BodyOwnerKind::Const => ConstContext::Const,
BodyOwnerKind::Static(mt) => ConstContext::Static(mt),
BodyOwnerKind::Fn if self.tcx.is_constructor(did.to_def_id()) => return None,
BodyOwnerKind::Fn if self.tcx.is_const_fn_raw(did.to_def_id()) => ConstContext::ConstFn,
BodyOwnerKind::Fn | BodyOwnerKind::Closure => return None,
};
Some(ccx)
}
pub fn ty_param_owner(&self, id: HirId) -> HirId {
2019-06-20 10:39:19 +02:00
match self.get(id) {
Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => id,
Node::GenericParam(_) => self.get_parent_node(id),
2019-12-22 17:42:04 -05:00
_ => bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id)),
}
}
2020-04-19 13:00:18 +02:00
pub fn ty_param_name(&self, id: HirId) -> Symbol {
2019-06-20 10:39:19 +02:00
match self.get(id) {
Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => {
kw::SelfUpper
}
2018-08-25 15:56:16 +01:00
Node::GenericParam(param) => param.name.ident().name,
_ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
}
}
pub fn trait_impls(&self, trait_did: DefId) -> &'hir [LocalDefId] {
2020-02-08 04:14:29 +01:00
self.tcx.all_local_trait_impls(LOCAL_CRATE).get(&trait_did).map_or(&[], |xs| &xs[..])
}
2019-02-08 14:53:55 +01:00
/// Gets the attributes on the crate. This is preferable to
/// invoking `krate.attrs` because it registers a tighter
/// dep-graph access.
2017-01-26 03:21:50 +02:00
pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
self.attrs(CRATE_HIR_ID)
}
pub fn get_module(&self, module: LocalDefId) -> (&'hir Mod<'hir>, Span, HirId) {
let hir_id = self.local_def_id_to_hir_id(module);
match self.get(hir_id) {
2019-12-22 17:42:04 -05:00
Node::Item(&Item { span, kind: ItemKind::Mod(ref m), .. }) => (m, span, hir_id),
2021-03-30 20:31:06 +02:00
Node::Crate(item) => (&item, item.inner, hir_id),
2019-08-21 16:11:01 -07:00
node => panic!("not a module: {:?}", node),
}
}
2020-06-27 13:09:54 +02:00
pub fn visit_item_likes_in_module<V>(&self, module: LocalDefId, visitor: &mut V)
2019-12-22 17:42:04 -05:00
where
V: ItemLikeVisitor<'hir>,
2018-06-06 22:13:52 +02:00
{
2020-06-27 13:09:54 +02:00
let module = self.tcx.hir_module_items(module);
2018-06-06 22:13:52 +02:00
for id in &module.items {
2021-01-30 12:06:04 +01:00
visitor.visit_item(self.item(*id));
2018-06-06 22:13:52 +02:00
}
for id in &module.trait_items {
2021-01-30 12:06:04 +01:00
visitor.visit_trait_item(self.trait_item(*id));
2018-06-06 22:13:52 +02:00
}
for id in &module.impl_items {
2021-01-30 12:06:04 +01:00
visitor.visit_impl_item(self.impl_item(*id));
2018-06-06 22:13:52 +02:00
}
2020-11-11 21:57:54 +01:00
for id in &module.foreign_items {
2021-01-30 12:06:04 +01:00
visitor.visit_foreign_item(self.foreign_item(*id));
2020-11-11 21:57:54 +01:00
}
2018-06-06 22:13:52 +02:00
}
pub fn visit_exported_macros_in_krate<V>(&self, visitor: &mut V)
where
V: Visitor<'hir>,
{
for id in self.krate().exported_macros {
visitor.visit_macro_def(self.expect_macro_def(id.hir_id()));
}
}
/// Returns an iterator for the nodes in the ancestor tree of the `current_id`
/// until the crate root is reached. Prefer this over your own loop using `get_parent_node`.
pub fn parent_iter(&self, current_id: HirId) -> ParentHirIterator<'_, 'hir> {
ParentHirIterator { current_id, map: self }
}
/// Returns an iterator for the nodes in the ancestor tree of the `current_id`
/// until the crate root is reached. Prefer this over your own loop using `get_parent_node`.
pub fn parent_owner_iter(&self, current_id: HirId) -> ParentOwnerIterator<'_, 'hir> {
ParentOwnerIterator { current_id, map: self }
}
/// Checks if the node is left-hand side of an assignment.
pub fn is_lhs(&self, id: HirId) -> bool {
match self.find(self.get_parent_node(id)) {
Some(Node::Expr(expr)) => match expr.kind {
ExprKind::Assign(lhs, _rhs, _span) => lhs.hir_id == id,
_ => false,
},
_ => false,
}
}
2019-08-13 11:24:08 -07:00
/// Whether the expression pointed at by `hir_id` belongs to a `const` evaluation context.
/// Used exclusively for diagnostics, to avoid suggestion function calls.
pub fn is_inside_const_context(&self, hir_id: HirId) -> bool {
2020-05-20 14:57:16 +02:00
self.body_const_context(self.local_def_id(self.enclosing_body_owner(hir_id))).is_some()
}
2020-03-06 12:13:55 +01:00
/// Whether `hir_id` corresponds to a `mod` or a crate.
2019-08-21 16:11:01 -07:00
pub fn is_hir_id_module(&self, hir_id: HirId) -> bool {
matches!(
self.get(hir_id),
Node::Item(Item { kind: ItemKind::Mod(_), .. }) | Node::Crate(..)
)
2019-08-21 16:11:01 -07:00
}
/// Retrieves the `HirId` for `id`'s enclosing method, unless there's a
/// `while` or `loop` before reaching it, as block tail returns are not
/// available in them.
///
/// ```
/// fn foo(x: usize) -> bool {
/// if x == 1 {
/// true // If `get_return_block` gets passed the `id` corresponding
/// } else { // to this, it will return `foo`'s `HirId`.
/// false
/// }
/// }
/// ```
///
/// ```
/// fn foo(x: usize) -> bool {
/// loop {
/// true // If `get_return_block` gets passed the `id` corresponding
/// } // to this, it will return `None`.
/// false
/// }
/// ```
2019-02-24 09:33:17 +01:00
pub fn get_return_block(&self, id: HirId) -> Option<HirId> {
let mut iter = self.parent_iter(id).peekable();
let mut ignore_tail = false;
if let Some(node) = self.find(id) {
if let Node::Expr(Expr { kind: ExprKind::Ret(_), .. }) = node {
// When dealing with `return` statements, we don't care about climbing only tail
// expressions.
ignore_tail = true;
}
}
while let Some((hir_id, node)) = iter.next() {
if let (Some((_, next_node)), false) = (iter.peek(), ignore_tail) {
match next_node {
Node::Block(Block { expr: None, .. }) => return None,
2020-03-24 06:17:44 +01:00
// The current node is not the tail expression of its parent.
Node::Block(Block { expr: Some(e), .. }) if hir_id != e.hir_id => return None,
_ => {}
}
}
match node {
2019-12-22 17:42:04 -05:00
Node::Item(_)
| Node::ForeignItem(_)
| Node::TraitItem(_)
| Node::Expr(Expr { kind: ExprKind::Closure(..), .. })
| Node::ImplItem(_) => return Some(hir_id),
2020-03-24 06:17:44 +01:00
// Ignore `return`s on the first iteration
Node::Expr(Expr { kind: ExprKind::Loop(..) | ExprKind::Ret(..), .. })
| Node::Local(_) => {
return None;
}
_ => {}
}
}
None
}
2019-06-14 12:28:47 +02:00
/// Retrieves the `HirId` for `id`'s parent item, or `id` itself if no
2015-07-01 08:58:48 +12:00
/// parent item is in this map. The "parent item" is the closest parent node
2018-06-13 09:11:23 +02:00
/// in the HIR which is recorded by the map and is an item, either an item
2015-07-01 08:58:48 +12:00
/// in a module, trait, or impl.
pub fn get_parent_item(&self, hir_id: HirId) -> HirId {
for (hir_id, node) in self.parent_owner_iter(hir_id) {
if let Node::Crate(_)
| Node::Item(_)
| Node::ForeignItem(_)
| Node::TraitItem(_)
| Node::ImplItem(_) = node
{
return hir_id;
}
2015-07-01 08:58:48 +12:00
}
CRATE_HIR_ID
2015-06-16 21:56:33 +12:00
}
/// Returns the `HirId` of `id`'s nearest module parent, or `id` itself if no
2018-09-19 09:28:49 -05:00
/// module parent is in this map.
pub(super) fn get_module_parent_node(&self, hir_id: HirId) -> HirId {
for (hir_id, node) in self.parent_owner_iter(hir_id) {
if let Node::Item(&Item { kind: ItemKind::Mod(_), .. }) = node {
return hir_id;
}
2018-09-19 09:28:49 -05:00
}
CRATE_HIR_ID
}
2021-01-01 15:38:11 -03:00
/// When on an if expression, a match arm tail expression or a match arm, give back
/// the enclosing `if` or `match` expression.
2019-09-27 18:35:34 -07:00
///
2021-01-01 15:38:11 -03:00
/// Used by error reporting when there's a type error in an if or match arm caused by the
2019-09-27 18:35:34 -07:00
/// expression needing to be unit.
2021-01-01 15:38:11 -03:00
pub fn get_if_cause(&self, hir_id: HirId) -> Option<&'hir Expr<'hir>> {
for (_, node) in self.parent_iter(hir_id) {
match node {
2020-03-24 06:17:44 +01:00
Node::Item(_)
| Node::ForeignItem(_)
| Node::TraitItem(_)
| Node::ImplItem(_)
| Node::Stmt(Stmt { kind: StmtKind::Local(_), .. }) => break,
2021-01-01 15:38:11 -03:00
Node::Expr(expr @ Expr { kind: ExprKind::If(..) | ExprKind::Match(..), .. }) => {
return Some(expr);
}
_ => {}
}
}
None
}
/// Returns the nearest enclosing scope. A scope is roughly an item or block.
2019-05-04 16:09:28 +01:00
pub fn get_enclosing_scope(&self, hir_id: HirId) -> Option<HirId> {
for (hir_id, node) in self.parent_iter(hir_id) {
2020-03-24 06:17:44 +01:00
if let Node::Item(Item {
kind:
2019-12-22 17:42:04 -05:00
ItemKind::Fn(..)
2020-05-10 11:57:58 +01:00
| ItemKind::Const(..)
| ItemKind::Static(..)
2019-12-22 17:42:04 -05:00
| ItemKind::Mod(..)
| ItemKind::Enum(..)
| ItemKind::Struct(..)
| ItemKind::Union(..)
| ItemKind::Trait(..)
2020-03-24 06:17:44 +01:00
| ItemKind::Impl { .. },
..
})
| Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(..), .. })
| Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(..), .. })
| Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(..), .. })
| Node::Block(_) = node
{
return Some(hir_id);
}
}
None
}
2019-08-01 00:41:54 +01:00
/// Returns the defining scope for an opaque type definition.
2019-09-26 14:38:01 -07:00
pub fn get_defining_scope(&self, id: HirId) -> HirId {
let mut scope = id;
loop {
scope = self.get_enclosing_scope(scope).unwrap_or(CRATE_HIR_ID);
2021-01-10 14:38:14 +01:00
if scope == CRATE_HIR_ID || !matches!(self.get(scope), Node::Block(_)) {
return scope;
}
}
}
pub fn get_parent_did(&self, id: HirId) -> LocalDefId {
self.local_def_id(self.get_parent_item(id))
2019-02-04 11:09:32 +01:00
}
pub fn get_foreign_abi(&self, hir_id: HirId) -> Abi {
let parent = self.get_parent_item(hir_id);
if let Some(node) = self.find(parent) {
if let Node::Item(Item { kind: ItemKind::ForeignMod { abi, .. }, .. }) = node {
2020-11-11 22:40:09 +01:00
return *abi;
}
}
bug!("expected foreign mod or inlined parent, found {}", self.node_to_string(parent))
2019-02-04 11:09:32 +01:00
}
2019-11-28 19:28:50 +01:00
pub fn expect_item(&self, id: HirId) -> &'hir Item<'hir> {
2019-12-22 17:42:04 -05:00
match self.find(id) {
Some(Node::Item(item)) => item,
2019-12-22 17:42:04 -05:00
_ => bug!("expected item, found {}", self.node_to_string(id)),
}
2019-02-03 09:14:31 +01:00
}
2019-11-28 22:16:44 +01:00
pub fn expect_impl_item(&self, id: HirId) -> &'hir ImplItem<'hir> {
2019-06-24 09:58:49 +02:00
match self.find(id) {
2018-08-25 15:56:16 +01:00
Some(Node::ImplItem(item)) => item,
2019-12-22 17:42:04 -05:00
_ => bug!("expected impl item, found {}", self.node_to_string(id)),
}
}
2019-11-28 21:47:10 +01:00
pub fn expect_trait_item(&self, id: HirId) -> &'hir TraitItem<'hir> {
2019-06-24 09:58:49 +02:00
match self.find(id) {
2018-08-25 15:56:16 +01:00
Some(Node::TraitItem(item)) => item,
2019-12-22 17:42:04 -05:00
_ => bug!("expected trait item, found {}", self.node_to_string(id)),
}
}
2019-11-29 09:26:18 +01:00
pub fn expect_variant(&self, id: HirId) -> &'hir Variant<'hir> {
2019-06-24 09:58:49 +02:00
match self.find(id) {
2018-08-25 15:56:16 +01:00
Some(Node::Variant(variant)) => variant,
_ => bug!("expected variant, found {}", self.node_to_string(id)),
}
}
2019-11-28 20:18:29 +01:00
pub fn expect_foreign_item(&self, id: HirId) -> &'hir ForeignItem<'hir> {
2019-06-24 09:58:49 +02:00
match self.find(id) {
2018-08-25 15:56:16 +01:00
Some(Node::ForeignItem(item)) => item,
2019-12-22 17:42:04 -05:00
_ => bug!("expected foreign item, found {}", self.node_to_string(id)),
}
}
pub fn expect_macro_def(&self, id: HirId) -> &'hir MacroDef<'hir> {
match self.find(id) {
Some(Node::MacroDef(macro_def)) => macro_def,
_ => bug!("expected macro def, found {}", self.node_to_string(id)),
}
}
2019-11-29 13:43:03 +01:00
pub fn expect_expr(&self, id: HirId) -> &'hir Expr<'hir> {
2019-12-22 17:42:04 -05:00
match self.find(id) {
Some(Node::Expr(expr)) => expr,
2019-12-22 17:42:04 -05:00
_ => bug!("expected expr, found {}", self.node_to_string(id)),
}
2019-02-04 11:09:32 +01:00
}
2020-04-19 13:00:18 +02:00
pub fn opt_name(&self, id: HirId) -> Option<Symbol> {
2019-12-13 15:27:55 -08:00
Some(match self.get(id) {
Node::Item(i) => i.ident.name,
Node::ForeignItem(fi) => fi.ident.name,
2018-08-25 15:56:16 +01:00
Node::ImplItem(ii) => ii.ident.name,
Node::TraitItem(ti) => ti.ident.name,
2019-08-13 21:40:21 -03:00
Node::Variant(v) => v.ident.name,
2018-08-25 15:56:16 +01:00
Node::Field(f) => f.ident.name,
Node::Lifetime(lt) => lt.name.ident().name,
Node::GenericParam(param) => param.name.ident().name,
2019-09-26 16:18:31 +01:00
Node::Binding(&Pat { kind: PatKind::Binding(_, _, l, _), .. }) => l.name,
Node::Ctor(..) => self.name(self.get_parent_item(id)),
Node::MacroDef(md) => md.ident.name,
2019-12-13 15:27:55 -08:00
_ => return None,
})
}
2020-04-19 13:00:18 +02:00
pub fn name(&self, id: HirId) -> Symbol {
2019-12-13 15:27:55 -08:00
match self.opt_name(id) {
Some(name) => name,
None => bug!("no name for {}", self.node_to_string(id)),
}
}
/// Given a node ID, gets a list of attributes associated with the AST
/// corresponding to the node-ID.
pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] {
2021-01-24 17:14:17 +01:00
self.tcx.hir_attrs(id.owner).get(id.local_id)
}
Use smaller def span for functions Currently, the def span of a funtion encompasses the entire function signature and body. However, this is usually unnecessarily verbose - when we are pointing at an entire function in a diagnostic, we almost always want to point at the signature. The actual contents of the body tends to be irrelevant to the diagnostic we are emitting, and just takes up additional screen space. This commit changes the `def_span` of all function items (freestanding functions, `impl`-block methods, and `trait`-block methods) to be the span of the signature. For example, the function ```rust pub fn foo<T>(val: T) -> T { val } ``` now has a `def_span` corresponding to `pub fn foo<T>(val: T) -> T` (everything before the opening curly brace). Trait methods without a body have a `def_span` which includes the trailing semicolon. For example: ```rust trait Foo { fn bar(); }``` the function definition `Foo::bar` has a `def_span` of `fn bar();` This makes our diagnostic output much shorter, and emphasizes information that is relevant to whatever diagnostic we are reporting. We continue to use the full span (including the body) in a few of places: * MIR building uses the full span when building source scopes. * 'Outlives suggestions' use the full span to sort the diagnostics being emitted. * The `#[rustc_on_unimplemented(enclosing_scope="in this scope")]` attribute points the entire scope body. * The 'unconditional recursion' lint uses the full span to show additional context for the recursive call. All of these cases work only with local items, so we don't need to add anything extra to crate metadata.
2020-08-12 17:02:14 -04:00
/// Gets the span of the definition of the specified HIR node.
/// This is used by `tcx.get_span`
pub fn span(&self, hir_id: HirId) -> Span {
2020-12-23 10:32:00 +01:00
self.opt_span(hir_id)
.unwrap_or_else(|| bug!("hir::map::Map::span: id not in map: {:?}", hir_id))
}
pub fn opt_span(&self, hir_id: HirId) -> Option<Span> {
let span = match self.find(hir_id)? {
2020-12-23 10:32:00 +01:00
Node::Param(param) => param.span,
Node::Item(item) => match &item.kind {
Use smaller def span for functions Currently, the def span of a funtion encompasses the entire function signature and body. However, this is usually unnecessarily verbose - when we are pointing at an entire function in a diagnostic, we almost always want to point at the signature. The actual contents of the body tends to be irrelevant to the diagnostic we are emitting, and just takes up additional screen space. This commit changes the `def_span` of all function items (freestanding functions, `impl`-block methods, and `trait`-block methods) to be the span of the signature. For example, the function ```rust pub fn foo<T>(val: T) -> T { val } ``` now has a `def_span` corresponding to `pub fn foo<T>(val: T) -> T` (everything before the opening curly brace). Trait methods without a body have a `def_span` which includes the trailing semicolon. For example: ```rust trait Foo { fn bar(); }``` the function definition `Foo::bar` has a `def_span` of `fn bar();` This makes our diagnostic output much shorter, and emphasizes information that is relevant to whatever diagnostic we are reporting. We continue to use the full span (including the body) in a few of places: * MIR building uses the full span when building source scopes. * 'Outlives suggestions' use the full span to sort the diagnostics being emitted. * The `#[rustc_on_unimplemented(enclosing_scope="in this scope")]` attribute points the entire scope body. * The 'unconditional recursion' lint uses the full span to show additional context for the recursive call. All of these cases work only with local items, so we don't need to add anything extra to crate metadata.
2020-08-12 17:02:14 -04:00
ItemKind::Fn(sig, _, _) => sig.span,
_ => item.span,
},
2020-12-23 10:32:00 +01:00
Node::ForeignItem(foreign_item) => foreign_item.span,
Node::TraitItem(trait_item) => match &trait_item.kind {
Use smaller def span for functions Currently, the def span of a funtion encompasses the entire function signature and body. However, this is usually unnecessarily verbose - when we are pointing at an entire function in a diagnostic, we almost always want to point at the signature. The actual contents of the body tends to be irrelevant to the diagnostic we are emitting, and just takes up additional screen space. This commit changes the `def_span` of all function items (freestanding functions, `impl`-block methods, and `trait`-block methods) to be the span of the signature. For example, the function ```rust pub fn foo<T>(val: T) -> T { val } ``` now has a `def_span` corresponding to `pub fn foo<T>(val: T) -> T` (everything before the opening curly brace). Trait methods without a body have a `def_span` which includes the trailing semicolon. For example: ```rust trait Foo { fn bar(); }``` the function definition `Foo::bar` has a `def_span` of `fn bar();` This makes our diagnostic output much shorter, and emphasizes information that is relevant to whatever diagnostic we are reporting. We continue to use the full span (including the body) in a few of places: * MIR building uses the full span when building source scopes. * 'Outlives suggestions' use the full span to sort the diagnostics being emitted. * The `#[rustc_on_unimplemented(enclosing_scope="in this scope")]` attribute points the entire scope body. * The 'unconditional recursion' lint uses the full span to show additional context for the recursive call. All of these cases work only with local items, so we don't need to add anything extra to crate metadata.
2020-08-12 17:02:14 -04:00
TraitItemKind::Fn(sig, _) => sig.span,
_ => trait_item.span,
},
2020-12-23 10:32:00 +01:00
Node::ImplItem(impl_item) => match &impl_item.kind {
Use smaller def span for functions Currently, the def span of a funtion encompasses the entire function signature and body. However, this is usually unnecessarily verbose - when we are pointing at an entire function in a diagnostic, we almost always want to point at the signature. The actual contents of the body tends to be irrelevant to the diagnostic we are emitting, and just takes up additional screen space. This commit changes the `def_span` of all function items (freestanding functions, `impl`-block methods, and `trait`-block methods) to be the span of the signature. For example, the function ```rust pub fn foo<T>(val: T) -> T { val } ``` now has a `def_span` corresponding to `pub fn foo<T>(val: T) -> T` (everything before the opening curly brace). Trait methods without a body have a `def_span` which includes the trailing semicolon. For example: ```rust trait Foo { fn bar(); }``` the function definition `Foo::bar` has a `def_span` of `fn bar();` This makes our diagnostic output much shorter, and emphasizes information that is relevant to whatever diagnostic we are reporting. We continue to use the full span (including the body) in a few of places: * MIR building uses the full span when building source scopes. * 'Outlives suggestions' use the full span to sort the diagnostics being emitted. * The `#[rustc_on_unimplemented(enclosing_scope="in this scope")]` attribute points the entire scope body. * The 'unconditional recursion' lint uses the full span to show additional context for the recursive call. All of these cases work only with local items, so we don't need to add anything extra to crate metadata.
2020-08-12 17:02:14 -04:00
ImplItemKind::Fn(sig, _) => sig.span,
_ => impl_item.span,
},
2020-12-23 10:32:00 +01:00
Node::Variant(variant) => variant.span,
Node::Field(field) => field.span,
Node::AnonConst(constant) => self.body(constant.body).value.span,
Node::Expr(expr) => expr.span,
Node::Stmt(stmt) => stmt.span,
Node::PathSegment(seg) => seg.ident.span,
Node::Ty(ty) => ty.span,
Node::TraitRef(tr) => tr.path.span,
Node::Binding(pat) => pat.span,
Node::Pat(pat) => pat.span,
Node::Arm(arm) => arm.span,
Node::Block(block) => block.span,
Node::Ctor(..) => match self.find(self.get_parent_node(hir_id))? {
Node::Item(item) => item.span,
Node::Variant(variant) => variant.span,
_ => unreachable!(),
2019-12-22 17:42:04 -05:00
},
2020-12-23 10:32:00 +01:00
Node::Lifetime(lifetime) => lifetime.span,
Node::GenericParam(param) => param.span,
Node::Visibility(&Spanned {
2019-12-22 17:42:04 -05:00
node: VisibilityKind::Restricted { ref path, .. },
..
2020-12-23 10:32:00 +01:00
}) => path.span,
Node::Visibility(v) => bug!("unexpected Visibility {:?}", v),
Node::Local(local) => local.span,
Node::MacroDef(macro_def) => macro_def.span,
2021-03-30 20:31:06 +02:00
Node::Crate(item) => item.inner,
2020-12-23 10:32:00 +01:00
};
Some(span)
}
Use smaller def span for functions Currently, the def span of a funtion encompasses the entire function signature and body. However, this is usually unnecessarily verbose - when we are pointing at an entire function in a diagnostic, we almost always want to point at the signature. The actual contents of the body tends to be irrelevant to the diagnostic we are emitting, and just takes up additional screen space. This commit changes the `def_span` of all function items (freestanding functions, `impl`-block methods, and `trait`-block methods) to be the span of the signature. For example, the function ```rust pub fn foo<T>(val: T) -> T { val } ``` now has a `def_span` corresponding to `pub fn foo<T>(val: T) -> T` (everything before the opening curly brace). Trait methods without a body have a `def_span` which includes the trailing semicolon. For example: ```rust trait Foo { fn bar(); }``` the function definition `Foo::bar` has a `def_span` of `fn bar();` This makes our diagnostic output much shorter, and emphasizes information that is relevant to whatever diagnostic we are reporting. We continue to use the full span (including the body) in a few of places: * MIR building uses the full span when building source scopes. * 'Outlives suggestions' use the full span to sort the diagnostics being emitted. * The `#[rustc_on_unimplemented(enclosing_scope="in this scope")]` attribute points the entire scope body. * The 'unconditional recursion' lint uses the full span to show additional context for the recursive call. All of these cases work only with local items, so we don't need to add anything extra to crate metadata.
2020-08-12 17:02:14 -04:00
/// Like `hir.span()`, but includes the body of function items
/// (instead of just the function header)
pub fn span_with_body(&self, hir_id: HirId) -> Span {
match self.find(hir_id) {
Use smaller def span for functions Currently, the def span of a funtion encompasses the entire function signature and body. However, this is usually unnecessarily verbose - when we are pointing at an entire function in a diagnostic, we almost always want to point at the signature. The actual contents of the body tends to be irrelevant to the diagnostic we are emitting, and just takes up additional screen space. This commit changes the `def_span` of all function items (freestanding functions, `impl`-block methods, and `trait`-block methods) to be the span of the signature. For example, the function ```rust pub fn foo<T>(val: T) -> T { val } ``` now has a `def_span` corresponding to `pub fn foo<T>(val: T) -> T` (everything before the opening curly brace). Trait methods without a body have a `def_span` which includes the trailing semicolon. For example: ```rust trait Foo { fn bar(); }``` the function definition `Foo::bar` has a `def_span` of `fn bar();` This makes our diagnostic output much shorter, and emphasizes information that is relevant to whatever diagnostic we are reporting. We continue to use the full span (including the body) in a few of places: * MIR building uses the full span when building source scopes. * 'Outlives suggestions' use the full span to sort the diagnostics being emitted. * The `#[rustc_on_unimplemented(enclosing_scope="in this scope")]` attribute points the entire scope body. * The 'unconditional recursion' lint uses the full span to show additional context for the recursive call. All of these cases work only with local items, so we don't need to add anything extra to crate metadata.
2020-08-12 17:02:14 -04:00
Some(Node::TraitItem(item)) => item.span,
Some(Node::ImplItem(impl_item)) => impl_item.span,
Some(Node::Item(item)) => item.span,
Some(_) => self.span(hir_id),
_ => bug!("hir::map::Map::span_with_body: id not in map: {:?}", hir_id),
}
}
pub fn span_if_local(&self, id: DefId) -> Option<Span> {
2020-12-23 10:32:00 +01:00
id.as_local().and_then(|id| self.opt_span(self.local_def_id_to_hir_id(id)))
}
pub fn res_span(&self, res: Res) -> Option<Span> {
match res {
Res::Err => None,
Res::Local(id) => Some(self.span(id)),
res => self.span_if_local(res.opt_def_id()?),
}
}
/// Get a representation of this `id` for debugging purposes.
/// NOTE: Do NOT use this in diagnostics!
pub fn node_to_string(&self, id: HirId) -> String {
hir_id_to_string(self, id)
2019-02-03 09:14:31 +01:00
}
}
2020-01-07 17:25:33 +01:00
impl<'hir> intravisit::Map<'hir> for Map<'hir> {
fn find(&self, hir_id: HirId) -> Option<Node<'hir>> {
self.find(hir_id)
}
2020-01-07 17:25:33 +01:00
fn body(&self, id: BodyId) -> &'hir Body<'hir> {
self.body(id)
}
2021-01-30 12:06:04 +01:00
fn item(&self, id: ItemId) -> &'hir Item<'hir> {
2020-01-07 17:25:33 +01:00
self.item(id)
}
fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
self.trait_item(id)
}
fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
self.impl_item(id)
}
2020-11-11 21:57:54 +01:00
fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
self.foreign_item(id)
}
2020-01-07 17:25:33 +01:00
}
2020-02-09 15:32:00 +01:00
pub(super) fn index_hir<'tcx>(tcx: TyCtxt<'tcx>, cnum: CrateNum) -> &'tcx IndexedHir<'tcx> {
assert_eq!(cnum, LOCAL_CRATE);
let _prof_timer = tcx.sess.prof.generic_activity("build_hir_map");
2021-03-05 20:09:33 +01:00
let hcx = tcx.create_stable_hashing_context();
let mut collector =
NodeCollector::root(tcx.sess, &**tcx.arena, tcx.untracked_crate, &tcx.definitions, hcx);
intravisit::walk_crate(&mut collector, tcx.untracked_crate);
2021-03-05 20:09:33 +01:00
let map = collector.finalize_and_compute_crate_hash();
tcx.arena.alloc(map)
2021-02-28 18:58:50 +01:00
}
pub(super) fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
let mut hir_body_nodes: Vec<_> = tcx
.index_hir(crate_num)
.map
.iter_enumerated()
.filter_map(|(def_id, hod)| {
let def_path_hash = tcx.definitions.def_path_hash(def_id);
let hash = hod.with_bodies.as_ref()?.hash;
Some((def_path_hash, hash))
})
.collect();
hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
let node_hashes = hir_body_nodes.iter().fold(
Fingerprint::ZERO,
|combined_fingerprint, &(def_path_hash, fingerprint)| {
combined_fingerprint.combine(def_path_hash.0.combine(fingerprint))
},
);
let upstream_crates = upstream_crates(&*tcx.cstore);
// We hash the final, remapped names of all local source files so we
// don't have to include the path prefix remapping commandline args.
// If we included the full mapping in the SVH, we could only have
// reproducible builds by compiling from the same directory. So we just
// hash the result of the mapping instead of the mapping itself.
let mut source_file_names: Vec<_> = tcx
.sess
.source_map()
.files()
.iter()
.filter(|source_file| source_file.cnum == LOCAL_CRATE)
.map(|source_file| source_file.name_hash)
.collect();
source_file_names.sort_unstable();
let mut hcx = tcx.create_stable_hashing_context();
let mut stable_hasher = StableHasher::new();
node_hashes.hash_stable(&mut hcx, &mut stable_hasher);
upstream_crates.hash_stable(&mut hcx, &mut stable_hasher);
source_file_names.hash_stable(&mut hcx, &mut stable_hasher);
tcx.sess.opts.dep_tracking_hash(true).hash_stable(&mut hcx, &mut stable_hasher);
tcx.sess.local_crate_disambiguator().to_fingerprint().hash_stable(&mut hcx, &mut stable_hasher);
let crate_hash: Fingerprint = stable_hasher.finish();
Svh::new(crate_hash.to_smaller_hash())
}
fn upstream_crates(cstore: &dyn CrateStore) -> Vec<(Symbol, Fingerprint, Svh)> {
let mut upstream_crates: Vec<_> = cstore
.crates_untracked()
.iter()
.map(|&cnum| {
let name = cstore.crate_name_untracked(cnum);
let disambiguator = cstore.crate_disambiguator_untracked(cnum).to_fingerprint();
let hash = cstore.crate_hash_untracked(cnum);
(name, disambiguator, hash)
})
.collect();
upstream_crates.sort_unstable_by_key(|&(name, dis, _)| (name.as_str(), dis));
upstream_crates
}
fn hir_id_to_string(map: &Map<'_>, id: HirId) -> String {
let id_str = format!(" (hir_id={})", id);
2016-04-06 13:51:55 +03:00
let path_str = || {
// This functionality is used for debugging, try to use `TyCtxt` to get
// the user-friendly path, otherwise fall back to stringifying `DefPath`.
2019-02-05 11:20:45 -06:00
crate::ty::tls::with_opt(|tcx| {
2016-04-06 13:51:55 +03:00
if let Some(tcx) = tcx {
let def_id = map.local_def_id(id);
tcx.def_path_str(def_id.to_def_id())
} else if let Some(path) = map.def_path_from_hir_id(id) {
path.data.into_iter().map(|elem| elem.to_string()).collect::<Vec<_>>().join("::")
2016-04-06 13:51:55 +03:00
} else {
String::from("<missing path>")
}
})
};
let span_str = || map.tcx.sess.source_map().span_to_snippet(map.span(id)).unwrap_or_default();
let node_str = |prefix| format!("{} {}{}", prefix, span_str(), id_str);
2019-06-24 09:58:49 +02:00
match map.find(id) {
2018-08-25 15:56:16 +01:00
Some(Node::Item(item)) => {
2019-09-26 17:51:36 +01:00
let item_str = match item.kind {
2018-07-11 23:36:06 +08:00
ItemKind::ExternCrate(..) => "extern crate",
ItemKind::Use(..) => "use",
ItemKind::Static(..) => "static",
ItemKind::Const(..) => "const",
ItemKind::Fn(..) => "fn",
ItemKind::Mod(..) => "mod",
2020-11-11 22:40:09 +01:00
ItemKind::ForeignMod { .. } => "foreign mod",
2018-07-11 23:36:06 +08:00
ItemKind::GlobalAsm(..) => "global asm",
ItemKind::TyAlias(..) => "ty",
2019-08-01 00:41:54 +01:00
ItemKind::OpaqueTy(..) => "opaque type",
2018-07-11 23:36:06 +08:00
ItemKind::Enum(..) => "enum",
ItemKind::Struct(..) => "struct",
ItemKind::Union(..) => "union",
ItemKind::Trait(..) => "trait",
ItemKind::TraitAlias(..) => "trait alias",
ItemKind::Impl { .. } => "impl",
};
2016-04-06 13:51:55 +03:00
format!("{} {}{}", item_str, path_str(), id_str)
}
2019-12-22 17:42:04 -05:00
Some(Node::ForeignItem(_)) => format!("foreign item {}{}", path_str(), id_str),
Some(Node::ImplItem(ii)) => match ii.kind {
ImplItemKind::Const(..) => {
format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
}
2020-03-05 09:57:34 -06:00
ImplItemKind::Fn(..) => format!("method {} in {}{}", ii.ident, path_str(), id_str),
2019-12-22 17:42:04 -05:00
ImplItemKind::TyAlias(_) => {
format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
}
},
2018-08-25 15:56:16 +01:00
Some(Node::TraitItem(ti)) => {
let kind = match ti.kind {
TraitItemKind::Const(..) => "assoc constant",
2020-03-03 12:46:22 -06:00
TraitItemKind::Fn(..) => "trait method",
TraitItemKind::Type(..) => "assoc type",
};
format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
}
2018-08-25 15:56:16 +01:00
Some(Node::Variant(ref variant)) => {
2019-12-22 17:42:04 -05:00
format!("variant {} in {}{}", variant.ident, path_str(), id_str)
}
2018-08-25 15:56:16 +01:00
Some(Node::Field(ref field)) => {
2019-12-22 17:42:04 -05:00
format!("field {} in {}{}", field.ident, path_str(), id_str)
}
Some(Node::AnonConst(_)) => node_str("const"),
Some(Node::Expr(_)) => node_str("expr"),
Some(Node::Stmt(_)) => node_str("stmt"),
Some(Node::PathSegment(_)) => node_str("path segment"),
Some(Node::Ty(_)) => node_str("type"),
Some(Node::TraitRef(_)) => node_str("trait ref"),
Some(Node::Binding(_)) => node_str("local"),
Some(Node::Pat(_)) => node_str("pat"),
Some(Node::Param(_)) => node_str("param"),
Some(Node::Arm(_)) => node_str("arm"),
Some(Node::Block(_)) => node_str("block"),
Some(Node::Local(_)) => node_str("local"),
2019-12-22 17:42:04 -05:00
Some(Node::Ctor(..)) => format!("ctor {}{}", path_str(), id_str),
Some(Node::Lifetime(_)) => node_str("lifetime"),
2019-12-22 17:42:04 -05:00
Some(Node::GenericParam(ref param)) => format!("generic_param {:?}{}", param, id_str),
Some(Node::Visibility(ref vis)) => format!("visibility {:?}{}", vis, id_str),
Some(Node::MacroDef(_)) => format!("macro {}{}", path_str(), id_str),
2020-02-07 16:43:36 +01:00
Some(Node::Crate(..)) => String::from("root_crate"),
2018-08-25 15:48:42 +01:00
None => format!("unknown node{}", id_str),
}
}