1 use self::collector::NodeCollector;
3 use crate::hir::{AttributeMap, HirOwnerData, IndexedHir};
4 use crate::middle::cstore::CrateStore;
7 use rustc_data_structures::fingerprint::Fingerprint;
8 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
9 use rustc_data_structures::svh::Svh;
10 use rustc_hir::def::{DefKind, Res};
11 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
12 use rustc_hir::definitions::{DefKey, DefPath, Definitions};
13 use rustc_hir::intravisit;
14 use rustc_hir::intravisit::Visitor;
15 use rustc_hir::itemlikevisit::ItemLikeVisitor;
17 use rustc_index::vec::Idx;
18 use rustc_span::hygiene::MacroKind;
19 use rustc_span::source_map::Spanned;
20 use rustc_span::symbol::{kw, 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(())
157 pub fn definitions(&self) -> &'hir Definitions {
158 &self.tcx.definitions
161 pub fn def_key(&self, def_id: LocalDefId) -> DefKey {
162 self.tcx.definitions.def_key(def_id)
165 pub fn def_path_from_hir_id(&self, id: HirId) -> Option<DefPath> {
166 self.opt_local_def_id(id).map(|def_id| self.def_path(def_id))
169 pub fn def_path(&self, def_id: LocalDefId) -> DefPath {
170 self.tcx.definitions.def_path(def_id)
174 pub fn local_def_id(&self, hir_id: HirId) -> LocalDefId {
175 self.opt_local_def_id(hir_id).unwrap_or_else(|| {
177 "local_def_id: no entry for `{:?}`, which has a map of `{:?}`",
185 pub fn opt_local_def_id(&self, hir_id: HirId) -> Option<LocalDefId> {
186 self.tcx.definitions.opt_hir_id_to_local_def_id(hir_id)
190 pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
191 self.tcx.definitions.local_def_id_to_hir_id(def_id)
194 pub fn iter_local_def_id(&self) -> impl Iterator<Item = LocalDefId> + '_ {
195 self.tcx.definitions.iter_local_def_id()
198 pub fn opt_def_kind(&self, local_def_id: LocalDefId) -> Option<DefKind> {
199 // FIXME(eddyb) support `find` on the crate root.
200 if local_def_id.to_def_id().index == CRATE_DEF_INDEX {
201 return Some(DefKind::Mod);
204 let hir_id = self.local_def_id_to_hir_id(local_def_id);
205 let def_kind = match self.find(hir_id)? {
206 Node::Item(item) => match item.kind {
207 ItemKind::Static(..) => DefKind::Static,
208 ItemKind::Const(..) => DefKind::Const,
209 ItemKind::Fn(..) => DefKind::Fn,
210 ItemKind::Mod(..) => DefKind::Mod,
211 ItemKind::OpaqueTy(..) => DefKind::OpaqueTy,
212 ItemKind::TyAlias(..) => DefKind::TyAlias,
213 ItemKind::Enum(..) => DefKind::Enum,
214 ItemKind::Struct(..) => DefKind::Struct,
215 ItemKind::Union(..) => DefKind::Union,
216 ItemKind::Trait(..) => DefKind::Trait,
217 ItemKind::TraitAlias(..) => DefKind::TraitAlias,
218 ItemKind::ExternCrate(_) => DefKind::ExternCrate,
219 ItemKind::Use(..) => DefKind::Use,
220 ItemKind::ForeignMod { .. } => DefKind::ForeignMod,
221 ItemKind::GlobalAsm(..) => DefKind::GlobalAsm,
222 ItemKind::Impl { .. } => DefKind::Impl,
224 Node::ForeignItem(item) => match item.kind {
225 ForeignItemKind::Fn(..) => DefKind::Fn,
226 ForeignItemKind::Static(..) => DefKind::Static,
227 ForeignItemKind::Type => DefKind::ForeignTy,
229 Node::TraitItem(item) => match item.kind {
230 TraitItemKind::Const(..) => DefKind::AssocConst,
231 TraitItemKind::Fn(..) => DefKind::AssocFn,
232 TraitItemKind::Type(..) => DefKind::AssocTy,
234 Node::ImplItem(item) => match item.kind {
235 ImplItemKind::Const(..) => DefKind::AssocConst,
236 ImplItemKind::Fn(..) => DefKind::AssocFn,
237 ImplItemKind::TyAlias(..) => DefKind::AssocTy,
239 Node::Variant(_) => DefKind::Variant,
240 Node::Ctor(variant_data) => {
241 // FIXME(eddyb) is this even possible, if we have a `Node::Ctor`?
242 assert_ne!(variant_data.ctor_hir_id(), None);
244 let ctor_of = match self.find(self.get_parent_node(hir_id)) {
245 Some(Node::Item(..)) => def::CtorOf::Struct,
246 Some(Node::Variant(..)) => def::CtorOf::Variant,
249 DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data))
251 Node::AnonConst(_) => DefKind::AnonConst,
252 Node::Field(_) => DefKind::Field,
253 Node::Expr(expr) => match expr.kind {
254 ExprKind::Closure(.., None) => DefKind::Closure,
255 ExprKind::Closure(.., Some(_)) => DefKind::Generator,
256 _ => bug!("def_kind: unsupported node: {}", self.node_to_string(hir_id)),
258 Node::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
259 Node::GenericParam(param) => match param.kind {
260 GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam,
261 GenericParamKind::Type { .. } => DefKind::TyParam,
262 GenericParamKind::Const { .. } => DefKind::ConstParam,
264 Node::Crate(_) => DefKind::Mod,
266 | Node::PathSegment(_)
275 | Node::Visibility(_)
276 | Node::Block(_) => return None,
281 pub fn def_kind(&self, local_def_id: LocalDefId) -> DefKind {
282 self.opt_def_kind(local_def_id)
283 .unwrap_or_else(|| bug!("def_kind: unsupported node: {:?}", local_def_id))
286 pub fn find_parent_node(&self, id: HirId) -> Option<HirId> {
287 if id.local_id == ItemLocalId::from_u32(0) {
288 Some(self.tcx.hir_owner_parent(id.owner))
290 let owner = self.tcx.hir_owner_nodes(id.owner)?;
291 let node = owner.nodes[id.local_id].as_ref()?;
292 let hir_id = HirId { owner: id.owner, local_id: node.parent };
297 pub fn get_parent_node(&self, hir_id: HirId) -> HirId {
298 self.find_parent_node(hir_id).unwrap_or(CRATE_HIR_ID)
301 /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
302 pub fn find(&self, id: HirId) -> Option<Node<'hir>> {
303 if id.local_id == ItemLocalId::from_u32(0) {
304 let owner = self.tcx.hir_owner(id.owner)?;
307 let owner = self.tcx.hir_owner_nodes(id.owner)?;
308 let node = owner.nodes[id.local_id].as_ref()?;
313 /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found.
314 pub fn get(&self, id: HirId) -> Node<'hir> {
315 self.find(id).unwrap_or_else(|| bug!("couldn't find hir id {} in the HIR map", id))
318 pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
319 id.as_local().and_then(|id| self.find(self.local_def_id_to_hir_id(id)))
322 pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics<'hir>> {
323 self.get_if_local(id).and_then(|node| match &node {
324 Node::ImplItem(impl_item) => Some(&impl_item.generics),
325 Node::TraitItem(trait_item) => Some(&trait_item.generics),
328 ItemKind::Fn(_, generics, _)
329 | ItemKind::TyAlias(_, generics)
330 | ItemKind::Enum(_, generics)
331 | ItemKind::Struct(_, generics)
332 | ItemKind::Union(_, generics)
333 | ItemKind::Trait(_, _, generics, ..)
334 | ItemKind::TraitAlias(generics, _)
335 | ItemKind::Impl(Impl { generics, .. }),
337 }) => Some(generics),
342 pub fn item(&self, id: ItemId) -> &'hir Item<'hir> {
343 match self.find(id.hir_id()).unwrap() {
344 Node::Item(item) => item,
349 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
350 match self.find(id.hir_id()).unwrap() {
351 Node::TraitItem(item) => item,
356 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
357 match self.find(id.hir_id()).unwrap() {
358 Node::ImplItem(item) => item,
363 pub fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
364 match self.find(id.hir_id()).unwrap() {
365 Node::ForeignItem(item) => item,
370 pub fn body(&self, id: BodyId) -> &'hir Body<'hir> {
371 self.tcx.hir_owner_nodes(id.hir_id.owner).unwrap().bodies.get(&id.hir_id.local_id).unwrap()
374 pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnDecl<'hir>> {
375 if let Some(node) = self.find(hir_id) {
378 bug!("no node for hir_id `{}`", hir_id)
382 pub fn fn_sig_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnSig<'hir>> {
383 if let Some(node) = self.find(hir_id) {
386 bug!("no node for hir_id `{}`", hir_id)
390 pub fn enclosing_body_owner(&self, hir_id: HirId) -> HirId {
391 for (parent, _) in self.parent_iter(hir_id) {
392 if let Some(body) = self.maybe_body_owned_by(parent) {
393 return self.body_owner(body);
397 bug!("no `enclosing_body_owner` for hir_id `{}`", hir_id);
400 /// Returns the `HirId` that corresponds to the definition of
401 /// which this is the body of, i.e., a `fn`, `const` or `static`
402 /// item (possibly associated), a closure, or a `hir::AnonConst`.
403 pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> HirId {
404 let parent = self.get_parent_node(hir_id);
405 assert!(self.find(parent).map_or(false, |n| is_body_owner(n, hir_id)));
409 pub fn body_owner_def_id(&self, id: BodyId) -> LocalDefId {
410 self.local_def_id(self.body_owner(id))
413 /// Given a `HirId`, returns the `BodyId` associated with it,
414 /// if the node is a body owner, otherwise returns `None`.
415 pub fn maybe_body_owned_by(&self, hir_id: HirId) -> Option<BodyId> {
416 self.find(hir_id).map(associated_body).flatten()
419 /// Given a body owner's id, returns the `BodyId` associated with it.
420 pub fn body_owned_by(&self, id: HirId) -> BodyId {
421 self.maybe_body_owned_by(id).unwrap_or_else(|| {
424 "body_owned_by: {} has no associated body",
425 self.node_to_string(id)
430 pub fn body_param_names(&self, id: BodyId) -> impl Iterator<Item = Ident> + 'hir {
431 self.body(id).params.iter().map(|arg| match arg.pat.kind {
432 PatKind::Binding(_, _, ident, _) => ident,
433 _ => Ident::new(kw::Empty, rustc_span::DUMMY_SP),
437 /// Returns the `BodyOwnerKind` of this `LocalDefId`.
439 /// Panics if `LocalDefId` does not have an associated body.
440 pub fn body_owner_kind(&self, id: HirId) -> BodyOwnerKind {
442 Node::Item(&Item { kind: ItemKind::Const(..), .. })
443 | Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. })
444 | Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. })
445 | Node::AnonConst(_) => BodyOwnerKind::Const,
447 | Node::Item(&Item { kind: ItemKind::Fn(..), .. })
448 | Node::TraitItem(&TraitItem { kind: TraitItemKind::Fn(..), .. })
449 | Node::ImplItem(&ImplItem { kind: ImplItemKind::Fn(..), .. }) => BodyOwnerKind::Fn,
450 Node::Item(&Item { kind: ItemKind::Static(_, m, _), .. }) => BodyOwnerKind::Static(m),
451 Node::Expr(&Expr { kind: ExprKind::Closure(..), .. }) => BodyOwnerKind::Closure,
452 node => bug!("{:#?} is not a body node", node),
456 /// Returns the `ConstContext` of the body associated with this `LocalDefId`.
458 /// Panics if `LocalDefId` does not have an associated body.
459 pub fn body_const_context(&self, did: LocalDefId) -> Option<ConstContext> {
460 let hir_id = self.local_def_id_to_hir_id(did);
461 let ccx = match self.body_owner_kind(hir_id) {
462 BodyOwnerKind::Const => ConstContext::Const,
463 BodyOwnerKind::Static(mt) => ConstContext::Static(mt),
465 BodyOwnerKind::Fn if self.tcx.is_constructor(did.to_def_id()) => return None,
466 BodyOwnerKind::Fn if self.tcx.is_const_fn_raw(did.to_def_id()) => ConstContext::ConstFn,
467 BodyOwnerKind::Fn | BodyOwnerKind::Closure => return None,
473 pub fn ty_param_owner(&self, id: HirId) -> HirId {
475 Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => id,
476 Node::GenericParam(_) => self.get_parent_node(id),
477 _ => bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id)),
481 pub fn ty_param_name(&self, id: HirId) -> Symbol {
483 Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => {
486 Node::GenericParam(param) => param.name.ident().name,
487 _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
491 pub fn trait_impls(&self, trait_did: DefId) -> &'hir [LocalDefId] {
492 self.tcx.all_local_trait_impls(()).get(&trait_did).map_or(&[], |xs| &xs[..])
495 /// Gets the attributes on the crate. This is preferable to
496 /// invoking `krate.attrs` because it registers a tighter
497 /// dep-graph access.
498 pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
499 self.attrs(CRATE_HIR_ID)
502 pub fn get_module(&self, module: LocalDefId) -> (&'hir Mod<'hir>, Span, HirId) {
503 let hir_id = self.local_def_id_to_hir_id(module);
504 match self.get(hir_id) {
505 Node::Item(&Item { span, kind: ItemKind::Mod(ref m), .. }) => (m, span, hir_id),
506 Node::Crate(item) => (&item, item.inner, hir_id),
507 node => panic!("not a module: {:?}", node),
511 pub fn visit_item_likes_in_module<V>(&self, module: LocalDefId, visitor: &mut V)
513 V: ItemLikeVisitor<'hir>,
515 let module = self.tcx.hir_module_items(module);
517 for id in &module.items {
518 visitor.visit_item(self.item(*id));
521 for id in &module.trait_items {
522 visitor.visit_trait_item(self.trait_item(*id));
525 for id in &module.impl_items {
526 visitor.visit_impl_item(self.impl_item(*id));
529 for id in &module.foreign_items {
530 visitor.visit_foreign_item(self.foreign_item(*id));
534 pub fn visit_exported_macros_in_krate<V>(&self, visitor: &mut V)
538 for id in self.krate().exported_macros {
539 visitor.visit_macro_def(self.expect_macro_def(id.hir_id()));
543 /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
544 /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`.
545 pub fn parent_iter(&self, current_id: HirId) -> ParentHirIterator<'_, 'hir> {
546 ParentHirIterator { current_id, map: self }
549 /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
550 /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`.
551 pub fn parent_owner_iter(&self, current_id: HirId) -> ParentOwnerIterator<'_, 'hir> {
552 ParentOwnerIterator { current_id, map: self }
555 /// Checks if the node is left-hand side of an assignment.
556 pub fn is_lhs(&self, id: HirId) -> bool {
557 match self.find(self.get_parent_node(id)) {
558 Some(Node::Expr(expr)) => match expr.kind {
559 ExprKind::Assign(lhs, _rhs, _span) => lhs.hir_id == id,
566 /// Whether the expression pointed at by `hir_id` belongs to a `const` evaluation context.
567 /// Used exclusively for diagnostics, to avoid suggestion function calls.
568 pub fn is_inside_const_context(&self, hir_id: HirId) -> bool {
569 self.body_const_context(self.local_def_id(self.enclosing_body_owner(hir_id))).is_some()
572 /// Whether `hir_id` corresponds to a `mod` or a crate.
573 pub fn is_hir_id_module(&self, hir_id: HirId) -> bool {
576 Node::Item(Item { kind: ItemKind::Mod(_), .. }) | Node::Crate(..)
580 /// Retrieves the `HirId` for `id`'s enclosing method, unless there's a
581 /// `while` or `loop` before reaching it, as block tail returns are not
582 /// available in them.
585 /// fn foo(x: usize) -> bool {
587 /// true // If `get_return_block` gets passed the `id` corresponding
588 /// } else { // to this, it will return `foo`'s `HirId`.
595 /// fn foo(x: usize) -> bool {
597 /// true // If `get_return_block` gets passed the `id` corresponding
598 /// } // to this, it will return `None`.
602 pub fn get_return_block(&self, id: HirId) -> Option<HirId> {
603 let mut iter = self.parent_iter(id).peekable();
604 let mut ignore_tail = false;
605 if let Some(node) = self.find(id) {
606 if let Node::Expr(Expr { kind: ExprKind::Ret(_), .. }) = node {
607 // When dealing with `return` statements, we don't care about climbing only tail
612 while let Some((hir_id, node)) = iter.next() {
613 if let (Some((_, next_node)), false) = (iter.peek(), ignore_tail) {
615 Node::Block(Block { expr: None, .. }) => return None,
616 // The current node is not the tail expression of its parent.
617 Node::Block(Block { expr: Some(e), .. }) if hir_id != e.hir_id => return None,
623 | Node::ForeignItem(_)
625 | Node::Expr(Expr { kind: ExprKind::Closure(..), .. })
626 | Node::ImplItem(_) => return Some(hir_id),
627 // Ignore `return`s on the first iteration
628 Node::Expr(Expr { kind: ExprKind::Loop(..) | ExprKind::Ret(..), .. })
629 | Node::Local(_) => {
638 /// Retrieves the `HirId` for `id`'s parent item, or `id` itself if no
639 /// parent item is in this map. The "parent item" is the closest parent node
640 /// in the HIR which is recorded by the map and is an item, either an item
641 /// in a module, trait, or impl.
642 pub fn get_parent_item(&self, hir_id: HirId) -> HirId {
643 for (hir_id, node) in self.parent_owner_iter(hir_id) {
644 if let Node::Crate(_)
646 | Node::ForeignItem(_)
648 | Node::ImplItem(_) = node
656 /// Returns the `HirId` of `id`'s nearest module parent, or `id` itself if no
657 /// module parent is in this map.
658 pub(super) fn get_module_parent_node(&self, hir_id: HirId) -> HirId {
659 for (hir_id, node) in self.parent_owner_iter(hir_id) {
660 if let Node::Item(&Item { kind: ItemKind::Mod(_), .. }) = node {
667 /// When on an if expression, a match arm tail expression or a match arm, give back
668 /// the enclosing `if` or `match` expression.
670 /// Used by error reporting when there's a type error in an if or match arm caused by the
671 /// expression needing to be unit.
672 pub fn get_if_cause(&self, hir_id: HirId) -> Option<&'hir Expr<'hir>> {
673 for (_, node) in self.parent_iter(hir_id) {
676 | Node::ForeignItem(_)
679 | Node::Stmt(Stmt { kind: StmtKind::Local(_), .. }) => break,
680 Node::Expr(expr @ Expr { kind: ExprKind::If(..) | ExprKind::Match(..), .. }) => {
689 /// Returns the nearest enclosing scope. A scope is roughly an item or block.
690 pub fn get_enclosing_scope(&self, hir_id: HirId) -> Option<HirId> {
691 for (hir_id, node) in self.parent_iter(hir_id) {
692 if let Node::Item(Item {
695 | ItemKind::Const(..)
696 | ItemKind::Static(..)
699 | ItemKind::Struct(..)
700 | ItemKind::Union(..)
701 | ItemKind::Trait(..)
702 | ItemKind::Impl { .. },
705 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(..), .. })
706 | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(..), .. })
707 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(..), .. })
708 | Node::Block(_) = node
716 /// Returns the defining scope for an opaque type definition.
717 pub fn get_defining_scope(&self, id: HirId) -> HirId {
720 scope = self.get_enclosing_scope(scope).unwrap_or(CRATE_HIR_ID);
721 if scope == CRATE_HIR_ID || !matches!(self.get(scope), Node::Block(_)) {
727 pub fn get_parent_did(&self, id: HirId) -> LocalDefId {
728 self.local_def_id(self.get_parent_item(id))
731 pub fn get_foreign_abi(&self, hir_id: HirId) -> Abi {
732 let parent = self.get_parent_item(hir_id);
733 if let Some(node) = self.find(parent) {
734 if let Node::Item(Item { kind: ItemKind::ForeignMod { abi, .. }, .. }) = node {
738 bug!("expected foreign mod or inlined parent, found {}", self.node_to_string(parent))
741 pub fn expect_item(&self, id: HirId) -> &'hir Item<'hir> {
742 match self.find(id) {
743 Some(Node::Item(item)) => item,
744 _ => bug!("expected item, found {}", self.node_to_string(id)),
748 pub fn expect_impl_item(&self, id: HirId) -> &'hir ImplItem<'hir> {
749 match self.find(id) {
750 Some(Node::ImplItem(item)) => item,
751 _ => bug!("expected impl item, found {}", self.node_to_string(id)),
755 pub fn expect_trait_item(&self, id: HirId) -> &'hir TraitItem<'hir> {
756 match self.find(id) {
757 Some(Node::TraitItem(item)) => item,
758 _ => bug!("expected trait item, found {}", self.node_to_string(id)),
762 pub fn expect_variant(&self, id: HirId) -> &'hir Variant<'hir> {
763 match self.find(id) {
764 Some(Node::Variant(variant)) => variant,
765 _ => bug!("expected variant, found {}", self.node_to_string(id)),
769 pub fn expect_foreign_item(&self, id: HirId) -> &'hir ForeignItem<'hir> {
770 match self.find(id) {
771 Some(Node::ForeignItem(item)) => item,
772 _ => bug!("expected foreign item, found {}", self.node_to_string(id)),
776 pub fn expect_macro_def(&self, id: HirId) -> &'hir MacroDef<'hir> {
777 match self.find(id) {
778 Some(Node::MacroDef(macro_def)) => macro_def,
779 _ => bug!("expected macro def, found {}", self.node_to_string(id)),
783 pub fn expect_expr(&self, id: HirId) -> &'hir Expr<'hir> {
784 match self.find(id) {
785 Some(Node::Expr(expr)) => expr,
786 _ => bug!("expected expr, found {}", self.node_to_string(id)),
790 pub fn opt_name(&self, id: HirId) -> Option<Symbol> {
791 Some(match self.get(id) {
792 Node::Item(i) => i.ident.name,
793 Node::ForeignItem(fi) => fi.ident.name,
794 Node::ImplItem(ii) => ii.ident.name,
795 Node::TraitItem(ti) => ti.ident.name,
796 Node::Variant(v) => v.ident.name,
797 Node::Field(f) => f.ident.name,
798 Node::Lifetime(lt) => lt.name.ident().name,
799 Node::GenericParam(param) => param.name.ident().name,
800 Node::Binding(&Pat { kind: PatKind::Binding(_, _, l, _), .. }) => l.name,
801 Node::Ctor(..) => self.name(self.get_parent_item(id)),
802 Node::MacroDef(md) => md.ident.name,
807 pub fn name(&self, id: HirId) -> Symbol {
808 match self.opt_name(id) {
810 None => bug!("no name for {}", self.node_to_string(id)),
814 /// Given a node ID, gets a list of attributes associated with the AST
815 /// corresponding to the node-ID.
816 pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] {
817 self.tcx.hir_attrs(id.owner).get(id.local_id)
820 /// Gets the span of the definition of the specified HIR node.
821 /// This is used by `tcx.get_span`
822 pub fn span(&self, hir_id: HirId) -> Span {
823 self.opt_span(hir_id)
824 .unwrap_or_else(|| bug!("hir::map::Map::span: id not in map: {:?}", hir_id))
827 pub fn opt_span(&self, hir_id: HirId) -> Option<Span> {
828 let span = match self.find(hir_id)? {
829 Node::Param(param) => param.span,
830 Node::Item(item) => match &item.kind {
831 ItemKind::Fn(sig, _, _) => sig.span,
834 Node::ForeignItem(foreign_item) => foreign_item.span,
835 Node::TraitItem(trait_item) => match &trait_item.kind {
836 TraitItemKind::Fn(sig, _) => sig.span,
837 _ => trait_item.span,
839 Node::ImplItem(impl_item) => match &impl_item.kind {
840 ImplItemKind::Fn(sig, _) => sig.span,
843 Node::Variant(variant) => variant.span,
844 Node::Field(field) => field.span,
845 Node::AnonConst(constant) => self.body(constant.body).value.span,
846 Node::Expr(expr) => expr.span,
847 Node::Stmt(stmt) => stmt.span,
848 Node::PathSegment(seg) => seg.ident.span,
849 Node::Ty(ty) => ty.span,
850 Node::TraitRef(tr) => tr.path.span,
851 Node::Binding(pat) => pat.span,
852 Node::Pat(pat) => pat.span,
853 Node::Arm(arm) => arm.span,
854 Node::Block(block) => block.span,
855 Node::Ctor(..) => match self.find(self.get_parent_node(hir_id))? {
856 Node::Item(item) => item.span,
857 Node::Variant(variant) => variant.span,
860 Node::Lifetime(lifetime) => lifetime.span,
861 Node::GenericParam(param) => param.span,
862 Node::Visibility(&Spanned {
863 node: VisibilityKind::Restricted { ref path, .. },
866 Node::Visibility(v) => bug!("unexpected Visibility {:?}", v),
867 Node::Local(local) => local.span,
868 Node::MacroDef(macro_def) => macro_def.span,
869 Node::Crate(item) => item.inner,
874 /// Like `hir.span()`, but includes the body of function items
875 /// (instead of just the function header)
876 pub fn span_with_body(&self, hir_id: HirId) -> Span {
877 match self.find(hir_id) {
878 Some(Node::TraitItem(item)) => item.span,
879 Some(Node::ImplItem(impl_item)) => impl_item.span,
880 Some(Node::Item(item)) => item.span,
881 Some(_) => self.span(hir_id),
882 _ => bug!("hir::map::Map::span_with_body: id not in map: {:?}", hir_id),
886 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
887 id.as_local().and_then(|id| self.opt_span(self.local_def_id_to_hir_id(id)))
890 pub fn res_span(&self, res: Res) -> Option<Span> {
893 Res::Local(id) => Some(self.span(id)),
894 res => self.span_if_local(res.opt_def_id()?),
898 /// Get a representation of this `id` for debugging purposes.
899 /// NOTE: Do NOT use this in diagnostics!
900 pub fn node_to_string(&self, id: HirId) -> String {
901 hir_id_to_string(self, id)
905 impl<'hir> intravisit::Map<'hir> for Map<'hir> {
906 fn find(&self, hir_id: HirId) -> Option<Node<'hir>> {
910 fn body(&self, id: BodyId) -> &'hir Body<'hir> {
914 fn item(&self, id: ItemId) -> &'hir Item<'hir> {
918 fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
922 fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
926 fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
927 self.foreign_item(id)
931 pub(super) fn index_hir<'tcx>(tcx: TyCtxt<'tcx>, (): ()) -> &'tcx IndexedHir<'tcx> {
932 let _prof_timer = tcx.sess.prof.generic_activity("build_hir_map");
934 let hcx = tcx.create_stable_hashing_context();
936 NodeCollector::root(tcx.sess, &**tcx.arena, tcx.untracked_crate, &tcx.definitions, hcx);
937 intravisit::walk_crate(&mut collector, tcx.untracked_crate);
939 let map = collector.finalize_and_compute_crate_hash();
943 pub(super) fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
944 assert_eq!(crate_num, LOCAL_CRATE);
946 let mut hcx = tcx.create_stable_hashing_context();
948 let mut hir_body_nodes: Vec<_> = tcx
952 .filter_map(|(def_id, hod)| {
953 let def_path_hash = tcx.definitions.def_path_hash(def_id);
954 let mut hasher = StableHasher::new();
955 hod.with_bodies.as_ref()?.hash_stable(&mut hcx, &mut hasher);
956 AttributeMap { map: &tcx.untracked_crate.attrs, prefix: def_id }
957 .hash_stable(&mut hcx, &mut hasher);
958 Some((def_path_hash, hasher.finish()))
961 hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
963 let node_hashes = hir_body_nodes.iter().fold(
965 |combined_fingerprint, &(def_path_hash, fingerprint)| {
966 combined_fingerprint.combine(def_path_hash.0.combine(fingerprint))
970 let upstream_crates = upstream_crates(&*tcx.cstore);
972 // We hash the final, remapped names of all local source files so we
973 // don't have to include the path prefix remapping commandline args.
974 // If we included the full mapping in the SVH, we could only have
975 // reproducible builds by compiling from the same directory. So we just
976 // hash the result of the mapping instead of the mapping itself.
977 let mut source_file_names: Vec<_> = tcx
982 .filter(|source_file| source_file.cnum == LOCAL_CRATE)
983 .map(|source_file| source_file.name_hash)
986 source_file_names.sort_unstable();
988 let mut stable_hasher = StableHasher::new();
989 node_hashes.hash_stable(&mut hcx, &mut stable_hasher);
990 upstream_crates.hash_stable(&mut hcx, &mut stable_hasher);
991 source_file_names.hash_stable(&mut hcx, &mut stable_hasher);
992 tcx.sess.opts.dep_tracking_hash(true).hash_stable(&mut hcx, &mut stable_hasher);
993 tcx.sess.local_crate_disambiguator().to_fingerprint().hash_stable(&mut hcx, &mut stable_hasher);
994 tcx.untracked_crate.non_exported_macro_attrs.hash_stable(&mut hcx, &mut stable_hasher);
996 let crate_hash: Fingerprint = stable_hasher.finish();
997 Svh::new(crate_hash.to_smaller_hash())
1000 fn upstream_crates(cstore: &dyn CrateStore) -> Vec<(Symbol, Fingerprint, Svh)> {
1001 let mut upstream_crates: Vec<_> = cstore
1005 let name = cstore.crate_name_untracked(cnum);
1006 let disambiguator = cstore.crate_disambiguator_untracked(cnum).to_fingerprint();
1007 let hash = cstore.crate_hash_untracked(cnum);
1008 (name, disambiguator, hash)
1011 upstream_crates.sort_unstable_by_key(|&(name, dis, _)| (name.as_str(), dis));
1015 fn hir_id_to_string(map: &Map<'_>, id: HirId) -> String {
1016 let id_str = format!(" (hir_id={})", id);
1019 // This functionality is used for debugging, try to use `TyCtxt` to get
1020 // the user-friendly path, otherwise fall back to stringifying `DefPath`.
1021 crate::ty::tls::with_opt(|tcx| {
1022 if let Some(tcx) = tcx {
1023 let def_id = map.local_def_id(id);
1024 tcx.def_path_str(def_id.to_def_id())
1025 } else if let Some(path) = map.def_path_from_hir_id(id) {
1026 path.data.into_iter().map(|elem| elem.to_string()).collect::<Vec<_>>().join("::")
1028 String::from("<missing path>")
1033 let span_str = || map.tcx.sess.source_map().span_to_snippet(map.span(id)).unwrap_or_default();
1034 let node_str = |prefix| format!("{} {}{}", prefix, span_str(), id_str);
1036 match map.find(id) {
1037 Some(Node::Item(item)) => {
1038 let item_str = match item.kind {
1039 ItemKind::ExternCrate(..) => "extern crate",
1040 ItemKind::Use(..) => "use",
1041 ItemKind::Static(..) => "static",
1042 ItemKind::Const(..) => "const",
1043 ItemKind::Fn(..) => "fn",
1044 ItemKind::Mod(..) => "mod",
1045 ItemKind::ForeignMod { .. } => "foreign mod",
1046 ItemKind::GlobalAsm(..) => "global asm",
1047 ItemKind::TyAlias(..) => "ty",
1048 ItemKind::OpaqueTy(..) => "opaque type",
1049 ItemKind::Enum(..) => "enum",
1050 ItemKind::Struct(..) => "struct",
1051 ItemKind::Union(..) => "union",
1052 ItemKind::Trait(..) => "trait",
1053 ItemKind::TraitAlias(..) => "trait alias",
1054 ItemKind::Impl { .. } => "impl",
1056 format!("{} {}{}", item_str, path_str(), id_str)
1058 Some(Node::ForeignItem(_)) => format!("foreign item {}{}", path_str(), id_str),
1059 Some(Node::ImplItem(ii)) => match ii.kind {
1060 ImplItemKind::Const(..) => {
1061 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1063 ImplItemKind::Fn(..) => format!("method {} in {}{}", ii.ident, path_str(), id_str),
1064 ImplItemKind::TyAlias(_) => {
1065 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1068 Some(Node::TraitItem(ti)) => {
1069 let kind = match ti.kind {
1070 TraitItemKind::Const(..) => "assoc constant",
1071 TraitItemKind::Fn(..) => "trait method",
1072 TraitItemKind::Type(..) => "assoc type",
1075 format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1077 Some(Node::Variant(ref variant)) => {
1078 format!("variant {} in {}{}", variant.ident, path_str(), id_str)
1080 Some(Node::Field(ref field)) => {
1081 format!("field {} in {}{}", field.ident, path_str(), id_str)
1083 Some(Node::AnonConst(_)) => node_str("const"),
1084 Some(Node::Expr(_)) => node_str("expr"),
1085 Some(Node::Stmt(_)) => node_str("stmt"),
1086 Some(Node::PathSegment(_)) => node_str("path segment"),
1087 Some(Node::Ty(_)) => node_str("type"),
1088 Some(Node::TraitRef(_)) => node_str("trait ref"),
1089 Some(Node::Binding(_)) => node_str("local"),
1090 Some(Node::Pat(_)) => node_str("pat"),
1091 Some(Node::Param(_)) => node_str("param"),
1092 Some(Node::Arm(_)) => node_str("arm"),
1093 Some(Node::Block(_)) => node_str("block"),
1094 Some(Node::Local(_)) => node_str("local"),
1095 Some(Node::Ctor(..)) => format!("ctor {}{}", path_str(), id_str),
1096 Some(Node::Lifetime(_)) => node_str("lifetime"),
1097 Some(Node::GenericParam(ref param)) => format!("generic_param {:?}{}", param, id_str),
1098 Some(Node::Visibility(ref vis)) => format!("visibility {:?}{}", vis, id_str),
1099 Some(Node::MacroDef(_)) => format!("macro {}{}", path_str(), id_str),
1100 Some(Node::Crate(..)) => String::from("root_crate"),
1101 None => format!("unknown node{}", id_str),