1 use crate::hir::{ModuleItems, Owner};
2 use crate::ty::{DefIdTree, TyCtxt};
4 use rustc_data_structures::fingerprint::Fingerprint;
5 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
6 use rustc_data_structures::svh::Svh;
7 use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
8 use rustc_hir::def::{DefKind, Res};
9 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE};
10 use rustc_hir::definitions::{DefKey, DefPath, DefPathHash};
11 use rustc_hir::intravisit::{self, Visitor};
13 use rustc_index::vec::Idx;
14 use rustc_middle::hir::nested_filter;
15 use rustc_span::def_id::StableCrateId;
16 use rustc_span::symbol::{kw, sym, Ident, Symbol};
17 use rustc_span::{Span, DUMMY_SP};
18 use rustc_target::spec::abi::Abi;
21 pub fn associated_body<'hir>(node: Node<'hir>) -> Option<BodyId> {
24 kind: ItemKind::Const(_, body) | ItemKind::Static(.., body) | ItemKind::Fn(.., body),
27 | Node::TraitItem(TraitItem {
29 TraitItemKind::Const(_, Some(body)) | TraitItemKind::Fn(_, TraitFn::Provided(body)),
32 | Node::ImplItem(ImplItem {
33 kind: ImplItemKind::Const(_, body) | ImplItemKind::Fn(_, body),
36 | Node::Expr(Expr { kind: ExprKind::Closure(Closure { body, .. }), .. }) => Some(*body),
38 Node::AnonConst(constant) => Some(constant.body),
44 fn is_body_owner<'hir>(node: Node<'hir>, hir_id: HirId) -> bool {
45 match associated_body(node) {
46 Some(b) => b.hir_id == hir_id,
51 #[derive(Copy, Clone)]
52 pub struct Map<'hir> {
53 pub(super) tcx: TyCtxt<'hir>,
56 /// An iterator that walks up the ancestor tree of a given `HirId`.
57 /// Constructed using `tcx.hir().parent_iter(hir_id)`.
58 pub struct ParentHirIterator<'hir> {
63 impl<'hir> Iterator for ParentHirIterator<'hir> {
66 fn next(&mut self) -> Option<Self::Item> {
67 if self.current_id == CRATE_HIR_ID {
71 // There are nodes that do not have entries, so we need to skip them.
72 let parent_id = self.map.get_parent_node(self.current_id);
74 if parent_id == self.current_id {
75 self.current_id = CRATE_HIR_ID;
79 self.current_id = parent_id;
80 return Some(parent_id);
85 /// An iterator that walks up the ancestor tree of a given `HirId`.
86 /// Constructed using `tcx.hir().parent_owner_iter(hir_id)`.
87 pub struct ParentOwnerIterator<'hir> {
92 impl<'hir> Iterator for ParentOwnerIterator<'hir> {
93 type Item = (OwnerId, OwnerNode<'hir>);
95 fn next(&mut self) -> Option<Self::Item> {
96 if self.current_id.local_id.index() != 0 {
97 self.current_id.local_id = ItemLocalId::new(0);
98 if let Some(node) = self.map.tcx.hir_owner(self.current_id.owner) {
99 return Some((self.current_id.owner, node.node));
102 if self.current_id == CRATE_HIR_ID {
106 // There are nodes that do not have entries, so we need to skip them.
107 let parent_id = self.map.def_key(self.current_id.owner.def_id).parent;
109 let parent_id = parent_id.map_or(CRATE_OWNER_ID, |local_def_index| {
110 let def_id = LocalDefId { local_def_index };
111 self.map.local_def_id_to_hir_id(def_id).owner
113 self.current_id = HirId::make_owner(parent_id.def_id);
115 // If this `HirId` doesn't have an entry, skip it and look for its `parent_id`.
116 if let Some(node) = self.map.tcx.hir_owner(self.current_id.owner) {
117 return Some((self.current_id.owner, node.node));
123 impl<'hir> Map<'hir> {
125 pub fn krate(self) -> &'hir Crate<'hir> {
126 self.tcx.hir_crate(())
130 pub fn root_module(self) -> &'hir Mod<'hir> {
131 match self.tcx.hir_owner(CRATE_OWNER_ID).map(|o| o.node) {
132 Some(OwnerNode::Crate(item)) => item,
138 pub fn items(self) -> impl Iterator<Item = ItemId> + 'hir {
139 self.tcx.hir_crate_items(()).items.iter().copied()
143 pub fn module_items(self, module: LocalDefId) -> impl Iterator<Item = ItemId> + 'hir {
144 self.tcx.hir_module_items(module).items()
148 pub fn par_for_each_item(self, f: impl Fn(ItemId) + Sync + Send) {
149 par_for_each_in(&self.tcx.hir_crate_items(()).items[..], |id| f(*id));
152 pub fn def_key(self, def_id: LocalDefId) -> DefKey {
153 // Accessing the DefKey is ok, since it is part of DefPathHash.
154 self.tcx.definitions_untracked().def_key(def_id)
157 pub fn def_path_from_hir_id(self, id: HirId) -> Option<DefPath> {
158 self.opt_local_def_id(id).map(|def_id| self.def_path(def_id))
161 pub fn def_path(self, def_id: LocalDefId) -> DefPath {
162 // Accessing the DefPath is ok, since it is part of DefPathHash.
163 self.tcx.definitions_untracked().def_path(def_id)
167 pub fn def_path_hash(self, def_id: LocalDefId) -> DefPathHash {
168 // Accessing the DefPathHash is ok, it is incr. comp. stable.
169 self.tcx.definitions_untracked().def_path_hash(def_id)
173 pub fn local_def_id(self, hir_id: HirId) -> LocalDefId {
174 self.opt_local_def_id(hir_id).unwrap_or_else(|| {
176 "local_def_id: no entry for `{:?}`, which has a map of `{:?}`",
184 pub fn opt_local_def_id(self, hir_id: HirId) -> Option<LocalDefId> {
185 if hir_id.local_id == ItemLocalId::new(0) {
186 Some(hir_id.owner.def_id)
189 .hir_owner_nodes(hir_id.owner)
192 .get(&hir_id.local_id)
198 pub fn local_def_id_to_hir_id(self, def_id: LocalDefId) -> HirId {
199 self.tcx.local_def_id_to_hir_id(def_id)
202 /// Do not call this function directly. The query should be called.
203 pub(super) fn opt_def_kind(self, local_def_id: LocalDefId) -> Option<DefKind> {
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(_, mt, _) => DefKind::Static(mt),
208 ItemKind::Const(..) => DefKind::Const,
209 ItemKind::Fn(..) => DefKind::Fn,
210 ItemKind::Macro(_, macro_kind) => DefKind::Macro(macro_kind),
211 ItemKind::Mod(..) => DefKind::Mod,
212 ItemKind::OpaqueTy(ref opaque) => {
214 DefKind::ImplTraitPlaceholder
219 ItemKind::TyAlias(..) => DefKind::TyAlias,
220 ItemKind::Enum(..) => DefKind::Enum,
221 ItemKind::Struct(..) => DefKind::Struct,
222 ItemKind::Union(..) => DefKind::Union,
223 ItemKind::Trait(..) => DefKind::Trait,
224 ItemKind::TraitAlias(..) => DefKind::TraitAlias,
225 ItemKind::ExternCrate(_) => DefKind::ExternCrate,
226 ItemKind::Use(..) => DefKind::Use,
227 ItemKind::ForeignMod { .. } => DefKind::ForeignMod,
228 ItemKind::GlobalAsm(..) => DefKind::GlobalAsm,
229 ItemKind::Impl { .. } => DefKind::Impl,
231 Node::ForeignItem(item) => match item.kind {
232 ForeignItemKind::Fn(..) => DefKind::Fn,
233 ForeignItemKind::Static(_, mt) => DefKind::Static(mt),
234 ForeignItemKind::Type => DefKind::ForeignTy,
236 Node::TraitItem(item) => match item.kind {
237 TraitItemKind::Const(..) => DefKind::AssocConst,
238 TraitItemKind::Fn(..) => DefKind::AssocFn,
239 TraitItemKind::Type(..) => DefKind::AssocTy,
241 Node::ImplItem(item) => match item.kind {
242 ImplItemKind::Const(..) => DefKind::AssocConst,
243 ImplItemKind::Fn(..) => DefKind::AssocFn,
244 ImplItemKind::Type(..) => DefKind::AssocTy,
246 Node::Variant(_) => DefKind::Variant,
247 Node::Ctor(variant_data) => {
248 // FIXME(eddyb) is this even possible, if we have a `Node::Ctor`?
249 assert_ne!(variant_data.ctor_hir_id(), None);
251 let ctor_of = match self.find(self.get_parent_node(hir_id)) {
252 Some(Node::Item(..)) => def::CtorOf::Struct,
253 Some(Node::Variant(..)) => def::CtorOf::Variant,
256 DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data))
258 Node::AnonConst(_) => {
259 let inline = match self.find(self.get_parent_node(hir_id)) {
260 Some(Node::Expr(&Expr {
261 kind: ExprKind::ConstBlock(ref anon_const), ..
262 })) if anon_const.hir_id == hir_id => true,
265 if inline { DefKind::InlineConst } else { DefKind::AnonConst }
267 Node::Field(_) => DefKind::Field,
268 Node::Expr(expr) => match expr.kind {
269 ExprKind::Closure(Closure { movability: None, .. }) => DefKind::Closure,
270 ExprKind::Closure(Closure { movability: Some(_), .. }) => DefKind::Generator,
271 _ => bug!("def_kind: unsupported node: {}", self.node_to_string(hir_id)),
273 Node::GenericParam(param) => match param.kind {
274 GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam,
275 GenericParamKind::Type { .. } => DefKind::TyParam,
276 GenericParamKind::Const { .. } => DefKind::ConstParam,
278 Node::Crate(_) => DefKind::Mod,
280 | Node::PathSegment(_)
282 | Node::TypeBinding(_)
292 | Node::Block(_) => return None,
297 /// Finds the id of the parent node to this one.
299 /// If calling repeatedly and iterating over parents, prefer [`Map::parent_iter`].
300 pub fn find_parent_node(self, id: HirId) -> Option<HirId> {
301 if id.local_id == ItemLocalId::from_u32(0) {
302 Some(self.tcx.hir_owner_parent(id.owner))
304 let owner = self.tcx.hir_owner_nodes(id.owner).as_owner()?;
305 let node = owner.nodes[id.local_id].as_ref()?;
306 let hir_id = HirId { owner: id.owner, local_id: node.parent };
307 // HIR indexing should have checked that.
308 debug_assert_ne!(id.local_id, node.parent);
313 pub fn get_parent_node(self, hir_id: HirId) -> HirId {
314 self.find_parent_node(hir_id)
315 .unwrap_or_else(|| bug!("No parent for node {:?}", self.node_to_string(hir_id)))
318 /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
319 pub fn find(self, id: HirId) -> Option<Node<'hir>> {
320 if id.local_id == ItemLocalId::from_u32(0) {
321 let owner = self.tcx.hir_owner(id.owner)?;
322 Some(owner.node.into())
324 let owner = self.tcx.hir_owner_nodes(id.owner).as_owner()?;
325 let node = owner.nodes[id.local_id].as_ref()?;
330 /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
332 pub fn find_by_def_id(self, id: LocalDefId) -> Option<Node<'hir>> {
333 self.find(self.local_def_id_to_hir_id(id))
336 /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found.
337 pub fn get(self, id: HirId) -> Node<'hir> {
338 self.find(id).unwrap_or_else(|| bug!("couldn't find hir id {} in the HIR map", id))
341 /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found.
343 pub fn get_by_def_id(self, id: LocalDefId) -> Node<'hir> {
344 self.find_by_def_id(id).unwrap_or_else(|| bug!("couldn't find {:?} in the HIR map", id))
347 pub fn get_if_local(self, id: DefId) -> Option<Node<'hir>> {
348 id.as_local().and_then(|id| self.find(self.local_def_id_to_hir_id(id)))
351 pub fn get_generics(self, id: LocalDefId) -> Option<&'hir Generics<'hir>> {
352 let node = self.tcx.hir_owner(OwnerId { def_id: id })?;
356 pub fn owner(self, id: OwnerId) -> OwnerNode<'hir> {
357 self.tcx.hir_owner(id).unwrap_or_else(|| bug!("expected owner for {:?}", id)).node
360 pub fn item(self, id: ItemId) -> &'hir Item<'hir> {
361 self.tcx.hir_owner(id.owner_id).unwrap().node.expect_item()
364 pub fn trait_item(self, id: TraitItemId) -> &'hir TraitItem<'hir> {
365 self.tcx.hir_owner(id.owner_id).unwrap().node.expect_trait_item()
368 pub fn impl_item(self, id: ImplItemId) -> &'hir ImplItem<'hir> {
369 self.tcx.hir_owner(id.owner_id).unwrap().node.expect_impl_item()
372 pub fn foreign_item(self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
373 self.tcx.hir_owner(id.owner_id).unwrap().node.expect_foreign_item()
376 pub fn body(self, id: BodyId) -> &'hir Body<'hir> {
377 self.tcx.hir_owner_nodes(id.hir_id.owner).unwrap().bodies[&id.hir_id.local_id]
380 pub fn fn_decl_by_hir_id(self, hir_id: HirId) -> Option<&'hir FnDecl<'hir>> {
381 if let Some(node) = self.find(hir_id) {
384 bug!("no node for hir_id `{}`", hir_id)
388 pub fn fn_sig_by_hir_id(self, hir_id: HirId) -> Option<&'hir FnSig<'hir>> {
389 if let Some(node) = self.find(hir_id) {
392 bug!("no node for hir_id `{}`", hir_id)
396 pub fn enclosing_body_owner(self, hir_id: HirId) -> LocalDefId {
397 for (_, node) in self.parent_iter(hir_id) {
398 if let Some(body) = associated_body(node) {
399 return self.body_owner_def_id(body);
403 bug!("no `enclosing_body_owner` for hir_id `{}`", hir_id);
406 /// Returns the `HirId` that corresponds to the definition of
407 /// which this is the body of, i.e., a `fn`, `const` or `static`
408 /// item (possibly associated), a closure, or a `hir::AnonConst`.
409 pub fn body_owner(self, BodyId { hir_id }: BodyId) -> HirId {
410 let parent = self.get_parent_node(hir_id);
411 assert!(self.find(parent).map_or(false, |n| is_body_owner(n, hir_id)));
415 pub fn body_owner_def_id(self, id: BodyId) -> LocalDefId {
416 self.local_def_id(self.body_owner(id))
419 /// Given a `LocalDefId`, returns the `BodyId` associated with it,
420 /// if the node is a body owner, otherwise returns `None`.
421 pub fn maybe_body_owned_by(self, id: LocalDefId) -> Option<BodyId> {
422 self.get_if_local(id.to_def_id()).map(associated_body).flatten()
425 /// Given a body owner's id, returns the `BodyId` associated with it.
426 pub fn body_owned_by(self, id: LocalDefId) -> BodyId {
427 self.maybe_body_owned_by(id).unwrap_or_else(|| {
428 let hir_id = self.local_def_id_to_hir_id(id);
431 "body_owned_by: {} has no associated body",
432 self.node_to_string(hir_id)
437 pub fn body_param_names(self, id: BodyId) -> impl Iterator<Item = Ident> + 'hir {
438 self.body(id).params.iter().map(|arg| match arg.pat.kind {
439 PatKind::Binding(_, _, ident, _) => ident,
444 /// Returns the `BodyOwnerKind` of this `LocalDefId`.
446 /// Panics if `LocalDefId` does not have an associated body.
447 pub fn body_owner_kind(self, def_id: LocalDefId) -> BodyOwnerKind {
448 match self.tcx.def_kind(def_id) {
449 DefKind::Const | DefKind::AssocConst | DefKind::InlineConst | DefKind::AnonConst => {
452 DefKind::Ctor(..) | DefKind::Fn | DefKind::AssocFn => BodyOwnerKind::Fn,
453 DefKind::Closure | DefKind::Generator => BodyOwnerKind::Closure,
454 DefKind::Static(mt) => BodyOwnerKind::Static(mt),
455 dk => bug!("{:?} is not a body node: {:?}", def_id, dk),
459 /// Returns the `ConstContext` of the body associated with this `LocalDefId`.
461 /// Panics if `LocalDefId` does not have an associated body.
463 /// This should only be used for determining the context of a body, a return
464 /// value of `Some` does not always suggest that the owner of the body is `const`,
465 /// just that it has to be checked as if it were.
466 pub fn body_const_context(self, def_id: LocalDefId) -> Option<ConstContext> {
467 let ccx = match self.body_owner_kind(def_id) {
468 BodyOwnerKind::Const => ConstContext::Const,
469 BodyOwnerKind::Static(mt) => ConstContext::Static(mt),
471 BodyOwnerKind::Fn if self.tcx.is_constructor(def_id.to_def_id()) => return None,
472 BodyOwnerKind::Fn if self.tcx.is_const_fn_raw(def_id.to_def_id()) => {
473 ConstContext::ConstFn
475 BodyOwnerKind::Fn if self.tcx.is_const_default_method(def_id.to_def_id()) => {
476 ConstContext::ConstFn
478 BodyOwnerKind::Fn | BodyOwnerKind::Closure => return None,
484 /// Returns an iterator of the `DefId`s for all body-owners in this
485 /// crate. If you would prefer to iterate over the bodies
486 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
488 pub fn body_owners(self) -> impl Iterator<Item = LocalDefId> + 'hir {
489 self.tcx.hir_crate_items(()).body_owners.iter().copied()
493 pub fn par_body_owners(self, f: impl Fn(LocalDefId) + Sync + Send) {
494 par_for_each_in(&self.tcx.hir_crate_items(()).body_owners[..], |&def_id| f(def_id));
497 pub fn ty_param_owner(self, def_id: LocalDefId) -> LocalDefId {
498 let def_kind = self.tcx.def_kind(def_id);
500 DefKind::Trait | DefKind::TraitAlias => def_id,
501 DefKind::LifetimeParam | DefKind::TyParam | DefKind::ConstParam => {
502 self.tcx.local_parent(def_id)
504 _ => bug!("ty_param_owner: {:?} is a {:?} not a type parameter", def_id, def_kind),
508 pub fn ty_param_name(self, def_id: LocalDefId) -> Symbol {
509 let def_kind = self.tcx.def_kind(def_id);
511 DefKind::Trait | DefKind::TraitAlias => kw::SelfUpper,
512 DefKind::LifetimeParam | DefKind::TyParam | DefKind::ConstParam => {
513 self.tcx.item_name(def_id.to_def_id())
515 _ => bug!("ty_param_name: {:?} is a {:?} not a type parameter", def_id, def_kind),
519 pub fn trait_impls(self, trait_did: DefId) -> &'hir [LocalDefId] {
520 self.tcx.all_local_trait_impls(()).get(&trait_did).map_or(&[], |xs| &xs[..])
523 /// Gets the attributes on the crate. This is preferable to
524 /// invoking `krate.attrs` because it registers a tighter
525 /// dep-graph access.
526 pub fn krate_attrs(self) -> &'hir [ast::Attribute] {
527 self.attrs(CRATE_HIR_ID)
530 pub fn rustc_coherence_is_core(self) -> bool {
531 self.krate_attrs().iter().any(|attr| attr.has_name(sym::rustc_coherence_is_core))
534 pub fn get_module(self, module: LocalDefId) -> (&'hir Mod<'hir>, Span, HirId) {
535 let hir_id = HirId::make_owner(module);
536 match self.tcx.hir_owner(hir_id.owner).map(|o| o.node) {
537 Some(OwnerNode::Item(&Item { span, kind: ItemKind::Mod(ref m), .. })) => {
540 Some(OwnerNode::Crate(item)) => (item, item.spans.inner_span, hir_id),
541 node => panic!("not a module: {:?}", node),
545 /// Walks the contents of the local crate. See also `visit_all_item_likes_in_crate`.
546 pub fn walk_toplevel_module(self, visitor: &mut impl Visitor<'hir>) {
547 let (top_mod, span, hir_id) = self.get_module(CRATE_DEF_ID);
548 visitor.visit_mod(top_mod, span, hir_id);
551 /// Walks the attributes in a crate.
552 pub fn walk_attributes(self, visitor: &mut impl Visitor<'hir>) {
553 let krate = self.krate();
554 for info in krate.owners.iter() {
555 if let MaybeOwner::Owner(info) = info {
556 for attrs in info.attrs.map.values() {
558 visitor.visit_attribute(a)
565 /// Visits all item-likes in the crate in some deterministic (but unspecified) order. If you
566 /// need to process every item-like, and don't care about visiting nested items in a particular
567 /// order then this method is the best choice. If you do care about this nesting, you should
568 /// use the `tcx.hir().walk_toplevel_module`.
570 /// Note that this function will access HIR for all the item-likes in the crate. If you only
571 /// need to access some of them, it is usually better to manually loop on the iterators
572 /// provided by `tcx.hir_crate_items(())`.
574 /// Please see the notes in `intravisit.rs` for more information.
575 pub fn visit_all_item_likes_in_crate<V>(self, visitor: &mut V)
579 let krate = self.tcx.hir_crate_items(());
581 for id in krate.items() {
582 visitor.visit_item(self.item(id));
585 for id in krate.trait_items() {
586 visitor.visit_trait_item(self.trait_item(id));
589 for id in krate.impl_items() {
590 visitor.visit_impl_item(self.impl_item(id));
593 for id in krate.foreign_items() {
594 visitor.visit_foreign_item(self.foreign_item(id));
598 /// This method is the equivalent of `visit_all_item_likes_in_crate` but restricted to
599 /// item-likes in a single module.
600 pub fn visit_item_likes_in_module<V>(self, module: LocalDefId, visitor: &mut V)
604 let module = self.tcx.hir_module_items(module);
606 for id in module.items() {
607 visitor.visit_item(self.item(id));
610 for id in module.trait_items() {
611 visitor.visit_trait_item(self.trait_item(id));
614 for id in module.impl_items() {
615 visitor.visit_impl_item(self.impl_item(id));
618 for id in module.foreign_items() {
619 visitor.visit_foreign_item(self.foreign_item(id));
623 pub fn for_each_module(self, mut f: impl FnMut(LocalDefId)) {
624 let crate_items = self.tcx.hir_crate_items(());
625 for module in crate_items.submodules.iter() {
631 pub fn par_for_each_module(self, f: impl Fn(LocalDefId) + Sync + Send) {
632 let crate_items = self.tcx.hir_crate_items(());
633 par_for_each_in(&crate_items.submodules[..], |module| f(module.def_id))
636 /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
637 /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`.
639 pub fn parent_id_iter(self, current_id: HirId) -> impl Iterator<Item = HirId> + 'hir {
640 ParentHirIterator { current_id, map: self }
643 /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
644 /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`.
646 pub fn parent_iter(self, current_id: HirId) -> impl Iterator<Item = (HirId, Node<'hir>)> {
647 self.parent_id_iter(current_id).filter_map(move |id| Some((id, self.find(id)?)))
650 /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
651 /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`.
653 pub fn parent_owner_iter(self, current_id: HirId) -> ParentOwnerIterator<'hir> {
654 ParentOwnerIterator { current_id, map: self }
657 /// Checks if the node is left-hand side of an assignment.
658 pub fn is_lhs(self, id: HirId) -> bool {
659 match self.find(self.get_parent_node(id)) {
660 Some(Node::Expr(expr)) => match expr.kind {
661 ExprKind::Assign(lhs, _rhs, _span) => lhs.hir_id == id,
668 /// Whether the expression pointed at by `hir_id` belongs to a `const` evaluation context.
669 /// Used exclusively for diagnostics, to avoid suggestion function calls.
670 pub fn is_inside_const_context(self, hir_id: HirId) -> bool {
671 self.body_const_context(self.enclosing_body_owner(hir_id)).is_some()
674 /// Retrieves the `HirId` for `id`'s enclosing method, unless there's a
675 /// `while` or `loop` before reaching it, as block tail returns are not
676 /// available in them.
679 /// fn foo(x: usize) -> bool {
681 /// true // If `get_return_block` gets passed the `id` corresponding
682 /// } else { // to this, it will return `foo`'s `HirId`.
688 /// ```compile_fail,E0308
689 /// fn foo(x: usize) -> bool {
691 /// true // If `get_return_block` gets passed the `id` corresponding
692 /// } // to this, it will return `None`.
696 pub fn get_return_block(self, id: HirId) -> Option<HirId> {
697 let mut iter = self.parent_iter(id).peekable();
698 let mut ignore_tail = false;
699 if let Some(node) = self.find(id) {
700 if let Node::Expr(Expr { kind: ExprKind::Ret(_), .. }) = node {
701 // When dealing with `return` statements, we don't care about climbing only tail
706 while let Some((hir_id, node)) = iter.next() {
707 if let (Some((_, next_node)), false) = (iter.peek(), ignore_tail) {
709 Node::Block(Block { expr: None, .. }) => return None,
710 // The current node is not the tail expression of its parent.
711 Node::Block(Block { expr: Some(e), .. }) if hir_id != e.hir_id => return None,
717 | Node::ForeignItem(_)
719 | Node::Expr(Expr { kind: ExprKind::Closure { .. }, .. })
720 | Node::ImplItem(_) => return Some(hir_id),
721 // Ignore `return`s on the first iteration
722 Node::Expr(Expr { kind: ExprKind::Loop(..) | ExprKind::Ret(..), .. })
723 | Node::Local(_) => {
732 /// Retrieves the `OwnerId` for `id`'s parent item, or `id` itself if no
733 /// parent item is in this map. The "parent item" is the closest parent node
734 /// in the HIR which is recorded by the map and is an item, either an item
735 /// in a module, trait, or impl.
736 pub fn get_parent_item(self, hir_id: HirId) -> OwnerId {
737 if let Some((def_id, _node)) = self.parent_owner_iter(hir_id).next() {
744 /// Returns the `OwnerId` of `id`'s nearest module parent, or `id` itself if no
745 /// module parent is in this map.
746 pub(super) fn get_module_parent_node(self, hir_id: HirId) -> OwnerId {
747 for (def_id, node) in self.parent_owner_iter(hir_id) {
748 if let OwnerNode::Item(&Item { kind: ItemKind::Mod(_), .. }) = node {
755 /// When on an if expression, a match arm tail expression or a match arm, give back
756 /// the enclosing `if` or `match` expression.
758 /// Used by error reporting when there's a type error in an if or match arm caused by the
759 /// expression needing to be unit.
760 pub fn get_if_cause(self, hir_id: HirId) -> Option<&'hir Expr<'hir>> {
761 for (_, node) in self.parent_iter(hir_id) {
764 | Node::ForeignItem(_)
767 | Node::Stmt(Stmt { kind: StmtKind::Local(_), .. }) => break,
768 Node::Expr(expr @ Expr { kind: ExprKind::If(..) | ExprKind::Match(..), .. }) => {
777 /// Returns the nearest enclosing scope. A scope is roughly an item or block.
778 pub fn get_enclosing_scope(self, hir_id: HirId) -> Option<HirId> {
779 for (hir_id, node) in self.parent_iter(hir_id) {
780 if let Node::Item(Item {
783 | ItemKind::Const(..)
784 | ItemKind::Static(..)
787 | ItemKind::Struct(..)
788 | ItemKind::Union(..)
789 | ItemKind::Trait(..)
790 | ItemKind::Impl { .. },
793 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(..), .. })
794 | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(..), .. })
795 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(..), .. })
796 | Node::Block(_) = node
804 /// Returns the defining scope for an opaque type definition.
805 pub fn get_defining_scope(self, id: HirId) -> HirId {
808 scope = self.get_enclosing_scope(scope).unwrap_or(CRATE_HIR_ID);
809 if scope == CRATE_HIR_ID || !matches!(self.get(scope), Node::Block(_)) {
815 pub fn get_foreign_abi(self, hir_id: HirId) -> Abi {
816 let parent = self.get_parent_item(hir_id);
817 if let Some(node) = self.tcx.hir_owner(parent) {
818 if let OwnerNode::Item(Item { kind: ItemKind::ForeignMod { abi, .. }, .. }) = node.node
824 "expected foreign mod or inlined parent, found {}",
825 self.node_to_string(HirId::make_owner(parent.def_id))
829 pub fn expect_owner(self, def_id: LocalDefId) -> OwnerNode<'hir> {
831 .hir_owner(OwnerId { def_id })
832 .unwrap_or_else(|| bug!("expected owner for {:?}", def_id))
836 pub fn expect_item(self, id: LocalDefId) -> &'hir Item<'hir> {
837 match self.tcx.hir_owner(OwnerId { def_id: id }) {
838 Some(Owner { node: OwnerNode::Item(item), .. }) => item,
839 _ => bug!("expected item, found {}", self.node_to_string(HirId::make_owner(id))),
843 pub fn expect_impl_item(self, id: LocalDefId) -> &'hir ImplItem<'hir> {
844 match self.tcx.hir_owner(OwnerId { def_id: id }) {
845 Some(Owner { node: OwnerNode::ImplItem(item), .. }) => item,
846 _ => bug!("expected impl item, found {}", self.node_to_string(HirId::make_owner(id))),
850 pub fn expect_trait_item(self, id: LocalDefId) -> &'hir TraitItem<'hir> {
851 match self.tcx.hir_owner(OwnerId { def_id: id }) {
852 Some(Owner { node: OwnerNode::TraitItem(item), .. }) => item,
853 _ => bug!("expected trait item, found {}", self.node_to_string(HirId::make_owner(id))),
857 pub fn expect_variant(self, id: HirId) -> &'hir Variant<'hir> {
858 match self.find(id) {
859 Some(Node::Variant(variant)) => variant,
860 _ => bug!("expected variant, found {}", self.node_to_string(id)),
864 pub fn expect_foreign_item(self, id: OwnerId) -> &'hir ForeignItem<'hir> {
865 match self.tcx.hir_owner(id) {
866 Some(Owner { node: OwnerNode::ForeignItem(item), .. }) => item,
869 "expected foreign item, found {}",
870 self.node_to_string(HirId::make_owner(id.def_id))
876 pub fn expect_expr(self, id: HirId) -> &'hir Expr<'hir> {
877 match self.find(id) {
878 Some(Node::Expr(expr)) => expr,
879 _ => bug!("expected expr, found {}", self.node_to_string(id)),
884 fn opt_ident(self, id: HirId) -> Option<Ident> {
886 Node::Pat(&Pat { kind: PatKind::Binding(_, _, ident, _), .. }) => Some(ident),
887 // A `Ctor` doesn't have an identifier itself, but its parent
888 // struct/variant does. Compare with `hir::Map::opt_span`.
889 Node::Ctor(..) => match self.find(self.get_parent_node(id))? {
890 Node::Item(item) => Some(item.ident),
891 Node::Variant(variant) => Some(variant.ident),
894 node => node.ident(),
899 pub(super) fn opt_ident_span(self, id: HirId) -> Option<Span> {
900 self.opt_ident(id).map(|ident| ident.span)
904 pub fn opt_name(self, id: HirId) -> Option<Symbol> {
905 self.opt_ident(id).map(|ident| ident.name)
908 pub fn name(self, id: HirId) -> Symbol {
909 self.opt_name(id).unwrap_or_else(|| bug!("no name for {}", self.node_to_string(id)))
912 /// Given a node ID, gets a list of attributes associated with the AST
913 /// corresponding to the node-ID.
914 pub fn attrs(self, id: HirId) -> &'hir [ast::Attribute] {
915 self.tcx.hir_attrs(id.owner).get(id.local_id)
918 /// Gets the span of the definition of the specified HIR node.
919 /// This is used by `tcx.def_span`.
920 pub fn span(self, hir_id: HirId) -> Span {
921 self.opt_span(hir_id)
922 .unwrap_or_else(|| bug!("hir::map::Map::span: id not in map: {:?}", hir_id))
925 pub fn opt_span(self, hir_id: HirId) -> Option<Span> {
926 fn until_within(outer: Span, end: Span) -> Span {
927 if let Some(end) = end.find_ancestor_inside(outer) {
928 outer.with_hi(end.hi())
934 fn named_span(item_span: Span, ident: Ident, generics: Option<&Generics<'_>>) -> Span {
935 if ident.name != kw::Empty {
936 let mut span = until_within(item_span, ident.span);
937 if let Some(g) = generics
938 && !g.span.is_dummy()
939 && let Some(g_span) = g.span.find_ancestor_inside(item_span)
941 span = span.to(g_span);
949 let span = match self.find(hir_id)? {
951 Node::Item(Item { kind: ItemKind::Fn(sig, ..), span: outer_span, .. })
952 | Node::TraitItem(TraitItem {
953 kind: TraitItemKind::Fn(sig, ..),
957 | Node::ImplItem(ImplItem {
958 kind: ImplItemKind::Fn(sig, ..), span: outer_span, ..
960 // Ensure that the returned span has the item's SyntaxContext, and not the
961 // SyntaxContext of the visibility.
962 sig.span.find_ancestor_in_same_ctxt(*outer_span).unwrap_or(*outer_span)
964 // Constants and Statics.
967 ItemKind::Const(ty, ..)
968 | ItemKind::Static(ty, ..)
969 | ItemKind::Impl(Impl { self_ty: ty, .. }),
973 | Node::TraitItem(TraitItem {
974 kind: TraitItemKind::Const(ty, ..),
978 | Node::ImplItem(ImplItem {
979 kind: ImplItemKind::Const(ty, ..),
983 | Node::ForeignItem(ForeignItem {
984 kind: ForeignItemKind::Static(ty, ..),
987 }) => until_within(*outer_span, ty.span),
988 // With generics and bounds.
990 kind: ItemKind::Trait(_, _, generics, bounds, _),
994 | Node::TraitItem(TraitItem {
995 kind: TraitItemKind::Type(bounds, _),
1000 let end = if let Some(b) = bounds.last() { b.span() } else { generics.span };
1001 until_within(*outer_span, end)
1004 Node::Item(item) => match &item.kind {
1005 ItemKind::Use(path, _) => {
1006 // Ensure that the returned span has the item's SyntaxContext, and not the
1007 // SyntaxContext of the path.
1008 path.span.find_ancestor_in_same_ctxt(item.span).unwrap_or(item.span)
1010 _ => named_span(item.span, item.ident, item.kind.generics()),
1012 Node::Variant(variant) => named_span(variant.span, variant.ident, None),
1013 Node::ImplItem(item) => named_span(item.span, item.ident, Some(item.generics)),
1014 Node::ForeignItem(item) => match item.kind {
1015 ForeignItemKind::Fn(decl, _, _) => until_within(item.span, decl.output.span()),
1016 _ => named_span(item.span, item.ident, None),
1018 Node::Ctor(_) => return self.opt_span(self.get_parent_node(hir_id)),
1020 kind: ExprKind::Closure(Closure { fn_decl_span, .. }),
1024 // Ensure that the returned span has the item's SyntaxContext.
1025 fn_decl_span.find_ancestor_in_same_ctxt(*span).unwrap_or(*span)
1027 _ => self.span_with_body(hir_id),
1029 debug_assert_eq!(span.ctxt(), self.span_with_body(hir_id).ctxt());
1033 /// Like `hir.span()`, but includes the body of items
1034 /// (instead of just the item header)
1035 pub fn span_with_body(self, hir_id: HirId) -> Span {
1036 match self.get(hir_id) {
1037 Node::Param(param) => param.span,
1038 Node::Item(item) => item.span,
1039 Node::ForeignItem(foreign_item) => foreign_item.span,
1040 Node::TraitItem(trait_item) => trait_item.span,
1041 Node::ImplItem(impl_item) => impl_item.span,
1042 Node::Variant(variant) => variant.span,
1043 Node::Field(field) => field.span,
1044 Node::AnonConst(constant) => self.body(constant.body).value.span,
1045 Node::Expr(expr) => expr.span,
1046 Node::ExprField(field) => field.span,
1047 Node::Stmt(stmt) => stmt.span,
1048 Node::PathSegment(seg) => {
1049 let ident_span = seg.ident.span;
1051 .with_hi(seg.args.map_or_else(|| ident_span.hi(), |args| args.span_ext.hi()))
1053 Node::Ty(ty) => ty.span,
1054 Node::TypeBinding(tb) => tb.span,
1055 Node::TraitRef(tr) => tr.path.span,
1056 Node::Pat(pat) => pat.span,
1057 Node::PatField(field) => field.span,
1058 Node::Arm(arm) => arm.span,
1059 Node::Block(block) => block.span,
1060 Node::Ctor(..) => self.span_with_body(self.get_parent_node(hir_id)),
1061 Node::Lifetime(lifetime) => lifetime.span,
1062 Node::GenericParam(param) => param.span,
1063 Node::Infer(i) => i.span,
1064 Node::Local(local) => local.span,
1065 Node::Crate(item) => item.spans.inner_span,
1069 pub fn span_if_local(self, id: DefId) -> Option<Span> {
1070 if id.is_local() { Some(self.tcx.def_span(id)) } else { None }
1073 pub fn res_span(self, res: Res) -> Option<Span> {
1076 Res::Local(id) => Some(self.span(id)),
1077 res => self.span_if_local(res.opt_def_id()?),
1081 /// Get a representation of this `id` for debugging purposes.
1082 /// NOTE: Do NOT use this in diagnostics!
1083 pub fn node_to_string(self, id: HirId) -> String {
1084 hir_id_to_string(self, id)
1087 /// Returns the HirId of `N` in `struct Foo<const N: usize = { ... }>` when
1088 /// called with the HirId for the `{ ... }` anon const
1089 pub fn opt_const_param_default_param_hir_id(self, anon_const: HirId) -> Option<HirId> {
1090 match self.get(self.get_parent_node(anon_const)) {
1091 Node::GenericParam(GenericParam {
1093 kind: GenericParamKind::Const { .. },
1095 }) => Some(*param_id),
1101 impl<'hir> intravisit::Map<'hir> for Map<'hir> {
1102 fn find(&self, hir_id: HirId) -> Option<Node<'hir>> {
1103 (*self).find(hir_id)
1106 fn body(&self, id: BodyId) -> &'hir Body<'hir> {
1110 fn item(&self, id: ItemId) -> &'hir Item<'hir> {
1114 fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
1115 (*self).trait_item(id)
1118 fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
1119 (*self).impl_item(id)
1122 fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
1123 (*self).foreign_item(id)
1127 pub(super) fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
1128 debug_assert_eq!(crate_num, LOCAL_CRATE);
1129 let krate = tcx.hir_crate(());
1130 let hir_body_hash = krate.hir_hash;
1132 let upstream_crates = upstream_crates(tcx);
1134 let resolutions = tcx.resolutions(());
1136 // We hash the final, remapped names of all local source files so we
1137 // don't have to include the path prefix remapping commandline args.
1138 // If we included the full mapping in the SVH, we could only have
1139 // reproducible builds by compiling from the same directory. So we just
1140 // hash the result of the mapping instead of the mapping itself.
1141 let mut source_file_names: Vec<_> = tcx
1146 .filter(|source_file| source_file.cnum == LOCAL_CRATE)
1147 .map(|source_file| source_file.name_hash)
1150 source_file_names.sort_unstable();
1152 let crate_hash: Fingerprint = tcx.with_stable_hashing_context(|mut hcx| {
1153 let mut stable_hasher = StableHasher::new();
1154 hir_body_hash.hash_stable(&mut hcx, &mut stable_hasher);
1155 upstream_crates.hash_stable(&mut hcx, &mut stable_hasher);
1156 source_file_names.hash_stable(&mut hcx, &mut stable_hasher);
1157 if tcx.sess.opts.unstable_opts.incremental_relative_spans {
1158 let definitions = tcx.definitions_untracked();
1159 let mut owner_spans: Vec<_> = krate
1162 .filter_map(|(def_id, info)| {
1163 let _ = info.as_owner()?;
1164 let def_path_hash = definitions.def_path_hash(def_id);
1165 let span = resolutions.source_span.get(def_id).unwrap_or(&DUMMY_SP);
1166 debug_assert_eq!(span.parent(), None);
1167 Some((def_path_hash, span))
1170 owner_spans.sort_unstable_by_key(|bn| bn.0);
1171 owner_spans.hash_stable(&mut hcx, &mut stable_hasher);
1173 tcx.sess.opts.dep_tracking_hash(true).hash_stable(&mut hcx, &mut stable_hasher);
1174 tcx.sess.local_stable_crate_id().hash_stable(&mut hcx, &mut stable_hasher);
1175 // Hash visibility information since it does not appear in HIR.
1176 resolutions.visibilities.hash_stable(&mut hcx, &mut stable_hasher);
1177 resolutions.has_pub_restricted.hash_stable(&mut hcx, &mut stable_hasher);
1178 stable_hasher.finish()
1181 Svh::new(crate_hash.to_smaller_hash())
1184 fn upstream_crates(tcx: TyCtxt<'_>) -> Vec<(StableCrateId, Svh)> {
1185 let mut upstream_crates: Vec<_> = tcx
1189 let stable_crate_id = tcx.stable_crate_id(cnum);
1190 let hash = tcx.crate_hash(cnum);
1191 (stable_crate_id, hash)
1194 upstream_crates.sort_unstable_by_key(|&(stable_crate_id, _)| stable_crate_id);
1198 fn hir_id_to_string(map: Map<'_>, id: HirId) -> String {
1199 let id_str = format!(" (hir_id={})", id);
1202 // This functionality is used for debugging, try to use `TyCtxt` to get
1203 // the user-friendly path, otherwise fall back to stringifying `DefPath`.
1204 crate::ty::tls::with_opt(|tcx| {
1205 if let Some(tcx) = tcx {
1206 let def_id = map.local_def_id(id);
1207 tcx.def_path_str(def_id.to_def_id())
1208 } else if let Some(path) = map.def_path_from_hir_id(id) {
1209 path.data.into_iter().map(|elem| elem.to_string()).collect::<Vec<_>>().join("::")
1211 String::from("<missing path>")
1216 let span_str = || map.tcx.sess.source_map().span_to_snippet(map.span(id)).unwrap_or_default();
1217 let node_str = |prefix| format!("{} {}{}", prefix, span_str(), id_str);
1219 match map.find(id) {
1220 Some(Node::Item(item)) => {
1221 let item_str = match item.kind {
1222 ItemKind::ExternCrate(..) => "extern crate",
1223 ItemKind::Use(..) => "use",
1224 ItemKind::Static(..) => "static",
1225 ItemKind::Const(..) => "const",
1226 ItemKind::Fn(..) => "fn",
1227 ItemKind::Macro(..) => "macro",
1228 ItemKind::Mod(..) => "mod",
1229 ItemKind::ForeignMod { .. } => "foreign mod",
1230 ItemKind::GlobalAsm(..) => "global asm",
1231 ItemKind::TyAlias(..) => "ty",
1232 ItemKind::OpaqueTy(ref opaque) => {
1233 if opaque.in_trait {
1234 "opaque type in trait"
1239 ItemKind::Enum(..) => "enum",
1240 ItemKind::Struct(..) => "struct",
1241 ItemKind::Union(..) => "union",
1242 ItemKind::Trait(..) => "trait",
1243 ItemKind::TraitAlias(..) => "trait alias",
1244 ItemKind::Impl { .. } => "impl",
1246 format!("{} {}{}", item_str, path_str(), id_str)
1248 Some(Node::ForeignItem(_)) => format!("foreign item {}{}", path_str(), id_str),
1249 Some(Node::ImplItem(ii)) => match ii.kind {
1250 ImplItemKind::Const(..) => {
1251 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1253 ImplItemKind::Fn(..) => format!("method {} in {}{}", ii.ident, path_str(), id_str),
1254 ImplItemKind::Type(_) => {
1255 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1258 Some(Node::TraitItem(ti)) => {
1259 let kind = match ti.kind {
1260 TraitItemKind::Const(..) => "assoc constant",
1261 TraitItemKind::Fn(..) => "trait method",
1262 TraitItemKind::Type(..) => "assoc type",
1265 format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1267 Some(Node::Variant(ref variant)) => {
1268 format!("variant {} in {}{}", variant.ident, path_str(), id_str)
1270 Some(Node::Field(ref field)) => {
1271 format!("field {} in {}{}", field.ident, path_str(), id_str)
1273 Some(Node::AnonConst(_)) => node_str("const"),
1274 Some(Node::Expr(_)) => node_str("expr"),
1275 Some(Node::ExprField(_)) => node_str("expr field"),
1276 Some(Node::Stmt(_)) => node_str("stmt"),
1277 Some(Node::PathSegment(_)) => node_str("path segment"),
1278 Some(Node::Ty(_)) => node_str("type"),
1279 Some(Node::TypeBinding(_)) => node_str("type binding"),
1280 Some(Node::TraitRef(_)) => node_str("trait ref"),
1281 Some(Node::Pat(_)) => node_str("pat"),
1282 Some(Node::PatField(_)) => node_str("pattern field"),
1283 Some(Node::Param(_)) => node_str("param"),
1284 Some(Node::Arm(_)) => node_str("arm"),
1285 Some(Node::Block(_)) => node_str("block"),
1286 Some(Node::Infer(_)) => node_str("infer"),
1287 Some(Node::Local(_)) => node_str("local"),
1288 Some(Node::Ctor(..)) => format!("ctor {}{}", path_str(), id_str),
1289 Some(Node::Lifetime(_)) => node_str("lifetime"),
1290 Some(Node::GenericParam(ref param)) => format!("generic_param {:?}{}", param, id_str),
1291 Some(Node::Crate(..)) => String::from("root_crate"),
1292 None => format!("unknown node{}", id_str),
1296 pub(super) fn hir_module_items(tcx: TyCtxt<'_>, module_id: LocalDefId) -> ModuleItems {
1297 let mut collector = ItemCollector::new(tcx, false);
1299 let (hir_mod, span, hir_id) = tcx.hir().get_module(module_id);
1300 collector.visit_mod(hir_mod, span, hir_id);
1311 return ModuleItems {
1312 submodules: submodules.into_boxed_slice(),
1313 items: items.into_boxed_slice(),
1314 trait_items: trait_items.into_boxed_slice(),
1315 impl_items: impl_items.into_boxed_slice(),
1316 foreign_items: foreign_items.into_boxed_slice(),
1317 body_owners: body_owners.into_boxed_slice(),
1321 pub(crate) fn hir_crate_items(tcx: TyCtxt<'_>, _: ()) -> ModuleItems {
1322 let mut collector = ItemCollector::new(tcx, true);
1324 // A "crate collector" and "module collector" start at a
1325 // module item (the former starts at the crate root) but only
1326 // the former needs to collect it. ItemCollector does not do this for us.
1327 collector.submodules.push(CRATE_OWNER_ID);
1328 tcx.hir().walk_toplevel_module(&mut collector);
1340 return ModuleItems {
1341 submodules: submodules.into_boxed_slice(),
1342 items: items.into_boxed_slice(),
1343 trait_items: trait_items.into_boxed_slice(),
1344 impl_items: impl_items.into_boxed_slice(),
1345 foreign_items: foreign_items.into_boxed_slice(),
1346 body_owners: body_owners.into_boxed_slice(),
1350 struct ItemCollector<'tcx> {
1351 // When true, it collects all items in the create,
1352 // otherwise it collects items in some module.
1353 crate_collector: bool,
1355 submodules: Vec<OwnerId>,
1357 trait_items: Vec<TraitItemId>,
1358 impl_items: Vec<ImplItemId>,
1359 foreign_items: Vec<ForeignItemId>,
1360 body_owners: Vec<LocalDefId>,
1363 impl<'tcx> ItemCollector<'tcx> {
1364 fn new(tcx: TyCtxt<'tcx>, crate_collector: bool) -> ItemCollector<'tcx> {
1368 submodules: Vec::default(),
1369 items: Vec::default(),
1370 trait_items: Vec::default(),
1371 impl_items: Vec::default(),
1372 foreign_items: Vec::default(),
1373 body_owners: Vec::default(),
1378 impl<'hir> Visitor<'hir> for ItemCollector<'hir> {
1379 type NestedFilter = nested_filter::All;
1381 fn nested_visit_map(&mut self) -> Self::Map {
1385 fn visit_item(&mut self, item: &'hir Item<'hir>) {
1386 if associated_body(Node::Item(item)).is_some() {
1387 self.body_owners.push(item.owner_id.def_id);
1390 self.items.push(item.item_id());
1392 // Items that are modules are handled here instead of in visit_mod.
1393 if let ItemKind::Mod(module) = &item.kind {
1394 self.submodules.push(item.owner_id);
1395 // A module collector does not recurse inside nested modules.
1396 if self.crate_collector {
1397 intravisit::walk_mod(self, module, item.hir_id());
1400 intravisit::walk_item(self, item)
1404 fn visit_foreign_item(&mut self, item: &'hir ForeignItem<'hir>) {
1405 self.foreign_items.push(item.foreign_item_id());
1406 intravisit::walk_foreign_item(self, item)
1409 fn visit_anon_const(&mut self, c: &'hir AnonConst) {
1410 self.body_owners.push(self.tcx.hir().local_def_id(c.hir_id));
1411 intravisit::walk_anon_const(self, c)
1414 fn visit_expr(&mut self, ex: &'hir Expr<'hir>) {
1415 if matches!(ex.kind, ExprKind::Closure { .. }) {
1416 self.body_owners.push(self.tcx.hir().local_def_id(ex.hir_id));
1418 intravisit::walk_expr(self, ex)
1421 fn visit_trait_item(&mut self, item: &'hir TraitItem<'hir>) {
1422 if associated_body(Node::TraitItem(item)).is_some() {
1423 self.body_owners.push(item.owner_id.def_id);
1426 self.trait_items.push(item.trait_item_id());
1427 intravisit::walk_trait_item(self, item)
1430 fn visit_impl_item(&mut self, item: &'hir ImplItem<'hir>) {
1431 if associated_body(Node::ImplItem(item)).is_some() {
1432 self.body_owners.push(item.owner_id.def_id);
1435 self.impl_items.push(item.impl_item_id());
1436 intravisit::walk_impl_item(self, item)