1 use self::collector::NodeCollector;
3 use crate::hir::{Owner, OwnerNodes};
4 use crate::ty::query::Providers;
7 use rustc_data_structures::svh::Svh;
8 use rustc_hir::def::{DefKind, Res};
9 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
10 use rustc_hir::definitions::{DefKey, DefPath, Definitions};
11 use rustc_hir::intravisit;
12 use rustc_hir::itemlikevisit::ItemLikeVisitor;
14 use rustc_index::vec::IndexVec;
15 use rustc_span::hygiene::MacroKind;
16 use rustc_span::source_map::Spanned;
17 use rustc_span::symbol::{kw, Ident, Symbol};
19 use rustc_target::spec::abi::Abi;
24 /// Represents an entry and its parent `HirId`.
25 #[derive(Copy, Clone, Debug)]
26 pub struct Entry<'hir> {
31 impl<'hir> Entry<'hir> {
32 fn parent_node(self) -> Option<HirId> {
34 Node::Crate(_) | Node::MacroDef(_) => None,
35 _ => Some(self.parent),
40 fn fn_decl<'hir>(node: Node<'hir>) -> Option<&'hir FnDecl<'hir>> {
42 Node::Item(Item { kind: ItemKind::Fn(sig, _, _), .. })
43 | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(sig, _), .. })
44 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(sig, _), .. }) => Some(&sig.decl),
45 Node::Expr(Expr { kind: ExprKind::Closure(_, fn_decl, ..), .. }) => Some(fn_decl),
50 fn fn_sig<'hir>(node: Node<'hir>) -> Option<&'hir FnSig<'hir>> {
52 Node::Item(Item { kind: ItemKind::Fn(sig, _, _), .. })
53 | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(sig, _), .. })
54 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(sig, _), .. }) => Some(sig),
59 pub fn associated_body<'hir>(node: Node<'hir>) -> Option<BodyId> {
62 kind: ItemKind::Const(_, body) | ItemKind::Static(.., body) | ItemKind::Fn(.., body),
65 | Node::TraitItem(TraitItem {
67 TraitItemKind::Const(_, Some(body)) | TraitItemKind::Fn(_, TraitFn::Provided(body)),
70 | Node::ImplItem(ImplItem {
71 kind: ImplItemKind::Const(_, body) | ImplItemKind::Fn(_, body),
74 | Node::Expr(Expr { kind: ExprKind::Closure(.., body, _, _), .. }) => Some(*body),
76 Node::AnonConst(constant) => Some(constant.body),
82 fn is_body_owner<'hir>(node: Node<'hir>, hir_id: HirId) -> bool {
83 match associated_body(node) {
84 Some(b) => b.hir_id == hir_id,
89 pub(super) struct HirOwnerData<'hir> {
90 pub(super) signature: Option<&'hir Owner<'hir>>,
91 pub(super) with_bodies: Option<&'hir mut OwnerNodes<'hir>>,
94 pub struct IndexedHir<'hir> {
95 /// The SVH of the local crate.
98 pub(super) map: IndexVec<LocalDefId, HirOwnerData<'hir>>,
101 #[derive(Copy, Clone)]
102 pub struct Map<'hir> {
103 pub(super) tcx: TyCtxt<'hir>,
106 /// An iterator that walks up the ancestor tree of a given `HirId`.
107 /// Constructed using `tcx.hir().parent_iter(hir_id)`.
108 pub struct ParentHirIterator<'map, 'hir> {
110 map: &'map Map<'hir>,
113 impl<'hir> Iterator for ParentHirIterator<'_, 'hir> {
114 type Item = (HirId, Node<'hir>);
116 fn next(&mut self) -> Option<Self::Item> {
117 if self.current_id == CRATE_HIR_ID {
121 // There are nodes that do not have entries, so we need to skip them.
122 let parent_id = self.map.get_parent_node(self.current_id);
124 if parent_id == self.current_id {
125 self.current_id = CRATE_HIR_ID;
129 self.current_id = parent_id;
130 if let Some(entry) = self.map.find_entry(parent_id) {
131 return Some((parent_id, entry.node));
133 // If this `HirId` doesn't have an `Entry`, skip it and look for its `parent_id`.
138 impl<'hir> Map<'hir> {
139 pub fn krate(&self) -> &'hir Crate<'hir> {
140 self.tcx.hir_crate(LOCAL_CRATE)
144 pub fn definitions(&self) -> &'hir Definitions {
145 &self.tcx.definitions
148 pub fn def_key(&self, def_id: LocalDefId) -> DefKey {
149 self.tcx.definitions.def_key(def_id)
152 pub fn def_path_from_hir_id(&self, id: HirId) -> Option<DefPath> {
153 self.opt_local_def_id(id).map(|def_id| self.def_path(def_id))
156 pub fn def_path(&self, def_id: LocalDefId) -> DefPath {
157 self.tcx.definitions.def_path(def_id)
161 pub fn local_def_id(&self, hir_id: HirId) -> LocalDefId {
162 self.opt_local_def_id(hir_id).unwrap_or_else(|| {
164 "local_def_id: no entry for `{:?}`, which has a map of `{:?}`",
166 self.find_entry(hir_id)
172 pub fn opt_local_def_id(&self, hir_id: HirId) -> Option<LocalDefId> {
173 self.tcx.definitions.opt_hir_id_to_local_def_id(hir_id)
177 pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
178 self.tcx.definitions.local_def_id_to_hir_id(def_id)
182 pub fn opt_local_def_id_to_hir_id(&self, def_id: LocalDefId) -> Option<HirId> {
183 self.tcx.definitions.opt_local_def_id_to_hir_id(def_id)
186 pub fn def_kind(&self, local_def_id: LocalDefId) -> DefKind {
187 // FIXME(eddyb) support `find` on the crate root.
188 if local_def_id.to_def_id().index == CRATE_DEF_INDEX {
192 let hir_id = self.local_def_id_to_hir_id(local_def_id);
193 match self.get(hir_id) {
194 Node::Item(item) => match item.kind {
195 ItemKind::Static(..) => DefKind::Static,
196 ItemKind::Const(..) => DefKind::Const,
197 ItemKind::Fn(..) => DefKind::Fn,
198 ItemKind::Mod(..) => DefKind::Mod,
199 ItemKind::OpaqueTy(..) => DefKind::OpaqueTy,
200 ItemKind::TyAlias(..) => DefKind::TyAlias,
201 ItemKind::Enum(..) => DefKind::Enum,
202 ItemKind::Struct(..) => DefKind::Struct,
203 ItemKind::Union(..) => DefKind::Union,
204 ItemKind::Trait(..) => DefKind::Trait,
205 ItemKind::TraitAlias(..) => DefKind::TraitAlias,
206 ItemKind::ExternCrate(_) => DefKind::ExternCrate,
207 ItemKind::Use(..) => DefKind::Use,
208 ItemKind::ForeignMod(..) => DefKind::ForeignMod,
209 ItemKind::GlobalAsm(..) => DefKind::GlobalAsm,
210 ItemKind::Impl { .. } => DefKind::Impl,
212 Node::ForeignItem(item) => match item.kind {
213 ForeignItemKind::Fn(..) => DefKind::Fn,
214 ForeignItemKind::Static(..) => DefKind::Static,
215 ForeignItemKind::Type => DefKind::ForeignTy,
217 Node::TraitItem(item) => match item.kind {
218 TraitItemKind::Const(..) => DefKind::AssocConst,
219 TraitItemKind::Fn(..) => DefKind::AssocFn,
220 TraitItemKind::Type(..) => DefKind::AssocTy,
222 Node::ImplItem(item) => match item.kind {
223 ImplItemKind::Const(..) => DefKind::AssocConst,
224 ImplItemKind::Fn(..) => DefKind::AssocFn,
225 ImplItemKind::TyAlias(..) => DefKind::AssocTy,
227 Node::Variant(_) => DefKind::Variant,
228 Node::Ctor(variant_data) => {
229 // FIXME(eddyb) is this even possible, if we have a `Node::Ctor`?
230 assert_ne!(variant_data.ctor_hir_id(), None);
232 let ctor_of = match self.find(self.get_parent_node(hir_id)) {
233 Some(Node::Item(..)) => def::CtorOf::Struct,
234 Some(Node::Variant(..)) => def::CtorOf::Variant,
237 DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data))
239 Node::AnonConst(_) => DefKind::AnonConst,
240 Node::Field(_) => DefKind::Field,
241 Node::Expr(expr) => match expr.kind {
242 ExprKind::Closure(.., None) => DefKind::Closure,
243 ExprKind::Closure(.., Some(_)) => DefKind::Generator,
244 _ => bug!("def_kind: unsupported node: {}", self.node_to_string(hir_id)),
246 Node::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
247 Node::GenericParam(param) => match param.kind {
248 GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam,
249 GenericParamKind::Type { .. } => DefKind::TyParam,
250 GenericParamKind::Const { .. } => DefKind::ConstParam,
253 | Node::PathSegment(_)
262 | Node::Visibility(_)
264 | Node::Crate(_) => bug!("def_kind: unsupported node: {}", self.node_to_string(hir_id)),
268 fn find_entry(&self, id: HirId) -> Option<Entry<'hir>> {
269 if id.local_id == ItemLocalId::from_u32(0) {
270 let owner = self.tcx.hir_owner(id.owner);
271 owner.map(|owner| Entry { parent: owner.parent, node: owner.node })
273 let owner = self.tcx.hir_owner_nodes(id.owner);
274 owner.and_then(|owner| {
275 let node = owner.nodes[id.local_id].as_ref();
276 // FIXME(eddyb) use a single generic type insted of having both
277 // `Entry` and `ParentedNode`, which are effectively the same.
278 // Alternatively, rewrite code using `Entry` to use `ParentedNode`.
279 node.map(|node| Entry {
280 parent: HirId { owner: id.owner, local_id: node.parent },
287 fn get_entry(&self, id: HirId) -> Entry<'hir> {
288 self.find_entry(id).unwrap()
291 pub fn item(&self, id: HirId) -> &'hir Item<'hir> {
292 match self.find(id).unwrap() {
293 Node::Item(item) => item,
298 pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
299 match self.find(id.hir_id).unwrap() {
300 Node::TraitItem(item) => item,
305 pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
306 match self.find(id.hir_id).unwrap() {
307 Node::ImplItem(item) => item,
312 pub fn body(&self, id: BodyId) -> &'hir Body<'hir> {
313 self.tcx.hir_owner_nodes(id.hir_id.owner).unwrap().bodies.get(&id.hir_id.local_id).unwrap()
316 pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnDecl<'hir>> {
317 if let Some(node) = self.find(hir_id) {
320 bug!("no node for hir_id `{}`", hir_id)
324 pub fn fn_sig_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnSig<'hir>> {
325 if let Some(node) = self.find(hir_id) {
328 bug!("no node for hir_id `{}`", hir_id)
332 pub fn enclosing_body_owner(&self, hir_id: HirId) -> HirId {
333 for (parent, _) in self.parent_iter(hir_id) {
334 if let Some(body) = self.maybe_body_owned_by(parent) {
335 return self.body_owner(body);
339 bug!("no `enclosing_body_owner` for hir_id `{}`", hir_id);
342 /// Returns the `HirId` that corresponds to the definition of
343 /// which this is the body of, i.e., a `fn`, `const` or `static`
344 /// item (possibly associated), a closure, or a `hir::AnonConst`.
345 pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> HirId {
346 let parent = self.get_parent_node(hir_id);
347 assert!(self.find(parent).map_or(false, |n| is_body_owner(n, hir_id)));
351 pub fn body_owner_def_id(&self, id: BodyId) -> LocalDefId {
352 self.local_def_id(self.body_owner(id))
355 /// Given a `HirId`, returns the `BodyId` associated with it,
356 /// if the node is a body owner, otherwise returns `None`.
357 pub fn maybe_body_owned_by(&self, hir_id: HirId) -> Option<BodyId> {
358 self.find(hir_id).map(associated_body).flatten()
361 /// Given a body owner's id, returns the `BodyId` associated with it.
362 pub fn body_owned_by(&self, id: HirId) -> BodyId {
363 self.maybe_body_owned_by(id).unwrap_or_else(|| {
366 "body_owned_by: {} has no associated body",
367 self.node_to_string(id)
372 pub fn body_param_names(&self, id: BodyId) -> impl Iterator<Item = Ident> + 'hir {
373 self.body(id).params.iter().map(|arg| match arg.pat.kind {
374 PatKind::Binding(_, _, ident, _) => ident,
375 _ => Ident::new(kw::Invalid, rustc_span::DUMMY_SP),
379 /// Returns the `BodyOwnerKind` of this `LocalDefId`.
381 /// Panics if `LocalDefId` does not have an associated body.
382 pub fn body_owner_kind(&self, id: HirId) -> BodyOwnerKind {
384 Node::Item(&Item { kind: ItemKind::Const(..), .. })
385 | Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. })
386 | Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. })
387 | Node::AnonConst(_) => BodyOwnerKind::Const,
389 | Node::Item(&Item { kind: ItemKind::Fn(..), .. })
390 | Node::TraitItem(&TraitItem { kind: TraitItemKind::Fn(..), .. })
391 | Node::ImplItem(&ImplItem { kind: ImplItemKind::Fn(..), .. }) => BodyOwnerKind::Fn,
392 Node::Item(&Item { kind: ItemKind::Static(_, m, _), .. }) => BodyOwnerKind::Static(m),
393 Node::Expr(&Expr { kind: ExprKind::Closure(..), .. }) => BodyOwnerKind::Closure,
394 node => bug!("{:#?} is not a body node", node),
398 /// Returns the `ConstContext` of the body associated with this `LocalDefId`.
400 /// Panics if `LocalDefId` does not have an associated body.
401 pub fn body_const_context(&self, did: LocalDefId) -> Option<ConstContext> {
402 let hir_id = self.local_def_id_to_hir_id(did);
403 let ccx = match self.body_owner_kind(hir_id) {
404 BodyOwnerKind::Const => ConstContext::Const,
405 BodyOwnerKind::Static(mt) => ConstContext::Static(mt),
407 BodyOwnerKind::Fn if self.tcx.is_constructor(did.to_def_id()) => return None,
408 BodyOwnerKind::Fn if self.tcx.is_const_fn_raw(did.to_def_id()) => ConstContext::ConstFn,
409 BodyOwnerKind::Fn | BodyOwnerKind::Closure => return None,
415 pub fn ty_param_owner(&self, id: HirId) -> HirId {
417 Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => id,
418 Node::GenericParam(_) => self.get_parent_node(id),
419 _ => bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id)),
423 pub fn ty_param_name(&self, id: HirId) -> Symbol {
425 Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => {
428 Node::GenericParam(param) => param.name.ident().name,
429 _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
433 pub fn trait_impls(&self, trait_did: DefId) -> &'hir [HirId] {
434 self.tcx.all_local_trait_impls(LOCAL_CRATE).get(&trait_did).map_or(&[], |xs| &xs[..])
437 /// Gets the attributes on the crate. This is preferable to
438 /// invoking `krate.attrs` because it registers a tighter
439 /// dep-graph access.
440 pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
441 match self.get_entry(CRATE_HIR_ID).node {
442 Node::Crate(item) => item.attrs,
447 pub fn get_module(&self, module: LocalDefId) -> (&'hir Mod<'hir>, Span, HirId) {
448 let hir_id = self.local_def_id_to_hir_id(module);
449 match self.get_entry(hir_id).node {
450 Node::Item(&Item { span, kind: ItemKind::Mod(ref m), .. }) => (m, span, hir_id),
451 Node::Crate(item) => (&item.module, item.span, hir_id),
452 node => panic!("not a module: {:?}", node),
456 pub fn visit_item_likes_in_module<V>(&self, module: LocalDefId, visitor: &mut V)
458 V: ItemLikeVisitor<'hir>,
460 let module = self.tcx.hir_module_items(module);
462 for id in &module.items {
463 visitor.visit_item(self.expect_item(*id));
466 for id in &module.trait_items {
467 visitor.visit_trait_item(self.expect_trait_item(id.hir_id));
470 for id in &module.impl_items {
471 visitor.visit_impl_item(self.expect_impl_item(id.hir_id));
475 /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found.
476 pub fn get(&self, id: HirId) -> Node<'hir> {
477 self.find(id).unwrap_or_else(|| bug!("couldn't find hir id {} in the HIR map", id))
480 pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
481 id.as_local().and_then(|id| self.find(self.local_def_id_to_hir_id(id)))
484 pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics<'hir>> {
485 self.get_if_local(id).and_then(|node| match &node {
486 Node::ImplItem(impl_item) => Some(&impl_item.generics),
487 Node::TraitItem(trait_item) => Some(&trait_item.generics),
490 ItemKind::Fn(_, generics, _)
491 | ItemKind::TyAlias(_, generics)
492 | ItemKind::Enum(_, generics)
493 | ItemKind::Struct(_, generics)
494 | ItemKind::Union(_, generics)
495 | ItemKind::Trait(_, _, generics, ..)
496 | ItemKind::TraitAlias(generics, _)
497 | ItemKind::Impl { generics, .. },
499 }) => Some(generics),
504 /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
505 pub fn find(&self, hir_id: HirId) -> Option<Node<'hir>> {
506 self.find_entry(hir_id).and_then(|entry| {
507 if let Node::Crate(..) = entry.node { None } else { Some(entry.node) }
511 /// Similar to `get_parent`; returns the parent HIR Id, or just `hir_id` if there
512 /// is no parent. Note that the parent may be `CRATE_HIR_ID`, which is not itself
513 /// present in the map, so passing the return value of `get_parent_node` to
514 /// `get` may in fact panic.
515 /// This function returns the immediate parent in the HIR, whereas `get_parent`
516 /// returns the enclosing item. Note that this might not be the actual parent
517 /// node in the HIR -- some kinds of nodes are not in the map and these will
518 /// never appear as the parent node. Thus, you can always walk the parent nodes
519 /// from a node to the root of the HIR (unless you get back the same ID here,
520 /// which can happen if the ID is not in the map itself or is just weird).
521 pub fn get_parent_node(&self, hir_id: HirId) -> HirId {
522 self.get_entry(hir_id).parent_node().unwrap_or(hir_id)
525 /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
526 /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`.
527 pub fn parent_iter(&self, current_id: HirId) -> ParentHirIterator<'_, 'hir> {
528 ParentHirIterator { current_id, map: self }
531 /// Checks if the node is an argument. An argument is a local variable whose
532 /// immediate parent is an item or a closure.
533 pub fn is_argument(&self, id: HirId) -> bool {
534 match self.find(id) {
535 Some(Node::Binding(_)) => (),
539 self.find(self.get_parent_node(id)),
544 | Node::Expr(Expr { kind: ExprKind::Closure(..), .. }),
549 /// Whether the expression pointed at by `hir_id` belongs to a `const` evaluation context.
550 /// Used exclusively for diagnostics, to avoid suggestion function calls.
551 pub fn is_inside_const_context(&self, hir_id: HirId) -> bool {
552 self.body_const_context(self.local_def_id(self.enclosing_body_owner(hir_id))).is_some()
555 /// Whether `hir_id` corresponds to a `mod` or a crate.
556 pub fn is_hir_id_module(&self, hir_id: HirId) -> bool {
558 self.get_entry(hir_id).node,
559 Node::Item(Item { kind: ItemKind::Mod(_), .. }) | Node::Crate(..)
563 /// Retrieves the `HirId` for `id`'s enclosing method, unless there's a
564 /// `while` or `loop` before reaching it, as block tail returns are not
565 /// available in them.
568 /// fn foo(x: usize) -> bool {
570 /// true // If `get_return_block` gets passed the `id` corresponding
571 /// } else { // to this, it will return `foo`'s `HirId`.
578 /// fn foo(x: usize) -> bool {
580 /// true // If `get_return_block` gets passed the `id` corresponding
581 /// } // to this, it will return `None`.
585 pub fn get_return_block(&self, id: HirId) -> Option<HirId> {
586 let mut iter = self.parent_iter(id).peekable();
587 let mut ignore_tail = false;
588 if let Some(entry) = self.find_entry(id) {
589 if let Node::Expr(Expr { kind: ExprKind::Ret(_), .. }) = entry.node {
590 // When dealing with `return` statements, we don't care about climbing only tail
595 while let Some((hir_id, node)) = iter.next() {
596 if let (Some((_, next_node)), false) = (iter.peek(), ignore_tail) {
598 Node::Block(Block { expr: None, .. }) => return None,
599 // The current node is not the tail expression of its parent.
600 Node::Block(Block { expr: Some(e), .. }) if hir_id != e.hir_id => return None,
606 | Node::ForeignItem(_)
608 | Node::Expr(Expr { kind: ExprKind::Closure(..), .. })
609 | Node::ImplItem(_) => return Some(hir_id),
610 // Ignore `return`s on the first iteration
611 Node::Expr(Expr { kind: ExprKind::Loop(..) | ExprKind::Ret(..), .. })
612 | Node::Local(_) => {
621 /// Retrieves the `HirId` for `id`'s parent item, or `id` itself if no
622 /// parent item is in this map. The "parent item" is the closest parent node
623 /// in the HIR which is recorded by the map and is an item, either an item
624 /// in a module, trait, or impl.
625 pub fn get_parent_item(&self, hir_id: HirId) -> HirId {
626 for (hir_id, node) in self.parent_iter(hir_id) {
630 | Node::ForeignItem(_)
632 | Node::ImplItem(_) => return hir_id,
639 /// Returns the `HirId` of `id`'s nearest module parent, or `id` itself if no
640 /// module parent is in this map.
641 pub(super) fn get_module_parent_node(&self, hir_id: HirId) -> HirId {
642 for (hir_id, node) in self.parent_iter(hir_id) {
643 if let Node::Item(&Item { kind: ItemKind::Mod(_), .. }) = node {
650 /// When on a match arm tail expression or on a match arm, give back the enclosing `match`
653 /// Used by error reporting when there's a type error in a match arm caused by the `match`
654 /// expression needing to be unit.
655 pub fn get_match_if_cause(&self, hir_id: HirId) -> Option<&'hir Expr<'hir>> {
656 for (_, node) in self.parent_iter(hir_id) {
659 | Node::ForeignItem(_)
662 | Node::Stmt(Stmt { kind: StmtKind::Local(_), .. }) => break,
663 Node::Expr(expr @ Expr { kind: ExprKind::Match(..), .. }) => return Some(expr),
670 /// Returns the nearest enclosing scope. A scope is roughly an item or block.
671 pub fn get_enclosing_scope(&self, hir_id: HirId) -> Option<HirId> {
672 for (hir_id, node) in self.parent_iter(hir_id) {
673 if let Node::Item(Item {
676 | ItemKind::Const(..)
677 | ItemKind::Static(..)
680 | ItemKind::Struct(..)
681 | ItemKind::Union(..)
682 | ItemKind::Trait(..)
683 | ItemKind::Impl { .. },
686 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(..), .. })
687 | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(..), .. })
688 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(..), .. })
689 | Node::Block(_) = node
697 /// Returns the defining scope for an opaque type definition.
698 pub fn get_defining_scope(&self, id: HirId) -> HirId {
701 scope = self.get_enclosing_scope(scope).unwrap_or(CRATE_HIR_ID);
702 if scope == CRATE_HIR_ID {
705 match self.get(scope) {
713 pub fn get_parent_did(&self, id: HirId) -> LocalDefId {
714 self.local_def_id(self.get_parent_item(id))
717 pub fn get_foreign_abi(&self, hir_id: HirId) -> Abi {
718 let parent = self.get_parent_item(hir_id);
719 if let Some(entry) = self.find_entry(parent) {
721 node: Node::Item(Item { kind: ItemKind::ForeignMod(ref nm), .. }), ..
727 bug!("expected foreign mod or inlined parent, found {}", self.node_to_string(parent))
730 pub fn expect_item(&self, id: HirId) -> &'hir Item<'hir> {
731 match self.find(id) {
732 Some(Node::Item(item)) => item,
733 _ => bug!("expected item, found {}", self.node_to_string(id)),
737 pub fn expect_impl_item(&self, id: HirId) -> &'hir ImplItem<'hir> {
738 match self.find(id) {
739 Some(Node::ImplItem(item)) => item,
740 _ => bug!("expected impl item, found {}", self.node_to_string(id)),
744 pub fn expect_trait_item(&self, id: HirId) -> &'hir TraitItem<'hir> {
745 match self.find(id) {
746 Some(Node::TraitItem(item)) => item,
747 _ => bug!("expected trait item, found {}", self.node_to_string(id)),
751 pub fn expect_variant_data(&self, id: HirId) -> &'hir VariantData<'hir> {
752 match self.find(id) {
755 | Node::Item(Item { kind: ItemKind::Struct(vd, _) | ItemKind::Union(vd, _), .. }),
757 Some(Node::Variant(variant)) => &variant.data,
758 _ => bug!("expected struct or variant, 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_expr(&self, id: HirId) -> &'hir Expr<'hir> {
777 match self.find(id) {
778 Some(Node::Expr(expr)) => expr,
779 _ => bug!("expected expr, found {}", self.node_to_string(id)),
783 pub fn opt_name(&self, id: HirId) -> Option<Symbol> {
784 Some(match self.get(id) {
785 Node::Item(i) => i.ident.name,
786 Node::ForeignItem(fi) => fi.ident.name,
787 Node::ImplItem(ii) => ii.ident.name,
788 Node::TraitItem(ti) => ti.ident.name,
789 Node::Variant(v) => v.ident.name,
790 Node::Field(f) => f.ident.name,
791 Node::Lifetime(lt) => lt.name.ident().name,
792 Node::GenericParam(param) => param.name.ident().name,
793 Node::Binding(&Pat { kind: PatKind::Binding(_, _, l, _), .. }) => l.name,
794 Node::Ctor(..) => self.name(self.get_parent_item(id)),
799 pub fn name(&self, id: HirId) -> Symbol {
800 match self.opt_name(id) {
802 None => bug!("no name for {}", self.node_to_string(id)),
806 /// Given a node ID, gets a list of attributes associated with the AST
807 /// corresponding to the node-ID.
808 pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] {
809 let attrs = self.find_entry(id).map(|entry| match entry.node {
810 Node::Param(a) => &a.attrs[..],
811 Node::Local(l) => &l.attrs[..],
812 Node::Item(i) => &i.attrs[..],
813 Node::ForeignItem(fi) => &fi.attrs[..],
814 Node::TraitItem(ref ti) => &ti.attrs[..],
815 Node::ImplItem(ref ii) => &ii.attrs[..],
816 Node::Variant(ref v) => &v.attrs[..],
817 Node::Field(ref f) => &f.attrs[..],
818 Node::Expr(ref e) => &*e.attrs,
819 Node::Stmt(ref s) => s.kind.attrs(|id| self.item(id.id)),
820 Node::Arm(ref a) => &*a.attrs,
821 Node::GenericParam(param) => ¶m.attrs[..],
822 // Unit/tuple structs/variants take the attributes straight from
823 // the struct/variant definition.
824 Node::Ctor(..) => self.attrs(self.get_parent_item(id)),
825 Node::Crate(item) => &item.attrs[..],
826 Node::MacroDef(def) => def.attrs,
828 | Node::PathSegment(..)
835 | Node::Visibility(..) => &[],
840 /// Gets the span of the definition of the specified HIR node.
841 /// This is used by `tcx.get_span`
842 pub fn span(&self, hir_id: HirId) -> Span {
843 match self.find_entry(hir_id).map(|entry| entry.node) {
844 Some(Node::Param(param)) => param.span,
845 Some(Node::Item(item)) => match &item.kind {
846 ItemKind::Fn(sig, _, _) => sig.span,
849 Some(Node::ForeignItem(foreign_item)) => foreign_item.span,
850 Some(Node::TraitItem(trait_item)) => match &trait_item.kind {
851 TraitItemKind::Fn(sig, _) => sig.span,
852 _ => trait_item.span,
854 Some(Node::ImplItem(impl_item)) => match &impl_item.kind {
855 ImplItemKind::Fn(sig, _) => sig.span,
858 Some(Node::Variant(variant)) => variant.span,
859 Some(Node::Field(field)) => field.span,
860 Some(Node::AnonConst(constant)) => self.body(constant.body).value.span,
861 Some(Node::Expr(expr)) => expr.span,
862 Some(Node::Stmt(stmt)) => stmt.span,
863 Some(Node::PathSegment(seg)) => seg.ident.span,
864 Some(Node::Ty(ty)) => ty.span,
865 Some(Node::TraitRef(tr)) => tr.path.span,
866 Some(Node::Binding(pat)) => pat.span,
867 Some(Node::Pat(pat)) => pat.span,
868 Some(Node::Arm(arm)) => arm.span,
869 Some(Node::Block(block)) => block.span,
870 Some(Node::Ctor(..)) => match self.find(self.get_parent_node(hir_id)) {
871 Some(Node::Item(item)) => item.span,
872 Some(Node::Variant(variant)) => variant.span,
875 Some(Node::Lifetime(lifetime)) => lifetime.span,
876 Some(Node::GenericParam(param)) => param.span,
877 Some(Node::Visibility(&Spanned {
878 node: VisibilityKind::Restricted { ref path, .. },
881 Some(Node::Visibility(v)) => bug!("unexpected Visibility {:?}", v),
882 Some(Node::Local(local)) => local.span,
883 Some(Node::MacroDef(macro_def)) => macro_def.span,
884 Some(Node::Crate(item)) => item.span,
885 None => bug!("hir::map::Map::span: id not in map: {:?}", hir_id),
889 /// Like `hir.span()`, but includes the body of function items
890 /// (instead of just the function header)
891 pub fn span_with_body(&self, hir_id: HirId) -> Span {
892 match self.find_entry(hir_id).map(|entry| entry.node) {
893 Some(Node::TraitItem(item)) => item.span,
894 Some(Node::ImplItem(impl_item)) => impl_item.span,
895 Some(Node::Item(item)) => item.span,
896 Some(_) => self.span(hir_id),
897 _ => bug!("hir::map::Map::span_with_body: id not in map: {:?}", hir_id),
901 pub fn span_if_local(&self, id: DefId) -> Option<Span> {
902 id.as_local().map(|id| self.span(self.local_def_id_to_hir_id(id)))
905 pub fn res_span(&self, res: Res) -> Option<Span> {
908 Res::Local(id) => Some(self.span(id)),
909 res => self.span_if_local(res.opt_def_id()?),
913 /// Get a representation of this `id` for debugging purposes.
914 /// NOTE: Do NOT use this in diagnostics!
915 pub fn node_to_string(&self, id: HirId) -> String {
916 hir_id_to_string(self, id)
920 impl<'hir> intravisit::Map<'hir> for Map<'hir> {
921 fn find(&self, hir_id: HirId) -> Option<Node<'hir>> {
925 fn body(&self, id: BodyId) -> &'hir Body<'hir> {
929 fn item(&self, id: HirId) -> &'hir Item<'hir> {
933 fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
937 fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
943 fn name(&self) -> Symbol;
946 impl<T: Named> Named for Spanned<T> {
947 fn name(&self) -> Symbol {
952 impl Named for Item<'_> {
953 fn name(&self) -> Symbol {
957 impl Named for ForeignItem<'_> {
958 fn name(&self) -> Symbol {
962 impl Named for Variant<'_> {
963 fn name(&self) -> Symbol {
967 impl Named for StructField<'_> {
968 fn name(&self) -> Symbol {
972 impl Named for TraitItem<'_> {
973 fn name(&self) -> Symbol {
977 impl Named for ImplItem<'_> {
978 fn name(&self) -> Symbol {
983 pub(super) fn index_hir<'tcx>(tcx: TyCtxt<'tcx>, cnum: CrateNum) -> &'tcx IndexedHir<'tcx> {
984 assert_eq!(cnum, LOCAL_CRATE);
986 let _prof_timer = tcx.sess.prof.generic_activity("build_hir_map");
988 let (map, crate_hash) = {
989 let hcx = tcx.create_stable_hashing_context();
992 NodeCollector::root(tcx.sess, &**tcx.arena, tcx.untracked_crate, &tcx.definitions, hcx);
993 intravisit::walk_crate(&mut collector, tcx.untracked_crate);
995 let crate_disambiguator = tcx.sess.local_crate_disambiguator();
996 let cmdline_args = tcx.sess.opts.dep_tracking_hash();
997 collector.finalize_and_compute_crate_hash(crate_disambiguator, &*tcx.cstore, cmdline_args)
1000 tcx.arena.alloc(IndexedHir { crate_hash, map })
1003 fn hir_id_to_string(map: &Map<'_>, id: HirId) -> String {
1004 let id_str = format!(" (hir_id={})", id);
1007 // This functionality is used for debugging, try to use `TyCtxt` to get
1008 // the user-friendly path, otherwise fall back to stringifying `DefPath`.
1009 crate::ty::tls::with_opt(|tcx| {
1010 if let Some(tcx) = tcx {
1011 let def_id = map.local_def_id(id);
1012 tcx.def_path_str(def_id.to_def_id())
1013 } else if let Some(path) = map.def_path_from_hir_id(id) {
1014 path.data.into_iter().map(|elem| elem.to_string()).collect::<Vec<_>>().join("::")
1016 String::from("<missing path>")
1021 let span_str = || map.tcx.sess.source_map().span_to_snippet(map.span(id)).unwrap_or_default();
1022 let node_str = |prefix| format!("{} {}{}", prefix, span_str(), id_str);
1024 match map.find(id) {
1025 Some(Node::Item(item)) => {
1026 let item_str = match item.kind {
1027 ItemKind::ExternCrate(..) => "extern crate",
1028 ItemKind::Use(..) => "use",
1029 ItemKind::Static(..) => "static",
1030 ItemKind::Const(..) => "const",
1031 ItemKind::Fn(..) => "fn",
1032 ItemKind::Mod(..) => "mod",
1033 ItemKind::ForeignMod(..) => "foreign mod",
1034 ItemKind::GlobalAsm(..) => "global asm",
1035 ItemKind::TyAlias(..) => "ty",
1036 ItemKind::OpaqueTy(..) => "opaque type",
1037 ItemKind::Enum(..) => "enum",
1038 ItemKind::Struct(..) => "struct",
1039 ItemKind::Union(..) => "union",
1040 ItemKind::Trait(..) => "trait",
1041 ItemKind::TraitAlias(..) => "trait alias",
1042 ItemKind::Impl { .. } => "impl",
1044 format!("{} {}{}", item_str, path_str(), id_str)
1046 Some(Node::ForeignItem(_)) => format!("foreign item {}{}", path_str(), id_str),
1047 Some(Node::ImplItem(ii)) => match ii.kind {
1048 ImplItemKind::Const(..) => {
1049 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1051 ImplItemKind::Fn(..) => format!("method {} in {}{}", ii.ident, path_str(), id_str),
1052 ImplItemKind::TyAlias(_) => {
1053 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1056 Some(Node::TraitItem(ti)) => {
1057 let kind = match ti.kind {
1058 TraitItemKind::Const(..) => "assoc constant",
1059 TraitItemKind::Fn(..) => "trait method",
1060 TraitItemKind::Type(..) => "assoc type",
1063 format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1065 Some(Node::Variant(ref variant)) => {
1066 format!("variant {} in {}{}", variant.ident, path_str(), id_str)
1068 Some(Node::Field(ref field)) => {
1069 format!("field {} in {}{}", field.ident, path_str(), id_str)
1071 Some(Node::AnonConst(_)) => node_str("const"),
1072 Some(Node::Expr(_)) => node_str("expr"),
1073 Some(Node::Stmt(_)) => node_str("stmt"),
1074 Some(Node::PathSegment(_)) => node_str("path segment"),
1075 Some(Node::Ty(_)) => node_str("type"),
1076 Some(Node::TraitRef(_)) => node_str("trait ref"),
1077 Some(Node::Binding(_)) => node_str("local"),
1078 Some(Node::Pat(_)) => node_str("pat"),
1079 Some(Node::Param(_)) => node_str("param"),
1080 Some(Node::Arm(_)) => node_str("arm"),
1081 Some(Node::Block(_)) => node_str("block"),
1082 Some(Node::Local(_)) => node_str("local"),
1083 Some(Node::Ctor(..)) => format!("ctor {}{}", path_str(), id_str),
1084 Some(Node::Lifetime(_)) => node_str("lifetime"),
1085 Some(Node::GenericParam(ref param)) => format!("generic_param {:?}{}", param, id_str),
1086 Some(Node::Visibility(ref vis)) => format!("visibility {:?}{}", vis, id_str),
1087 Some(Node::MacroDef(_)) => format!("macro {}{}", path_str(), id_str),
1088 Some(Node::Crate(..)) => String::from("root_crate"),
1089 None => format!("unknown node{}", id_str),
1093 pub fn provide(providers: &mut Providers) {
1094 providers.def_kind = |tcx, def_id| tcx.hir().def_kind(def_id.expect_local());