1 use self::collector::NodeCollector;
3 use crate::hir::{AttributeMap, IndexedHir};
6 use rustc_data_structures::fingerprint::Fingerprint;
7 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
8 use rustc_data_structures::svh::Svh;
9 use rustc_hir::def::{DefKind, Res};
10 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
11 use rustc_hir::definitions::{DefKey, DefPath, DefPathHash};
12 use rustc_hir::intravisit;
13 use rustc_hir::intravisit::Visitor;
14 use rustc_hir::itemlikevisit::ItemLikeVisitor;
16 use rustc_index::vec::Idx;
17 use rustc_span::def_id::StableCrateId;
18 use rustc_span::hygiene::MacroKind;
19 use rustc_span::source_map::Spanned;
20 use rustc_span::symbol::{kw, sym, Ident, Symbol};
22 use rustc_target::spec::abi::Abi;
27 fn fn_decl<'hir>(node: Node<'hir>) -> Option<&'hir FnDecl<'hir>> {
29 Node::Item(Item { kind: ItemKind::Fn(sig, _, _), .. })
30 | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(sig, _), .. })
31 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(sig, _), .. }) => Some(&sig.decl),
32 Node::Expr(Expr { kind: ExprKind::Closure(_, fn_decl, ..), .. }) => Some(fn_decl),
37 pub fn fn_sig<'hir>(node: Node<'hir>) -> Option<&'hir FnSig<'hir>> {
39 Node::Item(Item { kind: ItemKind::Fn(sig, _, _), .. })
40 | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(sig, _), .. })
41 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(sig, _), .. }) => Some(sig),
46 pub fn associated_body<'hir>(node: Node<'hir>) -> Option<BodyId> {
49 kind: ItemKind::Const(_, body) | ItemKind::Static(.., body) | ItemKind::Fn(.., body),
52 | Node::TraitItem(TraitItem {
54 TraitItemKind::Const(_, Some(body)) | TraitItemKind::Fn(_, TraitFn::Provided(body)),
57 | Node::ImplItem(ImplItem {
58 kind: ImplItemKind::Const(_, body) | ImplItemKind::Fn(_, body),
61 | Node::Expr(Expr { kind: ExprKind::Closure(.., body, _, _), .. }) => Some(*body),
63 Node::AnonConst(constant) => Some(constant.body),
69 fn is_body_owner<'hir>(node: Node<'hir>, hir_id: HirId) -> bool {
70 match associated_body(node) {
71 Some(b) => b.hir_id == hir_id,
76 #[derive(Copy, Clone)]
77 pub struct Map<'hir> {
78 pub(super) tcx: TyCtxt<'hir>,
81 /// An iterator that walks up the ancestor tree of a given `HirId`.
82 /// Constructed using `tcx.hir().parent_iter(hir_id)`.
83 pub struct ParentHirIterator<'map, 'hir> {
88 impl<'hir> Iterator for ParentHirIterator<'_, 'hir> {
89 type Item = (HirId, Node<'hir>);
91 fn next(&mut self) -> Option<Self::Item> {
92 if self.current_id == CRATE_HIR_ID {
96 // There are nodes that do not have entries, so we need to skip them.
97 let parent_id = self.map.get_parent_node(self.current_id);
99 if parent_id == self.current_id {
100 self.current_id = CRATE_HIR_ID;
104 self.current_id = parent_id;
105 if let Some(node) = self.map.find(parent_id) {
106 return Some((parent_id, node));
108 // If this `HirId` doesn't have an entry, skip it and look for its `parent_id`.
113 /// An iterator that walks up the ancestor tree of a given `HirId`.
114 /// Constructed using `tcx.hir().parent_owner_iter(hir_id)`.
115 pub struct ParentOwnerIterator<'map, 'hir> {
117 map: &'map Map<'hir>,
120 impl<'hir> Iterator for ParentOwnerIterator<'_, 'hir> {
121 type Item = (HirId, Node<'hir>);
123 fn next(&mut self) -> Option<Self::Item> {
124 if self.current_id.local_id.index() != 0 {
125 self.current_id.local_id = ItemLocalId::new(0);
126 if let Some(node) = self.map.find(self.current_id) {
127 return Some((self.current_id, node));
130 if self.current_id == CRATE_HIR_ID {
134 // There are nodes that do not have entries, so we need to skip them.
135 let parent_id = self.map.def_key(self.current_id.owner).parent;
137 let parent_id = parent_id.map_or(CRATE_HIR_ID.owner, |local_def_index| {
138 let def_id = LocalDefId { local_def_index };
139 self.map.local_def_id_to_hir_id(def_id).owner
141 self.current_id = HirId::make_owner(parent_id);
143 // If this `HirId` doesn't have an entry, skip it and look for its `parent_id`.
144 if let Some(node) = self.map.find(self.current_id) {
145 return Some((self.current_id, node));
151 impl<'hir> Map<'hir> {
152 pub fn krate(&self) -> &'hir Crate<'hir> {
153 self.tcx.hir_crate(())
156 pub fn def_key(&self, def_id: LocalDefId) -> DefKey {
157 // Accessing the DefKey is ok, since it is part of DefPathHash.
158 self.tcx.untracked_resolutions.definitions.def_key(def_id)
161 pub fn def_path_from_hir_id(&self, id: HirId) -> Option<DefPath> {
162 self.opt_local_def_id(id).map(|def_id| self.def_path(def_id))
165 pub fn def_path(&self, def_id: LocalDefId) -> DefPath {
166 // Accessing the DefPath is ok, since it is part of DefPathHash.
167 self.tcx.untracked_resolutions.definitions.def_path(def_id)
171 pub fn def_path_hash(self, def_id: LocalDefId) -> DefPathHash {
172 // Accessing the DefPathHash is ok, it is incr. comp. stable.
173 self.tcx.untracked_resolutions.definitions.def_path_hash(def_id)
177 pub fn local_def_id(&self, hir_id: HirId) -> LocalDefId {
178 self.opt_local_def_id(hir_id).unwrap_or_else(|| {
180 "local_def_id: no entry for `{:?}`, which has a map of `{:?}`",
188 pub fn opt_local_def_id(&self, hir_id: HirId) -> Option<LocalDefId> {
189 // FIXME(#85914) is this access safe for incr. comp.?
190 self.tcx.untracked_resolutions.definitions.opt_hir_id_to_local_def_id(hir_id)
194 pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
195 // FIXME(#85914) is this access safe for incr. comp.?
196 self.tcx.untracked_resolutions.definitions.local_def_id_to_hir_id(def_id)
199 pub fn iter_local_def_id(&self) -> impl Iterator<Item = LocalDefId> + '_ {
200 // Create a dependency to the crate to be sure we reexcute this when the amount of
201 // definitions change.
202 self.tcx.ensure().hir_crate(());
203 self.tcx.untracked_resolutions.definitions.iter_local_def_id()
206 pub fn opt_def_kind(&self, local_def_id: LocalDefId) -> Option<DefKind> {
207 // FIXME(eddyb) support `find` on the crate root.
208 if local_def_id.to_def_id().index == CRATE_DEF_INDEX {
209 return Some(DefKind::Mod);
212 let hir_id = self.local_def_id_to_hir_id(local_def_id);
213 let def_kind = match self.find(hir_id)? {
214 Node::Item(item) => match item.kind {
215 ItemKind::Static(..) => DefKind::Static,
216 ItemKind::Const(..) => DefKind::Const,
217 ItemKind::Fn(..) => DefKind::Fn,
218 ItemKind::Mod(..) => DefKind::Mod,
219 ItemKind::OpaqueTy(..) => DefKind::OpaqueTy,
220 ItemKind::TyAlias(..) => DefKind::TyAlias,
221 ItemKind::Enum(..) => DefKind::Enum,
222 ItemKind::Struct(..) => DefKind::Struct,
223 ItemKind::Union(..) => DefKind::Union,
224 ItemKind::Trait(..) => DefKind::Trait,
225 ItemKind::TraitAlias(..) => DefKind::TraitAlias,
226 ItemKind::ExternCrate(_) => DefKind::ExternCrate,
227 ItemKind::Use(..) => DefKind::Use,
228 ItemKind::ForeignMod { .. } => DefKind::ForeignMod,
229 ItemKind::GlobalAsm(..) => DefKind::GlobalAsm,
230 ItemKind::Impl { .. } => DefKind::Impl,
232 Node::ForeignItem(item) => match item.kind {
233 ForeignItemKind::Fn(..) => DefKind::Fn,
234 ForeignItemKind::Static(..) => DefKind::Static,
235 ForeignItemKind::Type => DefKind::ForeignTy,
237 Node::TraitItem(item) => match item.kind {
238 TraitItemKind::Const(..) => DefKind::AssocConst,
239 TraitItemKind::Fn(..) => DefKind::AssocFn,
240 TraitItemKind::Type(..) => DefKind::AssocTy,
242 Node::ImplItem(item) => match item.kind {
243 ImplItemKind::Const(..) => DefKind::AssocConst,
244 ImplItemKind::Fn(..) => DefKind::AssocFn,
245 ImplItemKind::TyAlias(..) => DefKind::AssocTy,
247 Node::Variant(_) => DefKind::Variant,
248 Node::Ctor(variant_data) => {
249 // FIXME(eddyb) is this even possible, if we have a `Node::Ctor`?
250 assert_ne!(variant_data.ctor_hir_id(), None);
252 let ctor_of = match self.find(self.get_parent_node(hir_id)) {
253 Some(Node::Item(..)) => def::CtorOf::Struct,
254 Some(Node::Variant(..)) => def::CtorOf::Variant,
257 DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data))
259 Node::AnonConst(_) => DefKind::AnonConst,
260 Node::Field(_) => DefKind::Field,
261 Node::Expr(expr) => match expr.kind {
262 ExprKind::Closure(.., None) => DefKind::Closure,
263 ExprKind::Closure(.., Some(_)) => DefKind::Generator,
264 _ => bug!("def_kind: unsupported node: {}", self.node_to_string(hir_id)),
266 Node::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
267 Node::GenericParam(param) => match param.kind {
268 GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam,
269 GenericParamKind::Type { .. } => DefKind::TyParam,
270 GenericParamKind::Const { .. } => DefKind::ConstParam,
272 Node::Crate(_) => DefKind::Mod,
274 | Node::PathSegment(_)
283 | Node::Visibility(_)
284 | Node::Block(_) => return None,
289 pub fn def_kind(&self, local_def_id: LocalDefId) -> DefKind {
290 self.opt_def_kind(local_def_id)
291 .unwrap_or_else(|| bug!("def_kind: unsupported node: {:?}", local_def_id))
294 pub fn find_parent_node(&self, id: HirId) -> Option<HirId> {
295 if id.local_id == ItemLocalId::from_u32(0) {
296 Some(self.tcx.hir_owner_parent(id.owner))
298 let owner = self.tcx.hir_owner_nodes(id.owner)?;
299 let node = owner.nodes[id.local_id].as_ref()?;
300 let hir_id = HirId { owner: id.owner, local_id: node.parent };
305 pub fn get_parent_node(&self, hir_id: HirId) -> HirId {
306 self.find_parent_node(hir_id).unwrap_or(CRATE_HIR_ID)
309 /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
310 pub fn find(&self, id: HirId) -> Option<Node<'hir>> {
311 if id.local_id == ItemLocalId::from_u32(0) {
312 let owner = self.tcx.hir_owner(id.owner)?;
315 let owner = self.tcx.hir_owner_nodes(id.owner)?;
316 let node = owner.nodes[id.local_id].as_ref()?;
321 /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found.
322 pub fn get(&self, id: HirId) -> Node<'hir> {
323 self.find(id).unwrap_or_else(|| bug!("couldn't find hir id {} in the HIR map", id))
326 pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
327 id.as_local().and_then(|id| self.find(self.local_def_id_to_hir_id(id)))
330 pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics<'hir>> {
331 self.get_if_local(id).and_then(|node| match &node {
332 Node::ImplItem(impl_item) => Some(&impl_item.generics),
333 Node::TraitItem(trait_item) => Some(&trait_item.generics),
336 ItemKind::Fn(_, generics, _)
337 | ItemKind::TyAlias(_, generics)
338 | ItemKind::Enum(_, generics)
339 | ItemKind::Struct(_, generics)
340 | ItemKind::Union(_, generics)
341 | ItemKind::Trait(_, _, generics, ..)
342 | ItemKind::TraitAlias(generics, _)
343 | ItemKind::Impl(Impl { generics, .. }),
345 }) => Some(generics),
350 pub fn item(&self, id: ItemId) -> &'hir Item<'hir> {
351 match self.find(id.hir_id()).unwrap() {
352 Node::Item(item) => item,
357 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
358 match self.find(id.hir_id()).unwrap() {
359 Node::TraitItem(item) => item,
364 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
365 match self.find(id.hir_id()).unwrap() {
366 Node::ImplItem(item) => item,
371 pub fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
372 match self.find(id.hir_id()).unwrap() {
373 Node::ForeignItem(item) => item,
378 pub fn body(&self, id: BodyId) -> &'hir Body<'hir> {
379 self.tcx.hir_owner_nodes(id.hir_id.owner).unwrap().bodies.get(&id.hir_id.local_id).unwrap()
382 pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnDecl<'hir>> {
383 if let Some(node) = self.find(hir_id) {
386 bug!("no node for hir_id `{}`", hir_id)
390 pub fn fn_sig_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnSig<'hir>> {
391 if let Some(node) = self.find(hir_id) {
394 bug!("no node for hir_id `{}`", hir_id)
398 pub fn enclosing_body_owner(&self, hir_id: HirId) -> HirId {
399 for (parent, _) in self.parent_iter(hir_id) {
400 if let Some(body) = self.maybe_body_owned_by(parent) {
401 return self.body_owner(body);
405 bug!("no `enclosing_body_owner` for hir_id `{}`", hir_id);
408 /// Returns the `HirId` that corresponds to the definition of
409 /// which this is the body of, i.e., a `fn`, `const` or `static`
410 /// item (possibly associated), a closure, or a `hir::AnonConst`.
411 pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> HirId {
412 let parent = self.get_parent_node(hir_id);
413 assert!(self.find(parent).map_or(false, |n| is_body_owner(n, hir_id)));
417 pub fn body_owner_def_id(&self, id: BodyId) -> LocalDefId {
418 self.local_def_id(self.body_owner(id))
421 /// Given a `HirId`, returns the `BodyId` associated with it,
422 /// if the node is a body owner, otherwise returns `None`.
423 pub fn maybe_body_owned_by(&self, hir_id: HirId) -> Option<BodyId> {
424 self.find(hir_id).map(associated_body).flatten()
427 /// Given a body owner's id, returns the `BodyId` associated with it.
428 pub fn body_owned_by(&self, id: HirId) -> BodyId {
429 self.maybe_body_owned_by(id).unwrap_or_else(|| {
432 "body_owned_by: {} has no associated body",
433 self.node_to_string(id)
438 pub fn body_param_names(&self, id: BodyId) -> impl Iterator<Item = Ident> + 'hir {
439 self.body(id).params.iter().map(|arg| match arg.pat.kind {
440 PatKind::Binding(_, _, ident, _) => ident,
441 _ => Ident::new(kw::Empty, rustc_span::DUMMY_SP),
445 /// Returns the `BodyOwnerKind` of this `LocalDefId`.
447 /// Panics if `LocalDefId` does not have an associated body.
448 pub fn body_owner_kind(&self, id: HirId) -> BodyOwnerKind {
450 Node::Item(&Item { kind: ItemKind::Const(..), .. })
451 | Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. })
452 | Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. })
453 | Node::AnonConst(_) => BodyOwnerKind::Const,
455 | Node::Item(&Item { kind: ItemKind::Fn(..), .. })
456 | Node::TraitItem(&TraitItem { kind: TraitItemKind::Fn(..), .. })
457 | Node::ImplItem(&ImplItem { kind: ImplItemKind::Fn(..), .. }) => BodyOwnerKind::Fn,
458 Node::Item(&Item { kind: ItemKind::Static(_, m, _), .. }) => BodyOwnerKind::Static(m),
459 Node::Expr(&Expr { kind: ExprKind::Closure(..), .. }) => BodyOwnerKind::Closure,
460 node => bug!("{:#?} is not a body node", node),
464 /// Returns the `ConstContext` of the body associated with this `LocalDefId`.
466 /// Panics if `LocalDefId` does not have an associated body.
468 /// This should only be used for determining the context of a body, a return
469 /// value of `Some` does not always suggest that the owner of the body is `const`.
470 pub fn body_const_context(&self, did: LocalDefId) -> Option<ConstContext> {
471 let hir_id = self.local_def_id_to_hir_id(did);
472 let ccx = match self.body_owner_kind(hir_id) {
473 BodyOwnerKind::Const => ConstContext::Const,
474 BodyOwnerKind::Static(mt) => ConstContext::Static(mt),
476 BodyOwnerKind::Fn if self.tcx.is_constructor(did.to_def_id()) => return None,
477 BodyOwnerKind::Fn if self.tcx.is_const_fn_raw(did.to_def_id()) => ConstContext::ConstFn,
479 if self.tcx.has_attr(did.to_def_id(), sym::default_method_body_is_const) =>
481 ConstContext::ConstFn
483 BodyOwnerKind::Fn | BodyOwnerKind::Closure => return None,
489 pub fn ty_param_owner(&self, id: HirId) -> HirId {
491 Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => id,
492 Node::GenericParam(_) => self.get_parent_node(id),
493 _ => bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id)),
497 pub fn ty_param_name(&self, id: HirId) -> Symbol {
499 Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => {
502 Node::GenericParam(param) => param.name.ident().name,
503 _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
507 pub fn trait_impls(&self, trait_did: DefId) -> &'hir [LocalDefId] {
508 self.tcx.all_local_trait_impls(()).get(&trait_did).map_or(&[], |xs| &xs[..])
511 /// Gets the attributes on the crate. This is preferable to
512 /// invoking `krate.attrs` because it registers a tighter
513 /// dep-graph access.
514 pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
515 self.attrs(CRATE_HIR_ID)
518 pub fn get_module(&self, module: LocalDefId) -> (&'hir Mod<'hir>, Span, HirId) {
519 let hir_id = self.local_def_id_to_hir_id(module);
520 match self.get(hir_id) {
521 Node::Item(&Item { span, kind: ItemKind::Mod(ref m), .. }) => (m, span, hir_id),
522 Node::Crate(item) => (&item, item.inner, hir_id),
523 node => panic!("not a module: {:?}", node),
527 pub fn visit_item_likes_in_module<V>(&self, module: LocalDefId, visitor: &mut V)
529 V: ItemLikeVisitor<'hir>,
531 let module = self.tcx.hir_module_items(module);
533 for id in &module.items {
534 visitor.visit_item(self.item(*id));
537 for id in &module.trait_items {
538 visitor.visit_trait_item(self.trait_item(*id));
541 for id in &module.impl_items {
542 visitor.visit_impl_item(self.impl_item(*id));
545 for id in &module.foreign_items {
546 visitor.visit_foreign_item(self.foreign_item(*id));
550 pub fn visit_exported_macros_in_krate<V>(&self, visitor: &mut V)
554 for id in self.krate().exported_macros {
555 visitor.visit_macro_def(self.expect_macro_def(id.hir_id()));
559 /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
560 /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`.
561 pub fn parent_iter(&self, current_id: HirId) -> ParentHirIterator<'_, 'hir> {
562 ParentHirIterator { current_id, map: self }
565 /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
566 /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`.
567 pub fn parent_owner_iter(&self, current_id: HirId) -> ParentOwnerIterator<'_, 'hir> {
568 ParentOwnerIterator { current_id, map: self }
571 /// Checks if the node is left-hand side of an assignment.
572 pub fn is_lhs(&self, id: HirId) -> bool {
573 match self.find(self.get_parent_node(id)) {
574 Some(Node::Expr(expr)) => match expr.kind {
575 ExprKind::Assign(lhs, _rhs, _span) => lhs.hir_id == id,
582 /// Whether the expression pointed at by `hir_id` belongs to a `const` evaluation context.
583 /// Used exclusively for diagnostics, to avoid suggestion function calls.
584 pub fn is_inside_const_context(&self, hir_id: HirId) -> bool {
585 self.body_const_context(self.local_def_id(self.enclosing_body_owner(hir_id))).is_some()
588 /// Whether `hir_id` corresponds to a `mod` or a crate.
589 pub fn is_hir_id_module(&self, hir_id: HirId) -> bool {
592 Node::Item(Item { kind: ItemKind::Mod(_), .. }) | Node::Crate(..)
596 /// Retrieves the `HirId` for `id`'s enclosing method, unless there's a
597 /// `while` or `loop` before reaching it, as block tail returns are not
598 /// available in them.
601 /// fn foo(x: usize) -> bool {
603 /// true // If `get_return_block` gets passed the `id` corresponding
604 /// } else { // to this, it will return `foo`'s `HirId`.
611 /// fn foo(x: usize) -> bool {
613 /// true // If `get_return_block` gets passed the `id` corresponding
614 /// } // to this, it will return `None`.
618 pub fn get_return_block(&self, id: HirId) -> Option<HirId> {
619 let mut iter = self.parent_iter(id).peekable();
620 let mut ignore_tail = false;
621 if let Some(node) = self.find(id) {
622 if let Node::Expr(Expr { kind: ExprKind::Ret(_), .. }) = node {
623 // When dealing with `return` statements, we don't care about climbing only tail
628 while let Some((hir_id, node)) = iter.next() {
629 if let (Some((_, next_node)), false) = (iter.peek(), ignore_tail) {
631 Node::Block(Block { expr: None, .. }) => return None,
632 // The current node is not the tail expression of its parent.
633 Node::Block(Block { expr: Some(e), .. }) if hir_id != e.hir_id => return None,
639 | Node::ForeignItem(_)
641 | Node::Expr(Expr { kind: ExprKind::Closure(..), .. })
642 | Node::ImplItem(_) => return Some(hir_id),
643 // Ignore `return`s on the first iteration
644 Node::Expr(Expr { kind: ExprKind::Loop(..) | ExprKind::Ret(..), .. })
645 | Node::Local(_) => {
654 /// Retrieves the `HirId` for `id`'s parent item, or `id` itself if no
655 /// parent item is in this map. The "parent item" is the closest parent node
656 /// in the HIR which is recorded by the map and is an item, either an item
657 /// in a module, trait, or impl.
658 pub fn get_parent_item(&self, hir_id: HirId) -> HirId {
659 for (hir_id, node) in self.parent_owner_iter(hir_id) {
660 if let Node::Crate(_)
662 | Node::ForeignItem(_)
664 | Node::ImplItem(_) = node
672 /// Returns the `HirId` of `id`'s nearest module parent, or `id` itself if no
673 /// module parent is in this map.
674 pub(super) fn get_module_parent_node(&self, hir_id: HirId) -> HirId {
675 for (hir_id, node) in self.parent_owner_iter(hir_id) {
676 if let Node::Item(&Item { kind: ItemKind::Mod(_), .. }) = node {
683 /// When on an if expression, a match arm tail expression or a match arm, give back
684 /// the enclosing `if` or `match` expression.
686 /// Used by error reporting when there's a type error in an if or match arm caused by the
687 /// expression needing to be unit.
688 pub fn get_if_cause(&self, hir_id: HirId) -> Option<&'hir Expr<'hir>> {
689 for (_, node) in self.parent_iter(hir_id) {
692 | Node::ForeignItem(_)
695 | Node::Stmt(Stmt { kind: StmtKind::Local(_), .. }) => break,
696 Node::Expr(expr @ Expr { kind: ExprKind::If(..) | ExprKind::Match(..), .. }) => {
705 /// Returns the nearest enclosing scope. A scope is roughly an item or block.
706 pub fn get_enclosing_scope(&self, hir_id: HirId) -> Option<HirId> {
707 for (hir_id, node) in self.parent_iter(hir_id) {
708 if let Node::Item(Item {
711 | ItemKind::Const(..)
712 | ItemKind::Static(..)
715 | ItemKind::Struct(..)
716 | ItemKind::Union(..)
717 | ItemKind::Trait(..)
718 | ItemKind::Impl { .. },
721 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(..), .. })
722 | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(..), .. })
723 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(..), .. })
724 | Node::Block(_) = node
732 /// Returns the defining scope for an opaque type definition.
733 pub fn get_defining_scope(&self, id: HirId) -> HirId {
736 scope = self.get_enclosing_scope(scope).unwrap_or(CRATE_HIR_ID);
737 if scope == CRATE_HIR_ID || !matches!(self.get(scope), Node::Block(_)) {
743 pub fn get_parent_did(&self, id: HirId) -> LocalDefId {
744 self.local_def_id(self.get_parent_item(id))
747 pub fn get_foreign_abi(&self, hir_id: HirId) -> Abi {
748 let parent = self.get_parent_item(hir_id);
749 if let Some(node) = self.find(parent) {
750 if let Node::Item(Item { kind: ItemKind::ForeignMod { abi, .. }, .. }) = node {
754 bug!("expected foreign mod or inlined parent, found {}", self.node_to_string(parent))
757 pub fn expect_item(&self, id: HirId) -> &'hir Item<'hir> {
758 match self.find(id) {
759 Some(Node::Item(item)) => item,
760 _ => bug!("expected item, found {}", self.node_to_string(id)),
764 pub fn expect_impl_item(&self, id: HirId) -> &'hir ImplItem<'hir> {
765 match self.find(id) {
766 Some(Node::ImplItem(item)) => item,
767 _ => bug!("expected impl item, found {}", self.node_to_string(id)),
771 pub fn expect_trait_item(&self, id: HirId) -> &'hir TraitItem<'hir> {
772 match self.find(id) {
773 Some(Node::TraitItem(item)) => item,
774 _ => bug!("expected trait item, found {}", self.node_to_string(id)),
778 pub fn expect_variant(&self, id: HirId) -> &'hir Variant<'hir> {
779 match self.find(id) {
780 Some(Node::Variant(variant)) => variant,
781 _ => bug!("expected variant, found {}", self.node_to_string(id)),
785 pub fn expect_foreign_item(&self, id: HirId) -> &'hir ForeignItem<'hir> {
786 match self.find(id) {
787 Some(Node::ForeignItem(item)) => item,
788 _ => bug!("expected foreign item, found {}", self.node_to_string(id)),
792 pub fn expect_macro_def(&self, id: HirId) -> &'hir MacroDef<'hir> {
793 match self.find(id) {
794 Some(Node::MacroDef(macro_def)) => macro_def,
795 _ => bug!("expected macro def, found {}", self.node_to_string(id)),
799 pub fn expect_expr(&self, id: HirId) -> &'hir Expr<'hir> {
800 match self.find(id) {
801 Some(Node::Expr(expr)) => expr,
802 _ => bug!("expected expr, found {}", self.node_to_string(id)),
806 pub fn opt_name(&self, id: HirId) -> Option<Symbol> {
807 Some(match self.get(id) {
808 Node::Item(i) => i.ident.name,
809 Node::ForeignItem(fi) => fi.ident.name,
810 Node::ImplItem(ii) => ii.ident.name,
811 Node::TraitItem(ti) => ti.ident.name,
812 Node::Variant(v) => v.ident.name,
813 Node::Field(f) => f.ident.name,
814 Node::Lifetime(lt) => lt.name.ident().name,
815 Node::GenericParam(param) => param.name.ident().name,
816 Node::Binding(&Pat { kind: PatKind::Binding(_, _, l, _), .. }) => l.name,
817 Node::Ctor(..) => self.name(self.get_parent_item(id)),
818 Node::MacroDef(md) => md.ident.name,
823 pub fn name(&self, id: HirId) -> Symbol {
824 match self.opt_name(id) {
826 None => bug!("no name for {}", self.node_to_string(id)),
830 /// Given a node ID, gets a list of attributes associated with the AST
831 /// corresponding to the node-ID.
832 pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] {
833 self.tcx.hir_attrs(id.owner).get(id.local_id)
836 /// Gets the span of the definition of the specified HIR node.
837 /// This is used by `tcx.get_span`
838 pub fn span(&self, hir_id: HirId) -> Span {
839 self.opt_span(hir_id)
840 .unwrap_or_else(|| bug!("hir::map::Map::span: id not in map: {:?}", hir_id))
843 pub fn opt_span(&self, hir_id: HirId) -> Option<Span> {
844 let span = match self.find(hir_id)? {
845 Node::Param(param) => param.span,
846 Node::Item(item) => match &item.kind {
847 ItemKind::Fn(sig, _, _) => sig.span,
850 Node::ForeignItem(foreign_item) => foreign_item.span,
851 Node::TraitItem(trait_item) => match &trait_item.kind {
852 TraitItemKind::Fn(sig, _) => sig.span,
853 _ => trait_item.span,
855 Node::ImplItem(impl_item) => match &impl_item.kind {
856 ImplItemKind::Fn(sig, _) => sig.span,
859 Node::Variant(variant) => variant.span,
860 Node::Field(field) => field.span,
861 Node::AnonConst(constant) => self.body(constant.body).value.span,
862 Node::Expr(expr) => expr.span,
863 Node::Stmt(stmt) => stmt.span,
864 Node::PathSegment(seg) => seg.ident.span,
865 Node::Ty(ty) => ty.span,
866 Node::TraitRef(tr) => tr.path.span,
867 Node::Binding(pat) => pat.span,
868 Node::Pat(pat) => pat.span,
869 Node::Arm(arm) => arm.span,
870 Node::Block(block) => block.span,
871 Node::Ctor(..) => match self.find(self.get_parent_node(hir_id))? {
872 Node::Item(item) => item.span,
873 Node::Variant(variant) => variant.span,
876 Node::Lifetime(lifetime) => lifetime.span,
877 Node::GenericParam(param) => param.span,
878 Node::Visibility(&Spanned {
879 node: VisibilityKind::Restricted { ref path, .. },
882 Node::Visibility(v) => bug!("unexpected Visibility {:?}", v),
883 Node::Local(local) => local.span,
884 Node::MacroDef(macro_def) => macro_def.span,
885 Node::Crate(item) => item.inner,
890 /// Like `hir.span()`, but includes the body of function items
891 /// (instead of just the function header)
892 pub fn span_with_body(&self, hir_id: HirId) -> Span {
893 match self.find(hir_id) {
894 Some(Node::TraitItem(item)) => item.span,
895 Some(Node::ImplItem(impl_item)) => impl_item.span,
896 Some(Node::Item(item)) => item.span,
897 Some(_) => self.span(hir_id),
898 _ => bug!("hir::map::Map::span_with_body: id not in map: {:?}", hir_id),
902 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
903 id.as_local().and_then(|id| self.opt_span(self.local_def_id_to_hir_id(id)))
906 pub fn res_span(&self, res: Res) -> Option<Span> {
909 Res::Local(id) => Some(self.span(id)),
910 res => self.span_if_local(res.opt_def_id()?),
914 /// Get a representation of this `id` for debugging purposes.
915 /// NOTE: Do NOT use this in diagnostics!
916 pub fn node_to_string(&self, id: HirId) -> String {
917 hir_id_to_string(self, id)
921 impl<'hir> intravisit::Map<'hir> for Map<'hir> {
922 fn find(&self, hir_id: HirId) -> Option<Node<'hir>> {
926 fn body(&self, id: BodyId) -> &'hir Body<'hir> {
930 fn item(&self, id: ItemId) -> &'hir Item<'hir> {
934 fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
938 fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
942 fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
943 self.foreign_item(id)
947 pub(super) fn index_hir<'tcx>(tcx: TyCtxt<'tcx>, (): ()) -> &'tcx IndexedHir<'tcx> {
948 let _prof_timer = tcx.sess.prof.generic_activity("build_hir_map");
950 // We can access untracked state since we are an eval_always query.
951 let hcx = tcx.create_stable_hashing_context();
952 let mut collector = NodeCollector::root(
956 &tcx.untracked_resolutions.definitions,
959 intravisit::walk_crate(&mut collector, tcx.untracked_crate);
961 let map = collector.finalize_and_compute_crate_hash();
965 pub(super) fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
966 assert_eq!(crate_num, LOCAL_CRATE);
968 // We can access untracked state since we are an eval_always query.
969 let mut hcx = tcx.create_stable_hashing_context();
971 let mut hir_body_nodes: Vec<_> = tcx
975 .filter_map(|(def_id, hod)| {
976 let def_path_hash = tcx.untracked_resolutions.definitions.def_path_hash(def_id);
977 let mut hasher = StableHasher::new();
978 hod.as_ref()?.hash_stable(&mut hcx, &mut hasher);
979 AttributeMap { map: &tcx.untracked_crate.attrs, prefix: def_id }
980 .hash_stable(&mut hcx, &mut hasher);
981 Some((def_path_hash, hasher.finish()))
984 hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
986 let node_hashes = hir_body_nodes.iter().fold(
988 |combined_fingerprint, &(def_path_hash, fingerprint)| {
989 combined_fingerprint.combine(def_path_hash.0.combine(fingerprint))
993 let upstream_crates = upstream_crates(tcx);
995 // We hash the final, remapped names of all local source files so we
996 // don't have to include the path prefix remapping commandline args.
997 // If we included the full mapping in the SVH, we could only have
998 // reproducible builds by compiling from the same directory. So we just
999 // hash the result of the mapping instead of the mapping itself.
1000 let mut source_file_names: Vec<_> = tcx
1005 .filter(|source_file| source_file.cnum == LOCAL_CRATE)
1006 .map(|source_file| source_file.name_hash)
1009 source_file_names.sort_unstable();
1011 let mut stable_hasher = StableHasher::new();
1012 node_hashes.hash_stable(&mut hcx, &mut stable_hasher);
1013 upstream_crates.hash_stable(&mut hcx, &mut stable_hasher);
1014 source_file_names.hash_stable(&mut hcx, &mut stable_hasher);
1015 tcx.sess.opts.dep_tracking_hash(true).hash_stable(&mut hcx, &mut stable_hasher);
1016 tcx.sess.local_stable_crate_id().hash_stable(&mut hcx, &mut stable_hasher);
1017 tcx.untracked_crate.non_exported_macro_attrs.hash_stable(&mut hcx, &mut stable_hasher);
1019 let crate_hash: Fingerprint = stable_hasher.finish();
1020 Svh::new(crate_hash.to_smaller_hash())
1023 fn upstream_crates(tcx: TyCtxt<'_>) -> Vec<(StableCrateId, Svh)> {
1024 let mut upstream_crates: Vec<_> = tcx
1028 let stable_crate_id = tcx.resolutions(()).cstore.stable_crate_id(cnum);
1029 let hash = tcx.crate_hash(cnum);
1030 (stable_crate_id, hash)
1033 upstream_crates.sort_unstable_by_key(|&(stable_crate_id, _)| stable_crate_id);
1037 fn hir_id_to_string(map: &Map<'_>, id: HirId) -> String {
1038 let id_str = format!(" (hir_id={})", id);
1041 // This functionality is used for debugging, try to use `TyCtxt` to get
1042 // the user-friendly path, otherwise fall back to stringifying `DefPath`.
1043 crate::ty::tls::with_opt(|tcx| {
1044 if let Some(tcx) = tcx {
1045 let def_id = map.local_def_id(id);
1046 tcx.def_path_str(def_id.to_def_id())
1047 } else if let Some(path) = map.def_path_from_hir_id(id) {
1048 path.data.into_iter().map(|elem| elem.to_string()).collect::<Vec<_>>().join("::")
1050 String::from("<missing path>")
1055 let span_str = || map.tcx.sess.source_map().span_to_snippet(map.span(id)).unwrap_or_default();
1056 let node_str = |prefix| format!("{} {}{}", prefix, span_str(), id_str);
1058 match map.find(id) {
1059 Some(Node::Item(item)) => {
1060 let item_str = match item.kind {
1061 ItemKind::ExternCrate(..) => "extern crate",
1062 ItemKind::Use(..) => "use",
1063 ItemKind::Static(..) => "static",
1064 ItemKind::Const(..) => "const",
1065 ItemKind::Fn(..) => "fn",
1066 ItemKind::Mod(..) => "mod",
1067 ItemKind::ForeignMod { .. } => "foreign mod",
1068 ItemKind::GlobalAsm(..) => "global asm",
1069 ItemKind::TyAlias(..) => "ty",
1070 ItemKind::OpaqueTy(..) => "opaque type",
1071 ItemKind::Enum(..) => "enum",
1072 ItemKind::Struct(..) => "struct",
1073 ItemKind::Union(..) => "union",
1074 ItemKind::Trait(..) => "trait",
1075 ItemKind::TraitAlias(..) => "trait alias",
1076 ItemKind::Impl { .. } => "impl",
1078 format!("{} {}{}", item_str, path_str(), id_str)
1080 Some(Node::ForeignItem(_)) => format!("foreign item {}{}", path_str(), id_str),
1081 Some(Node::ImplItem(ii)) => match ii.kind {
1082 ImplItemKind::Const(..) => {
1083 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1085 ImplItemKind::Fn(..) => format!("method {} in {}{}", ii.ident, path_str(), id_str),
1086 ImplItemKind::TyAlias(_) => {
1087 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1090 Some(Node::TraitItem(ti)) => {
1091 let kind = match ti.kind {
1092 TraitItemKind::Const(..) => "assoc constant",
1093 TraitItemKind::Fn(..) => "trait method",
1094 TraitItemKind::Type(..) => "assoc type",
1097 format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1099 Some(Node::Variant(ref variant)) => {
1100 format!("variant {} in {}{}", variant.ident, path_str(), id_str)
1102 Some(Node::Field(ref field)) => {
1103 format!("field {} in {}{}", field.ident, path_str(), id_str)
1105 Some(Node::AnonConst(_)) => node_str("const"),
1106 Some(Node::Expr(_)) => node_str("expr"),
1107 Some(Node::Stmt(_)) => node_str("stmt"),
1108 Some(Node::PathSegment(_)) => node_str("path segment"),
1109 Some(Node::Ty(_)) => node_str("type"),
1110 Some(Node::TraitRef(_)) => node_str("trait ref"),
1111 Some(Node::Binding(_)) => node_str("local"),
1112 Some(Node::Pat(_)) => node_str("pat"),
1113 Some(Node::Param(_)) => node_str("param"),
1114 Some(Node::Arm(_)) => node_str("arm"),
1115 Some(Node::Block(_)) => node_str("block"),
1116 Some(Node::Local(_)) => node_str("local"),
1117 Some(Node::Ctor(..)) => format!("ctor {}{}", path_str(), id_str),
1118 Some(Node::Lifetime(_)) => node_str("lifetime"),
1119 Some(Node::GenericParam(ref param)) => format!("generic_param {:?}{}", param, id_str),
1120 Some(Node::Visibility(ref vis)) => format!("visibility {:?}{}", vis, id_str),
1121 Some(Node::MacroDef(_)) => format!("macro {}{}", path_str(), id_str),
1122 Some(Node::Crate(..)) => String::from("root_crate"),
1123 None => format!("unknown node{}", id_str),