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};
18 use rustc_target::spec::abi::Abi;
21 pub fn associated_body(node: Node<'_>) -> 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(node: Node<'_>, 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.parent_id(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)
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 if hir_id.local_id == ItemLocalId::new(0) {
187 Some(hir_id.owner.def_id)
190 .hir_owner_nodes(hir_id.owner)
193 .get(&hir_id.local_id)
199 pub fn local_def_id_to_hir_id(self, def_id: LocalDefId) -> HirId {
200 self.tcx.local_def_id_to_hir_id(def_id)
203 /// Do not call this function directly. The query should be called.
204 pub(super) fn opt_def_kind(self, local_def_id: LocalDefId) -> Option<DefKind> {
205 let hir_id = self.local_def_id_to_hir_id(local_def_id);
206 let def_kind = match self.find(hir_id)? {
207 Node::Item(item) => match item.kind {
208 ItemKind::Static(_, mt, _) => DefKind::Static(mt),
209 ItemKind::Const(..) => DefKind::Const,
210 ItemKind::Fn(..) => DefKind::Fn,
211 ItemKind::Macro(_, macro_kind) => DefKind::Macro(macro_kind),
212 ItemKind::Mod(..) => DefKind::Mod,
213 ItemKind::OpaqueTy(ref opaque) => {
215 DefKind::ImplTraitPlaceholder
220 ItemKind::TyAlias(..) => DefKind::TyAlias,
221 ItemKind::Enum(..) => DefKind::Enum,
222 ItemKind::Struct(..) => DefKind::Struct,
223 ItemKind::Union(..) => DefKind::Union,
224 ItemKind::Trait(..) => DefKind::Trait,
225 ItemKind::TraitAlias(..) => DefKind::TraitAlias,
226 ItemKind::ExternCrate(_) => DefKind::ExternCrate,
227 ItemKind::Use(..) => DefKind::Use,
228 ItemKind::ForeignMod { .. } => DefKind::ForeignMod,
229 ItemKind::GlobalAsm(..) => DefKind::GlobalAsm,
230 ItemKind::Impl { .. } => DefKind::Impl,
232 Node::ForeignItem(item) => match item.kind {
233 ForeignItemKind::Fn(..) => DefKind::Fn,
234 ForeignItemKind::Static(_, mt) => DefKind::Static(mt),
235 ForeignItemKind::Type => DefKind::ForeignTy,
237 Node::TraitItem(item) => match item.kind {
238 TraitItemKind::Const(..) => DefKind::AssocConst,
239 TraitItemKind::Fn(..) => DefKind::AssocFn,
240 TraitItemKind::Type(..) => DefKind::AssocTy,
242 Node::ImplItem(item) => match item.kind {
243 ImplItemKind::Const(..) => DefKind::AssocConst,
244 ImplItemKind::Fn(..) => DefKind::AssocFn,
245 ImplItemKind::Type(..) => DefKind::AssocTy,
247 Node::Variant(_) => DefKind::Variant,
248 Node::Ctor(variant_data) => {
249 let ctor_of = match self.find_parent(hir_id) {
250 Some(Node::Item(..)) => def::CtorOf::Struct,
251 Some(Node::Variant(..)) => def::CtorOf::Variant,
254 match variant_data.ctor_kind() {
255 Some(kind) => DefKind::Ctor(ctor_of, kind),
256 None => bug!("constructor node without a constructor"),
259 Node::AnonConst(_) => {
260 let inline = match self.find_parent(hir_id) {
261 Some(Node::Expr(&Expr {
262 kind: ExprKind::ConstBlock(ref anon_const), ..
263 })) if anon_const.hir_id == hir_id => true,
266 if inline { DefKind::InlineConst } else { DefKind::AnonConst }
268 Node::Field(_) => DefKind::Field,
269 Node::Expr(expr) => match expr.kind {
270 ExprKind::Closure(Closure { movability: None, .. }) => DefKind::Closure,
271 ExprKind::Closure(Closure { movability: Some(_), .. }) => DefKind::Generator,
272 _ => bug!("def_kind: unsupported node: {}", self.node_to_string(hir_id)),
274 Node::GenericParam(param) => match param.kind {
275 GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam,
276 GenericParamKind::Type { .. } => DefKind::TyParam,
277 GenericParamKind::Const { .. } => DefKind::ConstParam,
279 Node::Crate(_) => DefKind::Mod,
281 | Node::PathSegment(_)
283 | Node::TypeBinding(_)
293 | Node::Block(_) => return None,
298 /// Finds the id of the parent node to this one.
300 /// If calling repeatedly and iterating over parents, prefer [`Map::parent_iter`].
301 pub fn opt_parent_id(self, id: HirId) -> Option<HirId> {
302 if id.local_id == ItemLocalId::from_u32(0) {
303 Some(self.tcx.hir_owner_parent(id.owner))
305 let owner = self.tcx.hir_owner_nodes(id.owner).as_owner()?;
306 let node = owner.nodes[id.local_id].as_ref()?;
307 let hir_id = HirId { owner: id.owner, local_id: node.parent };
308 // HIR indexing should have checked that.
309 debug_assert_ne!(id.local_id, node.parent);
315 pub fn parent_id(self, hir_id: HirId) -> HirId {
316 self.opt_parent_id(hir_id)
317 .unwrap_or_else(|| bug!("No parent for node {:?}", self.node_to_string(hir_id)))
320 pub fn get_parent(self, hir_id: HirId) -> Node<'hir> {
321 self.get(self.parent_id(hir_id))
324 pub fn find_parent(self, hir_id: HirId) -> Option<Node<'hir>> {
325 self.find(self.opt_parent_id(hir_id)?)
328 /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
329 pub fn find(self, id: HirId) -> Option<Node<'hir>> {
330 if id.local_id == ItemLocalId::from_u32(0) {
331 let owner = self.tcx.hir_owner(id.owner)?;
332 Some(owner.node.into())
334 let owner = self.tcx.hir_owner_nodes(id.owner).as_owner()?;
335 let node = owner.nodes[id.local_id].as_ref()?;
340 /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
342 pub fn find_by_def_id(self, id: LocalDefId) -> Option<Node<'hir>> {
343 self.find(self.local_def_id_to_hir_id(id))
346 /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found.
348 pub fn get(self, id: HirId) -> Node<'hir> {
349 self.find(id).unwrap_or_else(|| bug!("couldn't find hir id {} in the HIR map", id))
352 /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found.
355 pub fn get_by_def_id(self, id: LocalDefId) -> Node<'hir> {
356 self.find_by_def_id(id).unwrap_or_else(|| bug!("couldn't find {:?} in the HIR map", id))
359 pub fn get_if_local(self, id: DefId) -> Option<Node<'hir>> {
360 id.as_local().and_then(|id| self.find(self.local_def_id_to_hir_id(id)))
363 pub fn get_generics(self, id: LocalDefId) -> Option<&'hir Generics<'hir>> {
364 let node = self.tcx.hir_owner(OwnerId { def_id: id })?;
368 pub fn owner(self, id: OwnerId) -> OwnerNode<'hir> {
369 self.tcx.hir_owner(id).unwrap_or_else(|| bug!("expected owner for {:?}", id)).node
372 pub fn item(self, id: ItemId) -> &'hir Item<'hir> {
373 self.tcx.hir_owner(id.owner_id).unwrap().node.expect_item()
376 pub fn trait_item(self, id: TraitItemId) -> &'hir TraitItem<'hir> {
377 self.tcx.hir_owner(id.owner_id).unwrap().node.expect_trait_item()
380 pub fn impl_item(self, id: ImplItemId) -> &'hir ImplItem<'hir> {
381 self.tcx.hir_owner(id.owner_id).unwrap().node.expect_impl_item()
384 pub fn foreign_item(self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
385 self.tcx.hir_owner(id.owner_id).unwrap().node.expect_foreign_item()
388 pub fn body(self, id: BodyId) -> &'hir Body<'hir> {
389 self.tcx.hir_owner_nodes(id.hir_id.owner).unwrap().bodies[&id.hir_id.local_id]
393 pub fn fn_decl_by_hir_id(self, hir_id: HirId) -> Option<&'hir FnDecl<'hir>> {
394 if let Some(node) = self.find(hir_id) {
397 bug!("no node for hir_id `{}`", hir_id)
402 pub fn fn_sig_by_hir_id(self, hir_id: HirId) -> Option<&'hir FnSig<'hir>> {
403 if let Some(node) = self.find(hir_id) {
406 bug!("no node for hir_id `{}`", hir_id)
411 pub fn enclosing_body_owner(self, hir_id: HirId) -> LocalDefId {
412 for (_, node) in self.parent_iter(hir_id) {
413 if let Some(body) = associated_body(node) {
414 return self.body_owner_def_id(body);
418 bug!("no `enclosing_body_owner` for hir_id `{}`", hir_id);
421 /// Returns the `HirId` that corresponds to the definition of
422 /// which this is the body of, i.e., a `fn`, `const` or `static`
423 /// item (possibly associated), a closure, or a `hir::AnonConst`.
424 pub fn body_owner(self, BodyId { hir_id }: BodyId) -> HirId {
425 let parent = self.parent_id(hir_id);
426 assert!(self.find(parent).map_or(false, |n| is_body_owner(n, hir_id)), "{hir_id:?}");
430 pub fn body_owner_def_id(self, id: BodyId) -> LocalDefId {
431 self.local_def_id(self.body_owner(id))
434 /// Given a `LocalDefId`, returns the `BodyId` associated with it,
435 /// if the node is a body owner, otherwise returns `None`.
436 pub fn maybe_body_owned_by(self, id: LocalDefId) -> Option<BodyId> {
437 self.find_by_def_id(id).and_then(associated_body)
440 /// Given a body owner's id, returns the `BodyId` associated with it.
442 pub fn body_owned_by(self, id: LocalDefId) -> BodyId {
443 self.maybe_body_owned_by(id).unwrap_or_else(|| {
444 let hir_id = self.local_def_id_to_hir_id(id);
447 "body_owned_by: {} has no associated body",
448 self.node_to_string(hir_id)
453 pub fn body_param_names(self, id: BodyId) -> impl Iterator<Item = Ident> + 'hir {
454 self.body(id).params.iter().map(|arg| match arg.pat.kind {
455 PatKind::Binding(_, _, ident, _) => ident,
460 /// Returns the `BodyOwnerKind` of this `LocalDefId`.
462 /// Panics if `LocalDefId` does not have an associated body.
463 pub fn body_owner_kind(self, def_id: LocalDefId) -> BodyOwnerKind {
464 match self.tcx.def_kind(def_id) {
465 DefKind::Const | DefKind::AssocConst | DefKind::InlineConst | DefKind::AnonConst => {
468 DefKind::Ctor(..) | DefKind::Fn | DefKind::AssocFn => BodyOwnerKind::Fn,
469 DefKind::Closure | DefKind::Generator => BodyOwnerKind::Closure,
470 DefKind::Static(mt) => BodyOwnerKind::Static(mt),
471 dk => bug!("{:?} is not a body node: {:?}", def_id, dk),
475 /// Returns the `ConstContext` of the body associated with this `LocalDefId`.
477 /// Panics if `LocalDefId` does not have an associated body.
479 /// This should only be used for determining the context of a body, a return
480 /// value of `Some` does not always suggest that the owner of the body is `const`,
481 /// just that it has to be checked as if it were.
482 pub fn body_const_context(self, def_id: LocalDefId) -> Option<ConstContext> {
483 let ccx = match self.body_owner_kind(def_id) {
484 BodyOwnerKind::Const => ConstContext::Const,
485 BodyOwnerKind::Static(mt) => ConstContext::Static(mt),
487 BodyOwnerKind::Fn if self.tcx.is_constructor(def_id.to_def_id()) => return None,
488 BodyOwnerKind::Fn | BodyOwnerKind::Closure if self.tcx.is_const_fn_raw(def_id.to_def_id()) => {
489 ConstContext::ConstFn
491 BodyOwnerKind::Fn if self.tcx.is_const_default_method(def_id.to_def_id()) => {
492 ConstContext::ConstFn
494 BodyOwnerKind::Fn | BodyOwnerKind::Closure => return None,
500 /// Returns an iterator of the `DefId`s for all body-owners in this
501 /// crate. If you would prefer to iterate over the bodies
502 /// themselves, you can do `self.hir().krate().body_ids.iter()`.
504 pub fn body_owners(self) -> impl Iterator<Item = LocalDefId> + 'hir {
505 self.tcx.hir_crate_items(()).body_owners.iter().copied()
509 pub fn par_body_owners(self, f: impl Fn(LocalDefId) + Sync + Send) {
510 par_for_each_in(&self.tcx.hir_crate_items(()).body_owners[..], |&def_id| f(def_id));
513 pub fn ty_param_owner(self, def_id: LocalDefId) -> LocalDefId {
514 let def_kind = self.tcx.def_kind(def_id);
516 DefKind::Trait | DefKind::TraitAlias => def_id,
517 DefKind::LifetimeParam | DefKind::TyParam | DefKind::ConstParam => {
518 self.tcx.local_parent(def_id)
520 _ => bug!("ty_param_owner: {:?} is a {:?} not a type parameter", def_id, def_kind),
524 pub fn ty_param_name(self, def_id: LocalDefId) -> Symbol {
525 let def_kind = self.tcx.def_kind(def_id);
527 DefKind::Trait | DefKind::TraitAlias => kw::SelfUpper,
528 DefKind::LifetimeParam | DefKind::TyParam | DefKind::ConstParam => {
529 self.tcx.item_name(def_id.to_def_id())
531 _ => bug!("ty_param_name: {:?} is a {:?} not a type parameter", def_id, def_kind),
535 pub fn trait_impls(self, trait_did: DefId) -> &'hir [LocalDefId] {
536 self.tcx.all_local_trait_impls(()).get(&trait_did).map_or(&[], |xs| &xs[..])
539 /// Gets the attributes on the crate. This is preferable to
540 /// invoking `krate.attrs` because it registers a tighter
541 /// dep-graph access.
542 pub fn krate_attrs(self) -> &'hir [ast::Attribute] {
543 self.attrs(CRATE_HIR_ID)
546 pub fn rustc_coherence_is_core(self) -> bool {
547 self.krate_attrs().iter().any(|attr| attr.has_name(sym::rustc_coherence_is_core))
550 pub fn get_module(self, module: LocalDefId) -> (&'hir Mod<'hir>, Span, HirId) {
551 let hir_id = HirId::make_owner(module);
552 match self.tcx.hir_owner(hir_id.owner).map(|o| o.node) {
553 Some(OwnerNode::Item(&Item { span, kind: ItemKind::Mod(ref m), .. })) => {
556 Some(OwnerNode::Crate(item)) => (item, item.spans.inner_span, hir_id),
557 node => panic!("not a module: {:?}", node),
561 /// Walks the contents of the local crate. See also `visit_all_item_likes_in_crate`.
562 pub fn walk_toplevel_module(self, visitor: &mut impl Visitor<'hir>) {
563 let (top_mod, span, hir_id) = self.get_module(CRATE_DEF_ID);
564 visitor.visit_mod(top_mod, span, hir_id);
567 /// Walks the attributes in a crate.
568 pub fn walk_attributes(self, visitor: &mut impl Visitor<'hir>) {
569 let krate = self.krate();
570 for info in krate.owners.iter() {
571 if let MaybeOwner::Owner(info) = info {
572 for attrs in info.attrs.map.values() {
574 visitor.visit_attribute(a)
581 /// Visits all item-likes in the crate in some deterministic (but unspecified) order. If you
582 /// need to process every item-like, and don't care about visiting nested items in a particular
583 /// order then this method is the best choice. If you do care about this nesting, you should
584 /// use the `tcx.hir().walk_toplevel_module`.
586 /// Note that this function will access HIR for all the item-likes in the crate. If you only
587 /// need to access some of them, it is usually better to manually loop on the iterators
588 /// provided by `tcx.hir_crate_items(())`.
590 /// Please see the notes in `intravisit.rs` for more information.
591 pub fn visit_all_item_likes_in_crate<V>(self, visitor: &mut V)
595 let krate = self.tcx.hir_crate_items(());
597 for id in krate.items() {
598 visitor.visit_item(self.item(id));
601 for id in krate.trait_items() {
602 visitor.visit_trait_item(self.trait_item(id));
605 for id in krate.impl_items() {
606 visitor.visit_impl_item(self.impl_item(id));
609 for id in krate.foreign_items() {
610 visitor.visit_foreign_item(self.foreign_item(id));
614 /// This method is the equivalent of `visit_all_item_likes_in_crate` but restricted to
615 /// item-likes in a single module.
616 pub fn visit_item_likes_in_module<V>(self, module: LocalDefId, visitor: &mut V)
620 let module = self.tcx.hir_module_items(module);
622 for id in module.items() {
623 visitor.visit_item(self.item(id));
626 for id in module.trait_items() {
627 visitor.visit_trait_item(self.trait_item(id));
630 for id in module.impl_items() {
631 visitor.visit_impl_item(self.impl_item(id));
634 for id in module.foreign_items() {
635 visitor.visit_foreign_item(self.foreign_item(id));
639 pub fn for_each_module(self, mut f: impl FnMut(LocalDefId)) {
640 let crate_items = self.tcx.hir_crate_items(());
641 for module in crate_items.submodules.iter() {
647 pub fn par_for_each_module(self, f: impl Fn(LocalDefId) + Sync + Send) {
648 let crate_items = self.tcx.hir_crate_items(());
649 par_for_each_in(&crate_items.submodules[..], |module| f(module.def_id))
652 /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
653 /// until the crate root is reached. Prefer this over your own loop using `parent_id`.
655 pub fn parent_id_iter(self, current_id: HirId) -> impl Iterator<Item = HirId> + 'hir {
656 ParentHirIterator { current_id, map: self }
659 /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
660 /// until the crate root is reached. Prefer this over your own loop using `parent_id`.
662 pub fn parent_iter(self, current_id: HirId) -> impl Iterator<Item = (HirId, Node<'hir>)> {
663 self.parent_id_iter(current_id).filter_map(move |id| Some((id, self.find(id)?)))
666 /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
667 /// until the crate root is reached. Prefer this over your own loop using `parent_id`.
669 pub fn parent_owner_iter(self, current_id: HirId) -> ParentOwnerIterator<'hir> {
670 ParentOwnerIterator { current_id, map: self }
673 /// Checks if the node is left-hand side of an assignment.
674 pub fn is_lhs(self, id: HirId) -> bool {
675 match self.find_parent(id) {
676 Some(Node::Expr(expr)) => match expr.kind {
677 ExprKind::Assign(lhs, _rhs, _span) => lhs.hir_id == id,
684 /// Whether the expression pointed at by `hir_id` belongs to a `const` evaluation context.
685 /// Used exclusively for diagnostics, to avoid suggestion function calls.
686 pub fn is_inside_const_context(self, hir_id: HirId) -> bool {
687 self.body_const_context(self.enclosing_body_owner(hir_id)).is_some()
690 /// Retrieves the `HirId` for `id`'s enclosing method, unless there's a
691 /// `while` or `loop` before reaching it, as block tail returns are not
692 /// available in them.
695 /// fn foo(x: usize) -> bool {
697 /// true // If `get_return_block` gets passed the `id` corresponding
698 /// } else { // to this, it will return `foo`'s `HirId`.
704 /// ```compile_fail,E0308
705 /// fn foo(x: usize) -> bool {
707 /// true // If `get_return_block` gets passed the `id` corresponding
708 /// } // to this, it will return `None`.
712 pub fn get_return_block(self, id: HirId) -> Option<HirId> {
713 let mut iter = self.parent_iter(id).peekable();
714 let mut ignore_tail = false;
715 if let Some(Node::Expr(Expr { kind: ExprKind::Ret(_), .. })) = self.find(id) {
716 // When dealing with `return` statements, we don't care about climbing only tail
720 while let Some((hir_id, node)) = iter.next() {
721 if let (Some((_, next_node)), false) = (iter.peek(), ignore_tail) {
723 Node::Block(Block { expr: None, .. }) => return None,
724 // The current node is not the tail expression of its parent.
725 Node::Block(Block { expr: Some(e), .. }) if hir_id != e.hir_id => return None,
731 | Node::ForeignItem(_)
733 | Node::Expr(Expr { kind: ExprKind::Closure { .. }, .. })
734 | Node::ImplItem(_) => return Some(hir_id),
735 // Ignore `return`s on the first iteration
736 Node::Expr(Expr { kind: ExprKind::Loop(..) | ExprKind::Ret(..), .. })
737 | Node::Local(_) => {
746 /// Retrieves the `OwnerId` for `id`'s parent item, or `id` itself if no
747 /// parent item is in this map. The "parent item" is the closest parent node
748 /// in the HIR which is recorded by the map and is an item, either an item
749 /// in a module, trait, or impl.
750 pub fn get_parent_item(self, hir_id: HirId) -> OwnerId {
751 if let Some((def_id, _node)) = self.parent_owner_iter(hir_id).next() {
758 /// Returns the `OwnerId` of `id`'s nearest module parent, or `id` itself if no
759 /// module parent is in this map.
760 pub(super) fn get_module_parent_node(self, hir_id: HirId) -> OwnerId {
761 for (def_id, node) in self.parent_owner_iter(hir_id) {
762 if let OwnerNode::Item(&Item { kind: ItemKind::Mod(_), .. }) = node {
769 /// When on an if expression, a match arm tail expression or a match arm, give back
770 /// the enclosing `if` or `match` expression.
772 /// Used by error reporting when there's a type error in an if or match arm caused by the
773 /// expression needing to be unit.
774 pub fn get_if_cause(self, hir_id: HirId) -> Option<&'hir Expr<'hir>> {
775 for (_, node) in self.parent_iter(hir_id) {
778 | Node::ForeignItem(_)
781 | Node::Stmt(Stmt { kind: StmtKind::Local(_), .. }) => break,
782 Node::Expr(expr @ Expr { kind: ExprKind::If(..) | ExprKind::Match(..), .. }) => {
791 /// Returns the nearest enclosing scope. A scope is roughly an item or block.
792 pub fn get_enclosing_scope(self, hir_id: HirId) -> Option<HirId> {
793 for (hir_id, node) in self.parent_iter(hir_id) {
794 if let Node::Item(Item {
797 | ItemKind::Const(..)
798 | ItemKind::Static(..)
801 | ItemKind::Struct(..)
802 | ItemKind::Union(..)
803 | ItemKind::Trait(..)
804 | ItemKind::Impl { .. },
807 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(..), .. })
808 | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(..), .. })
809 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(..), .. })
810 | Node::Block(_) = node
818 /// Returns the defining scope for an opaque type definition.
819 pub fn get_defining_scope(self, id: HirId) -> HirId {
822 scope = self.get_enclosing_scope(scope).unwrap_or(CRATE_HIR_ID);
823 if scope == CRATE_HIR_ID || !matches!(self.get(scope), Node::Block(_)) {
829 pub fn get_foreign_abi(self, hir_id: HirId) -> Abi {
830 let parent = self.get_parent_item(hir_id);
831 if let Some(node) = self.tcx.hir_owner(parent) {
832 if let OwnerNode::Item(Item { kind: ItemKind::ForeignMod { abi, .. }, .. }) = node.node
838 "expected foreign mod or inlined parent, found {}",
839 self.node_to_string(HirId::make_owner(parent.def_id))
843 pub fn expect_owner(self, def_id: LocalDefId) -> OwnerNode<'hir> {
845 .hir_owner(OwnerId { def_id })
846 .unwrap_or_else(|| bug!("expected owner for {:?}", def_id))
850 pub fn expect_item(self, id: LocalDefId) -> &'hir Item<'hir> {
851 match self.tcx.hir_owner(OwnerId { def_id: id }) {
852 Some(Owner { node: OwnerNode::Item(item), .. }) => item,
853 _ => bug!("expected item, found {}", self.node_to_string(HirId::make_owner(id))),
857 pub fn expect_impl_item(self, id: LocalDefId) -> &'hir ImplItem<'hir> {
858 match self.tcx.hir_owner(OwnerId { def_id: id }) {
859 Some(Owner { node: OwnerNode::ImplItem(item), .. }) => item,
860 _ => bug!("expected impl item, found {}", self.node_to_string(HirId::make_owner(id))),
864 pub fn expect_trait_item(self, id: LocalDefId) -> &'hir TraitItem<'hir> {
865 match self.tcx.hir_owner(OwnerId { def_id: id }) {
866 Some(Owner { node: OwnerNode::TraitItem(item), .. }) => item,
867 _ => bug!("expected trait item, found {}", self.node_to_string(HirId::make_owner(id))),
871 pub fn expect_variant(self, id: HirId) -> &'hir Variant<'hir> {
872 match self.find(id) {
873 Some(Node::Variant(variant)) => variant,
874 _ => bug!("expected variant, found {}", self.node_to_string(id)),
878 pub fn expect_foreign_item(self, id: OwnerId) -> &'hir ForeignItem<'hir> {
879 match self.tcx.hir_owner(id) {
880 Some(Owner { node: OwnerNode::ForeignItem(item), .. }) => item,
883 "expected foreign item, found {}",
884 self.node_to_string(HirId::make_owner(id.def_id))
890 pub fn expect_expr(self, id: HirId) -> &'hir Expr<'hir> {
891 match self.find(id) {
892 Some(Node::Expr(expr)) => expr,
893 _ => bug!("expected expr, found {}", self.node_to_string(id)),
898 fn opt_ident(self, id: HirId) -> Option<Ident> {
900 Node::Pat(&Pat { kind: PatKind::Binding(_, _, ident, _), .. }) => Some(ident),
901 // A `Ctor` doesn't have an identifier itself, but its parent
902 // struct/variant does. Compare with `hir::Map::opt_span`.
903 Node::Ctor(..) => match self.find_parent(id)? {
904 Node::Item(item) => Some(item.ident),
905 Node::Variant(variant) => Some(variant.ident),
908 node => node.ident(),
913 pub(super) fn opt_ident_span(self, id: HirId) -> Option<Span> {
914 self.opt_ident(id).map(|ident| ident.span)
918 pub fn opt_name(self, id: HirId) -> Option<Symbol> {
919 self.opt_ident(id).map(|ident| ident.name)
922 pub fn name(self, id: HirId) -> Symbol {
923 self.opt_name(id).unwrap_or_else(|| bug!("no name for {}", self.node_to_string(id)))
926 /// Given a node ID, gets a list of attributes associated with the AST
927 /// corresponding to the node-ID.
928 pub fn attrs(self, id: HirId) -> &'hir [ast::Attribute] {
929 self.tcx.hir_attrs(id.owner).get(id.local_id)
932 /// Gets the span of the definition of the specified HIR node.
933 /// This is used by `tcx.def_span`.
934 pub fn span(self, hir_id: HirId) -> Span {
935 self.opt_span(hir_id)
936 .unwrap_or_else(|| bug!("hir::map::Map::span: id not in map: {:?}", hir_id))
939 pub fn opt_span(self, hir_id: HirId) -> Option<Span> {
940 fn until_within(outer: Span, end: Span) -> Span {
941 if let Some(end) = end.find_ancestor_inside(outer) {
942 outer.with_hi(end.hi())
948 fn named_span(item_span: Span, ident: Ident, generics: Option<&Generics<'_>>) -> Span {
949 if ident.name != kw::Empty {
950 let mut span = until_within(item_span, ident.span);
951 if let Some(g) = generics
952 && !g.span.is_dummy()
953 && let Some(g_span) = g.span.find_ancestor_inside(item_span)
955 span = span.to(g_span);
963 let span = match self.find(hir_id)? {
965 Node::Item(Item { kind: ItemKind::Fn(sig, ..), span: outer_span, .. })
966 | Node::TraitItem(TraitItem {
967 kind: TraitItemKind::Fn(sig, ..),
971 | Node::ImplItem(ImplItem {
972 kind: ImplItemKind::Fn(sig, ..), span: outer_span, ..
974 // Ensure that the returned span has the item's SyntaxContext, and not the
975 // SyntaxContext of the visibility.
976 sig.span.find_ancestor_in_same_ctxt(*outer_span).unwrap_or(*outer_span)
978 // Constants and Statics.
981 ItemKind::Const(ty, ..)
982 | ItemKind::Static(ty, ..)
983 | ItemKind::Impl(Impl { self_ty: ty, .. }),
987 | Node::TraitItem(TraitItem {
988 kind: TraitItemKind::Const(ty, ..),
992 | Node::ImplItem(ImplItem {
993 kind: ImplItemKind::Const(ty, ..),
997 | Node::ForeignItem(ForeignItem {
998 kind: ForeignItemKind::Static(ty, ..),
1001 }) => until_within(*outer_span, ty.span),
1002 // With generics and bounds.
1004 kind: ItemKind::Trait(_, _, generics, bounds, _),
1008 | Node::TraitItem(TraitItem {
1009 kind: TraitItemKind::Type(bounds, _),
1014 let end = if let Some(b) = bounds.last() { b.span() } else { generics.span };
1015 until_within(*outer_span, end)
1018 Node::Item(item) => match &item.kind {
1019 ItemKind::Use(path, _) => {
1020 // Ensure that the returned span has the item's SyntaxContext, and not the
1021 // SyntaxContext of the path.
1022 path.span.find_ancestor_in_same_ctxt(item.span).unwrap_or(item.span)
1024 _ => named_span(item.span, item.ident, item.kind.generics()),
1026 Node::Variant(variant) => named_span(variant.span, variant.ident, None),
1027 Node::ImplItem(item) => named_span(item.span, item.ident, Some(item.generics)),
1028 Node::ForeignItem(item) => match item.kind {
1029 ForeignItemKind::Fn(decl, _, _) => until_within(item.span, decl.output.span()),
1030 _ => named_span(item.span, item.ident, None),
1032 Node::Ctor(_) => return self.opt_span(self.parent_id(hir_id)),
1034 kind: ExprKind::Closure(Closure { fn_decl_span, .. }),
1038 // Ensure that the returned span has the item's SyntaxContext.
1039 fn_decl_span.find_ancestor_inside(*span).unwrap_or(*span)
1041 _ => self.span_with_body(hir_id),
1043 debug_assert_eq!(span.ctxt(), self.span_with_body(hir_id).ctxt());
1047 /// Like `hir.span()`, but includes the body of items
1048 /// (instead of just the item header)
1049 pub fn span_with_body(self, hir_id: HirId) -> Span {
1050 match self.get(hir_id) {
1051 Node::Param(param) => param.span,
1052 Node::Item(item) => item.span,
1053 Node::ForeignItem(foreign_item) => foreign_item.span,
1054 Node::TraitItem(trait_item) => trait_item.span,
1055 Node::ImplItem(impl_item) => impl_item.span,
1056 Node::Variant(variant) => variant.span,
1057 Node::Field(field) => field.span,
1058 Node::AnonConst(constant) => self.body(constant.body).value.span,
1059 Node::Expr(expr) => expr.span,
1060 Node::ExprField(field) => field.span,
1061 Node::Stmt(stmt) => stmt.span,
1062 Node::PathSegment(seg) => {
1063 let ident_span = seg.ident.span;
1065 .with_hi(seg.args.map_or_else(|| ident_span.hi(), |args| args.span_ext.hi()))
1067 Node::Ty(ty) => ty.span,
1068 Node::TypeBinding(tb) => tb.span,
1069 Node::TraitRef(tr) => tr.path.span,
1070 Node::Pat(pat) => pat.span,
1071 Node::PatField(field) => field.span,
1072 Node::Arm(arm) => arm.span,
1073 Node::Block(block) => block.span,
1074 Node::Ctor(..) => self.span_with_body(self.parent_id(hir_id)),
1075 Node::Lifetime(lifetime) => lifetime.ident.span,
1076 Node::GenericParam(param) => param.span,
1077 Node::Infer(i) => i.span,
1078 Node::Local(local) => local.span,
1079 Node::Crate(item) => item.spans.inner_span,
1083 pub fn span_if_local(self, id: DefId) -> Option<Span> {
1084 if id.is_local() { Some(self.tcx.def_span(id)) } else { None }
1087 pub fn res_span(self, res: Res) -> Option<Span> {
1090 Res::Local(id) => Some(self.span(id)),
1091 res => self.span_if_local(res.opt_def_id()?),
1095 /// Get a representation of this `id` for debugging purposes.
1096 /// NOTE: Do NOT use this in diagnostics!
1097 pub fn node_to_string(self, id: HirId) -> String {
1098 hir_id_to_string(self, id)
1101 /// Returns the HirId of `N` in `struct Foo<const N: usize = { ... }>` when
1102 /// called with the HirId for the `{ ... }` anon const
1103 pub fn opt_const_param_default_param_def_id(self, anon_const: HirId) -> Option<LocalDefId> {
1104 match self.get_parent(anon_const) {
1105 Node::GenericParam(GenericParam {
1107 kind: GenericParamKind::Const { .. },
1109 }) => Some(*param_id),
1115 impl<'hir> intravisit::Map<'hir> for Map<'hir> {
1116 fn find(&self, hir_id: HirId) -> Option<Node<'hir>> {
1117 (*self).find(hir_id)
1120 fn body(&self, id: BodyId) -> &'hir Body<'hir> {
1124 fn item(&self, id: ItemId) -> &'hir Item<'hir> {
1128 fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
1129 (*self).trait_item(id)
1132 fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
1133 (*self).impl_item(id)
1136 fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
1137 (*self).foreign_item(id)
1141 pub(super) fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
1142 debug_assert_eq!(crate_num, LOCAL_CRATE);
1143 let krate = tcx.hir_crate(());
1144 let hir_body_hash = krate.hir_hash;
1146 let upstream_crates = upstream_crates(tcx);
1148 let resolutions = tcx.resolutions(());
1150 // We hash the final, remapped names of all local source files so we
1151 // don't have to include the path prefix remapping commandline args.
1152 // If we included the full mapping in the SVH, we could only have
1153 // reproducible builds by compiling from the same directory. So we just
1154 // hash the result of the mapping instead of the mapping itself.
1155 let mut source_file_names: Vec<_> = tcx
1160 .filter(|source_file| source_file.cnum == LOCAL_CRATE)
1161 .map(|source_file| source_file.name_hash)
1164 source_file_names.sort_unstable();
1166 let crate_hash: Fingerprint = tcx.with_stable_hashing_context(|mut hcx| {
1167 let mut stable_hasher = StableHasher::new();
1168 hir_body_hash.hash_stable(&mut hcx, &mut stable_hasher);
1169 upstream_crates.hash_stable(&mut hcx, &mut stable_hasher);
1170 source_file_names.hash_stable(&mut hcx, &mut stable_hasher);
1171 if tcx.sess.opts.incremental_relative_spans() {
1172 let definitions = tcx.definitions_untracked();
1173 let mut owner_spans: Vec<_> = krate
1176 .filter_map(|(def_id, info)| {
1177 let _ = info.as_owner()?;
1178 let def_path_hash = definitions.def_path_hash(def_id);
1179 let span = tcx.source_span(def_id);
1180 debug_assert_eq!(span.parent(), None);
1181 Some((def_path_hash, span))
1184 owner_spans.sort_unstable_by_key(|bn| bn.0);
1185 owner_spans.hash_stable(&mut hcx, &mut stable_hasher);
1187 tcx.sess.opts.dep_tracking_hash(true).hash_stable(&mut hcx, &mut stable_hasher);
1188 tcx.sess.local_stable_crate_id().hash_stable(&mut hcx, &mut stable_hasher);
1189 // Hash visibility information since it does not appear in HIR.
1190 resolutions.visibilities.hash_stable(&mut hcx, &mut stable_hasher);
1191 resolutions.has_pub_restricted.hash_stable(&mut hcx, &mut stable_hasher);
1192 stable_hasher.finish()
1195 Svh::new(crate_hash.to_smaller_hash())
1198 fn upstream_crates(tcx: TyCtxt<'_>) -> Vec<(StableCrateId, Svh)> {
1199 let mut upstream_crates: Vec<_> = tcx
1203 let stable_crate_id = tcx.stable_crate_id(cnum);
1204 let hash = tcx.crate_hash(cnum);
1205 (stable_crate_id, hash)
1208 upstream_crates.sort_unstable_by_key(|&(stable_crate_id, _)| stable_crate_id);
1212 fn hir_id_to_string(map: Map<'_>, id: HirId) -> String {
1213 let id_str = format!(" (hir_id={})", id);
1215 let path_str = |def_id: LocalDefId| map.tcx.def_path_str(def_id.to_def_id());
1217 let span_str = || map.tcx.sess.source_map().span_to_snippet(map.span(id)).unwrap_or_default();
1218 let node_str = |prefix| format!("{} {}{}", prefix, span_str(), id_str);
1220 match map.find(id) {
1221 Some(Node::Item(item)) => {
1222 let item_str = match item.kind {
1223 ItemKind::ExternCrate(..) => "extern crate",
1224 ItemKind::Use(..) => "use",
1225 ItemKind::Static(..) => "static",
1226 ItemKind::Const(..) => "const",
1227 ItemKind::Fn(..) => "fn",
1228 ItemKind::Macro(..) => "macro",
1229 ItemKind::Mod(..) => "mod",
1230 ItemKind::ForeignMod { .. } => "foreign mod",
1231 ItemKind::GlobalAsm(..) => "global asm",
1232 ItemKind::TyAlias(..) => "ty",
1233 ItemKind::OpaqueTy(ref opaque) => {
1234 if opaque.in_trait {
1235 "opaque type in trait"
1240 ItemKind::Enum(..) => "enum",
1241 ItemKind::Struct(..) => "struct",
1242 ItemKind::Union(..) => "union",
1243 ItemKind::Trait(..) => "trait",
1244 ItemKind::TraitAlias(..) => "trait alias",
1245 ItemKind::Impl { .. } => "impl",
1247 format!("{} {}{}", item_str, path_str(item.owner_id.def_id), id_str)
1249 Some(Node::ForeignItem(item)) => {
1250 format!("foreign item {}{}", path_str(item.owner_id.def_id), id_str)
1252 Some(Node::ImplItem(ii)) => {
1253 let kind = match ii.kind {
1254 ImplItemKind::Const(..) => "assoc const",
1255 ImplItemKind::Fn(..) => "method",
1256 ImplItemKind::Type(_) => "assoc type",
1258 format!("{} {} in {}{}", kind, ii.ident, path_str(ii.owner_id.def_id), id_str)
1260 Some(Node::TraitItem(ti)) => {
1261 let kind = match ti.kind {
1262 TraitItemKind::Const(..) => "assoc constant",
1263 TraitItemKind::Fn(..) => "trait method",
1264 TraitItemKind::Type(..) => "assoc type",
1267 format!("{} {} in {}{}", kind, ti.ident, path_str(ti.owner_id.def_id), id_str)
1269 Some(Node::Variant(ref variant)) => {
1270 format!("variant {} in {}{}", variant.ident, path_str(variant.def_id), id_str)
1272 Some(Node::Field(ref field)) => {
1273 format!("field {} in {}{}", field.ident, path_str(field.def_id), id_str)
1275 Some(Node::AnonConst(_)) => node_str("const"),
1276 Some(Node::Expr(_)) => node_str("expr"),
1277 Some(Node::ExprField(_)) => node_str("expr field"),
1278 Some(Node::Stmt(_)) => node_str("stmt"),
1279 Some(Node::PathSegment(_)) => node_str("path segment"),
1280 Some(Node::Ty(_)) => node_str("type"),
1281 Some(Node::TypeBinding(_)) => node_str("type binding"),
1282 Some(Node::TraitRef(_)) => node_str("trait ref"),
1283 Some(Node::Pat(_)) => node_str("pat"),
1284 Some(Node::PatField(_)) => node_str("pattern field"),
1285 Some(Node::Param(_)) => node_str("param"),
1286 Some(Node::Arm(_)) => node_str("arm"),
1287 Some(Node::Block(_)) => node_str("block"),
1288 Some(Node::Infer(_)) => node_str("infer"),
1289 Some(Node::Local(_)) => node_str("local"),
1290 Some(Node::Ctor(ctor)) => format!(
1292 ctor.ctor_def_id().map_or("<missing path>".into(), |def_id| path_str(def_id)),
1295 Some(Node::Lifetime(_)) => node_str("lifetime"),
1296 Some(Node::GenericParam(ref param)) => {
1297 format!("generic_param {}{}", path_str(param.def_id), id_str)
1299 Some(Node::Crate(..)) => String::from("root_crate"),
1300 None => format!("unknown node{}", id_str),
1304 pub(super) fn hir_module_items(tcx: TyCtxt<'_>, module_id: LocalDefId) -> ModuleItems {
1305 let mut collector = ItemCollector::new(tcx, false);
1307 let (hir_mod, span, hir_id) = tcx.hir().get_module(module_id);
1308 collector.visit_mod(hir_mod, span, hir_id);
1319 return ModuleItems {
1320 submodules: submodules.into_boxed_slice(),
1321 items: items.into_boxed_slice(),
1322 trait_items: trait_items.into_boxed_slice(),
1323 impl_items: impl_items.into_boxed_slice(),
1324 foreign_items: foreign_items.into_boxed_slice(),
1325 body_owners: body_owners.into_boxed_slice(),
1329 pub(crate) fn hir_crate_items(tcx: TyCtxt<'_>, _: ()) -> ModuleItems {
1330 let mut collector = ItemCollector::new(tcx, true);
1332 // A "crate collector" and "module collector" start at a
1333 // module item (the former starts at the crate root) but only
1334 // the former needs to collect it. ItemCollector does not do this for us.
1335 collector.submodules.push(CRATE_OWNER_ID);
1336 tcx.hir().walk_toplevel_module(&mut collector);
1348 return ModuleItems {
1349 submodules: submodules.into_boxed_slice(),
1350 items: items.into_boxed_slice(),
1351 trait_items: trait_items.into_boxed_slice(),
1352 impl_items: impl_items.into_boxed_slice(),
1353 foreign_items: foreign_items.into_boxed_slice(),
1354 body_owners: body_owners.into_boxed_slice(),
1358 struct ItemCollector<'tcx> {
1359 // When true, it collects all items in the create,
1360 // otherwise it collects items in some module.
1361 crate_collector: bool,
1363 submodules: Vec<OwnerId>,
1365 trait_items: Vec<TraitItemId>,
1366 impl_items: Vec<ImplItemId>,
1367 foreign_items: Vec<ForeignItemId>,
1368 body_owners: Vec<LocalDefId>,
1371 impl<'tcx> ItemCollector<'tcx> {
1372 fn new(tcx: TyCtxt<'tcx>, crate_collector: bool) -> ItemCollector<'tcx> {
1376 submodules: Vec::default(),
1377 items: Vec::default(),
1378 trait_items: Vec::default(),
1379 impl_items: Vec::default(),
1380 foreign_items: Vec::default(),
1381 body_owners: Vec::default(),
1386 impl<'hir> Visitor<'hir> for ItemCollector<'hir> {
1387 type NestedFilter = nested_filter::All;
1389 fn nested_visit_map(&mut self) -> Self::Map {
1393 fn visit_item(&mut self, item: &'hir Item<'hir>) {
1394 if associated_body(Node::Item(item)).is_some() {
1395 self.body_owners.push(item.owner_id.def_id);
1398 self.items.push(item.item_id());
1400 // Items that are modules are handled here instead of in visit_mod.
1401 if let ItemKind::Mod(module) = &item.kind {
1402 self.submodules.push(item.owner_id);
1403 // A module collector does not recurse inside nested modules.
1404 if self.crate_collector {
1405 intravisit::walk_mod(self, module, item.hir_id());
1408 intravisit::walk_item(self, item)
1412 fn visit_foreign_item(&mut self, item: &'hir ForeignItem<'hir>) {
1413 self.foreign_items.push(item.foreign_item_id());
1414 intravisit::walk_foreign_item(self, item)
1417 fn visit_anon_const(&mut self, c: &'hir AnonConst) {
1418 self.body_owners.push(c.def_id);
1419 intravisit::walk_anon_const(self, c)
1422 fn visit_expr(&mut self, ex: &'hir Expr<'hir>) {
1423 if let ExprKind::Closure(closure) = ex.kind {
1424 self.body_owners.push(closure.def_id);
1426 intravisit::walk_expr(self, ex)
1429 fn visit_trait_item(&mut self, item: &'hir TraitItem<'hir>) {
1430 if associated_body(Node::TraitItem(item)).is_some() {
1431 self.body_owners.push(item.owner_id.def_id);
1434 self.trait_items.push(item.trait_item_id());
1435 intravisit::walk_trait_item(self, item)
1438 fn visit_impl_item(&mut self, item: &'hir ImplItem<'hir>) {
1439 if associated_body(Node::ImplItem(item)).is_some() {
1440 self.body_owners.push(item.owner_id.def_id);
1443 self.impl_items.push(item.impl_item_id());
1444 intravisit::walk_impl_item(self, item)