]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/hir/map/mod.rs
Gather module items after lowering.
[rust.git] / compiler / rustc_middle / src / hir / map / mod.rs
1 use self::collector::NodeCollector;
2
3 use crate::hir::{AttributeMap, IndexedHir, ModuleItems, Owner};
4 use crate::ty::TyCtxt;
5 use rustc_ast as ast;
6 use rustc_data_structures::fingerprint::Fingerprint;
7 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
8 use rustc_data_structures::svh::Svh;
9 use rustc_data_structures::sync::{self, par_iter};
10 use rustc_hir::def::{DefKind, Res};
11 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE};
12 use rustc_hir::definitions::{DefKey, DefPath, DefPathHash};
13 use rustc_hir::intravisit::{self, Visitor};
14 use rustc_hir::itemlikevisit::ItemLikeVisitor;
15 use rustc_hir::*;
16 use rustc_index::vec::Idx;
17 use rustc_span::def_id::StableCrateId;
18 use rustc_span::hygiene::MacroKind;
19 use rustc_span::source_map::Spanned;
20 use rustc_span::symbol::{kw, sym, Ident, Symbol};
21 use rustc_span::Span;
22 use rustc_target::spec::abi::Abi;
23 use std::collections::BTreeSet;
24
25 pub mod blocks;
26 mod collector;
27
28 fn fn_decl<'hir>(node: Node<'hir>) -> Option<&'hir FnDecl<'hir>> {
29     match node {
30         Node::Item(Item { kind: ItemKind::Fn(sig, _, _), .. })
31         | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(sig, _), .. })
32         | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(sig, _), .. }) => Some(&sig.decl),
33         Node::Expr(Expr { kind: ExprKind::Closure(_, fn_decl, ..), .. })
34         | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, ..), .. }) => {
35             Some(fn_decl)
36         }
37         _ => None,
38     }
39 }
40
41 pub fn fn_sig<'hir>(node: Node<'hir>) -> Option<&'hir FnSig<'hir>> {
42     match &node {
43         Node::Item(Item { kind: ItemKind::Fn(sig, _, _), .. })
44         | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(sig, _), .. })
45         | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(sig, _), .. }) => Some(sig),
46         _ => None,
47     }
48 }
49
50 pub fn associated_body<'hir>(node: Node<'hir>) -> Option<BodyId> {
51     match node {
52         Node::Item(Item {
53             kind: ItemKind::Const(_, body) | ItemKind::Static(.., body) | ItemKind::Fn(.., body),
54             ..
55         })
56         | Node::TraitItem(TraitItem {
57             kind:
58                 TraitItemKind::Const(_, Some(body)) | TraitItemKind::Fn(_, TraitFn::Provided(body)),
59             ..
60         })
61         | Node::ImplItem(ImplItem {
62             kind: ImplItemKind::Const(_, body) | ImplItemKind::Fn(_, body),
63             ..
64         })
65         | Node::Expr(Expr { kind: ExprKind::Closure(.., body, _, _), .. }) => Some(*body),
66
67         Node::AnonConst(constant) => Some(constant.body),
68
69         _ => None,
70     }
71 }
72
73 fn is_body_owner<'hir>(node: Node<'hir>, hir_id: HirId) -> bool {
74     match associated_body(node) {
75         Some(b) => b.hir_id == hir_id,
76         None => false,
77     }
78 }
79
80 #[derive(Copy, Clone)]
81 pub struct Map<'hir> {
82     pub(super) tcx: TyCtxt<'hir>,
83 }
84
85 /// An iterator that walks up the ancestor tree of a given `HirId`.
86 /// Constructed using `tcx.hir().parent_iter(hir_id)`.
87 pub struct ParentHirIterator<'map, 'hir> {
88     current_id: HirId,
89     map: &'map Map<'hir>,
90 }
91
92 impl<'hir> Iterator for ParentHirIterator<'_, 'hir> {
93     type Item = (HirId, Node<'hir>);
94
95     fn next(&mut self) -> Option<Self::Item> {
96         if self.current_id == CRATE_HIR_ID {
97             return None;
98         }
99         loop {
100             // There are nodes that do not have entries, so we need to skip them.
101             let parent_id = self.map.get_parent_node(self.current_id);
102
103             if parent_id == self.current_id {
104                 self.current_id = CRATE_HIR_ID;
105                 return None;
106             }
107
108             self.current_id = parent_id;
109             if let Some(node) = self.map.find(parent_id) {
110                 return Some((parent_id, node));
111             }
112             // If this `HirId` doesn't have an entry, skip it and look for its `parent_id`.
113         }
114     }
115 }
116
117 /// An iterator that walks up the ancestor tree of a given `HirId`.
118 /// Constructed using `tcx.hir().parent_owner_iter(hir_id)`.
119 pub struct ParentOwnerIterator<'map, 'hir> {
120     current_id: HirId,
121     map: &'map Map<'hir>,
122 }
123
124 impl<'hir> Iterator for ParentOwnerIterator<'_, 'hir> {
125     type Item = (HirId, OwnerNode<'hir>);
126
127     fn next(&mut self) -> Option<Self::Item> {
128         if self.current_id.local_id.index() != 0 {
129             self.current_id.local_id = ItemLocalId::new(0);
130             if let Some(node) = self.map.tcx.hir_owner(self.current_id.owner) {
131                 return Some((self.current_id, node.node));
132             }
133         }
134         if self.current_id == CRATE_HIR_ID {
135             return None;
136         }
137         loop {
138             // There are nodes that do not have entries, so we need to skip them.
139             let parent_id = self.map.def_key(self.current_id.owner).parent;
140
141             let parent_id = parent_id.map_or(CRATE_HIR_ID.owner, |local_def_index| {
142                 let def_id = LocalDefId { local_def_index };
143                 self.map.local_def_id_to_hir_id(def_id).owner
144             });
145             self.current_id = HirId::make_owner(parent_id);
146
147             // If this `HirId` doesn't have an entry, skip it and look for its `parent_id`.
148             if let Some(node) = self.map.tcx.hir_owner(self.current_id.owner) {
149                 return Some((self.current_id, node.node));
150             }
151         }
152     }
153 }
154
155 impl<'hir> Map<'hir> {
156     pub fn krate(&self) -> &'hir Crate<'hir> {
157         self.tcx.hir_crate(())
158     }
159
160     pub fn def_key(&self, def_id: LocalDefId) -> DefKey {
161         // Accessing the DefKey is ok, since it is part of DefPathHash.
162         self.tcx.untracked_resolutions.definitions.def_key(def_id)
163     }
164
165     pub fn def_path_from_hir_id(&self, id: HirId) -> Option<DefPath> {
166         self.opt_local_def_id(id).map(|def_id| self.def_path(def_id))
167     }
168
169     pub fn def_path(&self, def_id: LocalDefId) -> DefPath {
170         // Accessing the DefPath is ok, since it is part of DefPathHash.
171         self.tcx.untracked_resolutions.definitions.def_path(def_id)
172     }
173
174     #[inline]
175     pub fn def_path_hash(self, def_id: LocalDefId) -> DefPathHash {
176         // Accessing the DefPathHash is ok, it is incr. comp. stable.
177         self.tcx.untracked_resolutions.definitions.def_path_hash(def_id)
178     }
179
180     #[inline]
181     pub fn local_def_id(&self, hir_id: HirId) -> LocalDefId {
182         self.opt_local_def_id(hir_id).unwrap_or_else(|| {
183             bug!(
184                 "local_def_id: no entry for `{:?}`, which has a map of `{:?}`",
185                 hir_id,
186                 self.find(hir_id)
187             )
188         })
189     }
190
191     #[inline]
192     pub fn opt_local_def_id(&self, hir_id: HirId) -> Option<LocalDefId> {
193         // FIXME(#85914) is this access safe for incr. comp.?
194         self.tcx.untracked_resolutions.definitions.opt_hir_id_to_local_def_id(hir_id)
195     }
196
197     #[inline]
198     pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId {
199         // FIXME(#85914) is this access safe for incr. comp.?
200         self.tcx.untracked_resolutions.definitions.local_def_id_to_hir_id(def_id)
201     }
202
203     pub fn iter_local_def_id(&self) -> impl Iterator<Item = LocalDefId> + '_ {
204         // Create a dependency to the crate to be sure we reexcute this when the amount of
205         // definitions change.
206         self.tcx.ensure().hir_crate(());
207         self.tcx.untracked_resolutions.definitions.iter_local_def_id()
208     }
209
210     pub fn opt_def_kind(&self, local_def_id: LocalDefId) -> Option<DefKind> {
211         // FIXME(eddyb) support `find` on the crate root.
212         if local_def_id.to_def_id().index == CRATE_DEF_INDEX {
213             return Some(DefKind::Mod);
214         }
215
216         let hir_id = self.local_def_id_to_hir_id(local_def_id);
217         let def_kind = match self.find(hir_id)? {
218             Node::Item(item) => match item.kind {
219                 ItemKind::Static(..) => DefKind::Static,
220                 ItemKind::Const(..) => DefKind::Const,
221                 ItemKind::Fn(..) => DefKind::Fn,
222                 ItemKind::Macro(..) => DefKind::Macro(MacroKind::Bang),
223                 ItemKind::Mod(..) => DefKind::Mod,
224                 ItemKind::OpaqueTy(..) => DefKind::OpaqueTy,
225                 ItemKind::TyAlias(..) => DefKind::TyAlias,
226                 ItemKind::Enum(..) => DefKind::Enum,
227                 ItemKind::Struct(..) => DefKind::Struct,
228                 ItemKind::Union(..) => DefKind::Union,
229                 ItemKind::Trait(..) => DefKind::Trait,
230                 ItemKind::TraitAlias(..) => DefKind::TraitAlias,
231                 ItemKind::ExternCrate(_) => DefKind::ExternCrate,
232                 ItemKind::Use(..) => DefKind::Use,
233                 ItemKind::ForeignMod { .. } => DefKind::ForeignMod,
234                 ItemKind::GlobalAsm(..) => DefKind::GlobalAsm,
235                 ItemKind::Impl { .. } => DefKind::Impl,
236             },
237             Node::ForeignItem(item) => match item.kind {
238                 ForeignItemKind::Fn(..) => DefKind::Fn,
239                 ForeignItemKind::Static(..) => DefKind::Static,
240                 ForeignItemKind::Type => DefKind::ForeignTy,
241             },
242             Node::TraitItem(item) => match item.kind {
243                 TraitItemKind::Const(..) => DefKind::AssocConst,
244                 TraitItemKind::Fn(..) => DefKind::AssocFn,
245                 TraitItemKind::Type(..) => DefKind::AssocTy,
246             },
247             Node::ImplItem(item) => match item.kind {
248                 ImplItemKind::Const(..) => DefKind::AssocConst,
249                 ImplItemKind::Fn(..) => DefKind::AssocFn,
250                 ImplItemKind::TyAlias(..) => DefKind::AssocTy,
251             },
252             Node::Variant(_) => DefKind::Variant,
253             Node::Ctor(variant_data) => {
254                 // FIXME(eddyb) is this even possible, if we have a `Node::Ctor`?
255                 assert_ne!(variant_data.ctor_hir_id(), None);
256
257                 let ctor_of = match self.find(self.get_parent_node(hir_id)) {
258                     Some(Node::Item(..)) => def::CtorOf::Struct,
259                     Some(Node::Variant(..)) => def::CtorOf::Variant,
260                     _ => unreachable!(),
261                 };
262                 DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data))
263             }
264             Node::AnonConst(_) => DefKind::AnonConst,
265             Node::Field(_) => DefKind::Field,
266             Node::Expr(expr) => match expr.kind {
267                 ExprKind::Closure(.., None) => DefKind::Closure,
268                 ExprKind::Closure(.., Some(_)) => DefKind::Generator,
269                 _ => bug!("def_kind: unsupported node: {}", self.node_to_string(hir_id)),
270             },
271             Node::GenericParam(param) => match param.kind {
272                 GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam,
273                 GenericParamKind::Type { .. } => DefKind::TyParam,
274                 GenericParamKind::Const { .. } => DefKind::ConstParam,
275             },
276             Node::Crate(_) => DefKind::Mod,
277             Node::Stmt(_)
278             | Node::PathSegment(_)
279             | Node::Ty(_)
280             | Node::Infer(_)
281             | Node::TraitRef(_)
282             | Node::Pat(_)
283             | Node::Binding(_)
284             | Node::Local(_)
285             | Node::Param(_)
286             | Node::Arm(_)
287             | Node::Lifetime(_)
288             | Node::Visibility(_)
289             | Node::Block(_) => return None,
290         };
291         Some(def_kind)
292     }
293
294     pub fn def_kind(&self, local_def_id: LocalDefId) -> DefKind {
295         self.opt_def_kind(local_def_id)
296             .unwrap_or_else(|| bug!("def_kind: unsupported node: {:?}", local_def_id))
297     }
298
299     pub fn find_parent_node(&self, id: HirId) -> Option<HirId> {
300         if id.local_id == ItemLocalId::from_u32(0) {
301             Some(self.tcx.hir_owner_parent(id.owner))
302         } else {
303             let owner = self.tcx.hir_owner_nodes(id.owner)?;
304             let node = owner.nodes[id.local_id].as_ref()?;
305             let hir_id = HirId { owner: id.owner, local_id: node.parent };
306             Some(hir_id)
307         }
308     }
309
310     pub fn get_parent_node(&self, hir_id: HirId) -> HirId {
311         self.find_parent_node(hir_id).unwrap_or(CRATE_HIR_ID)
312     }
313
314     /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
315     pub fn find(&self, id: HirId) -> Option<Node<'hir>> {
316         if id.local_id == ItemLocalId::from_u32(0) {
317             let owner = self.tcx.hir_owner(id.owner)?;
318             Some(owner.node.into())
319         } else {
320             let owner = self.tcx.hir_owner_nodes(id.owner)?;
321             let node = owner.nodes[id.local_id].as_ref()?;
322             Some(node.node)
323         }
324     }
325
326     /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found.
327     pub fn get(&self, id: HirId) -> Node<'hir> {
328         self.find(id).unwrap_or_else(|| bug!("couldn't find hir id {} in the HIR map", id))
329     }
330
331     pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
332         id.as_local().and_then(|id| self.find(self.local_def_id_to_hir_id(id)))
333     }
334
335     pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics<'hir>> {
336         let id = id.as_local()?;
337         let node = self.tcx.hir_owner(id)?;
338         match node.node {
339             OwnerNode::ImplItem(impl_item) => Some(&impl_item.generics),
340             OwnerNode::TraitItem(trait_item) => Some(&trait_item.generics),
341             OwnerNode::Item(Item {
342                 kind:
343                     ItemKind::Fn(_, generics, _)
344                     | ItemKind::TyAlias(_, generics)
345                     | ItemKind::Enum(_, generics)
346                     | ItemKind::Struct(_, generics)
347                     | ItemKind::Union(_, generics)
348                     | ItemKind::Trait(_, _, generics, ..)
349                     | ItemKind::TraitAlias(generics, _)
350                     | ItemKind::Impl(Impl { generics, .. }),
351                 ..
352             }) => Some(generics),
353             _ => None,
354         }
355     }
356
357     pub fn item(&self, id: ItemId) -> &'hir Item<'hir> {
358         self.tcx.hir_owner(id.def_id).unwrap().node.expect_item()
359     }
360
361     pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
362         self.tcx.hir_owner(id.def_id).unwrap().node.expect_trait_item()
363     }
364
365     pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
366         self.tcx.hir_owner(id.def_id).unwrap().node.expect_impl_item()
367     }
368
369     pub fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
370         self.tcx.hir_owner(id.def_id).unwrap().node.expect_foreign_item()
371     }
372
373     pub fn body(&self, id: BodyId) -> &'hir Body<'hir> {
374         self.tcx.hir_owner_nodes(id.hir_id.owner).unwrap().bodies.get(&id.hir_id.local_id).unwrap()
375     }
376
377     pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnDecl<'hir>> {
378         if let Some(node) = self.find(hir_id) {
379             fn_decl(node)
380         } else {
381             bug!("no node for hir_id `{}`", hir_id)
382         }
383     }
384
385     pub fn fn_sig_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnSig<'hir>> {
386         if let Some(node) = self.find(hir_id) {
387             fn_sig(node)
388         } else {
389             bug!("no node for hir_id `{}`", hir_id)
390         }
391     }
392
393     pub fn enclosing_body_owner(&self, hir_id: HirId) -> HirId {
394         for (parent, _) in self.parent_iter(hir_id) {
395             if let Some(body) = self.maybe_body_owned_by(parent) {
396                 return self.body_owner(body);
397             }
398         }
399
400         bug!("no `enclosing_body_owner` for hir_id `{}`", hir_id);
401     }
402
403     /// Returns the `HirId` that corresponds to the definition of
404     /// which this is the body of, i.e., a `fn`, `const` or `static`
405     /// item (possibly associated), a closure, or a `hir::AnonConst`.
406     pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> HirId {
407         let parent = self.get_parent_node(hir_id);
408         assert!(self.find(parent).map_or(false, |n| is_body_owner(n, hir_id)));
409         parent
410     }
411
412     pub fn body_owner_def_id(&self, id: BodyId) -> LocalDefId {
413         self.local_def_id(self.body_owner(id))
414     }
415
416     /// Given a `HirId`, returns the `BodyId` associated with it,
417     /// if the node is a body owner, otherwise returns `None`.
418     pub fn maybe_body_owned_by(&self, hir_id: HirId) -> Option<BodyId> {
419         self.find(hir_id).map(associated_body).flatten()
420     }
421
422     /// Given a body owner's id, returns the `BodyId` associated with it.
423     pub fn body_owned_by(&self, id: HirId) -> BodyId {
424         self.maybe_body_owned_by(id).unwrap_or_else(|| {
425             span_bug!(
426                 self.span(id),
427                 "body_owned_by: {} has no associated body",
428                 self.node_to_string(id)
429             );
430         })
431     }
432
433     pub fn body_param_names(&self, id: BodyId) -> impl Iterator<Item = Ident> + 'hir {
434         self.body(id).params.iter().map(|arg| match arg.pat.kind {
435             PatKind::Binding(_, _, ident, _) => ident,
436             _ => Ident::new(kw::Empty, rustc_span::DUMMY_SP),
437         })
438     }
439
440     /// Returns the `BodyOwnerKind` of this `LocalDefId`.
441     ///
442     /// Panics if `LocalDefId` does not have an associated body.
443     pub fn body_owner_kind(&self, id: HirId) -> BodyOwnerKind {
444         match self.get(id) {
445             Node::Item(&Item { kind: ItemKind::Const(..), .. })
446             | Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. })
447             | Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. })
448             | Node::AnonConst(_) => BodyOwnerKind::Const,
449             Node::Ctor(..)
450             | Node::Item(&Item { kind: ItemKind::Fn(..), .. })
451             | Node::TraitItem(&TraitItem { kind: TraitItemKind::Fn(..), .. })
452             | Node::ImplItem(&ImplItem { kind: ImplItemKind::Fn(..), .. }) => BodyOwnerKind::Fn,
453             Node::Item(&Item { kind: ItemKind::Static(_, m, _), .. }) => BodyOwnerKind::Static(m),
454             Node::Expr(&Expr { kind: ExprKind::Closure(..), .. }) => BodyOwnerKind::Closure,
455             node => bug!("{:#?} is not a body node", node),
456         }
457     }
458
459     /// Returns the `ConstContext` of the body associated with this `LocalDefId`.
460     ///
461     /// Panics if `LocalDefId` does not have an associated body.
462     ///
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     pub fn body_const_context(&self, did: LocalDefId) -> Option<ConstContext> {
466         let hir_id = self.local_def_id_to_hir_id(did);
467         let ccx = match self.body_owner_kind(hir_id) {
468             BodyOwnerKind::Const => ConstContext::Const,
469             BodyOwnerKind::Static(mt) => ConstContext::Static(mt),
470
471             BodyOwnerKind::Fn if self.tcx.is_constructor(did.to_def_id()) => return None,
472             BodyOwnerKind::Fn if self.tcx.is_const_fn_raw(did.to_def_id()) => ConstContext::ConstFn,
473             BodyOwnerKind::Fn
474                 if self.tcx.has_attr(did.to_def_id(), sym::default_method_body_is_const) =>
475             {
476                 ConstContext::ConstFn
477             }
478             BodyOwnerKind::Fn | BodyOwnerKind::Closure => return None,
479         };
480
481         Some(ccx)
482     }
483
484     pub fn ty_param_owner(&self, id: HirId) -> HirId {
485         match self.get(id) {
486             Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => id,
487             Node::GenericParam(_) => self.get_parent_node(id),
488             _ => bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id)),
489         }
490     }
491
492     pub fn ty_param_name(&self, id: HirId) -> Symbol {
493         match self.get(id) {
494             Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => {
495                 kw::SelfUpper
496             }
497             Node::GenericParam(param) => param.name.ident().name,
498             _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
499         }
500     }
501
502     pub fn trait_impls(&self, trait_did: DefId) -> &'hir [LocalDefId] {
503         self.tcx.all_local_trait_impls(()).get(&trait_did).map_or(&[], |xs| &xs[..])
504     }
505
506     /// Gets the attributes on the crate. This is preferable to
507     /// invoking `krate.attrs` because it registers a tighter
508     /// dep-graph access.
509     pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
510         self.attrs(CRATE_HIR_ID)
511     }
512
513     pub fn get_module(&self, module: LocalDefId) -> (&'hir Mod<'hir>, Span, HirId) {
514         let hir_id = HirId::make_owner(module);
515         match self.tcx.hir_owner(module).map(|o| o.node) {
516             Some(OwnerNode::Item(&Item { span, kind: ItemKind::Mod(ref m), .. })) => {
517                 (m, span, hir_id)
518             }
519             Some(OwnerNode::Crate(item)) => (item, item.inner, hir_id),
520             node => panic!("not a module: {:?}", node),
521         }
522     }
523
524     /// Walks the contents of a crate. See also `Crate::visit_all_items`.
525     pub fn walk_toplevel_module(self, visitor: &mut impl Visitor<'hir>) {
526         let (top_mod, span, hir_id) = self.get_module(CRATE_DEF_ID);
527         visitor.visit_mod(top_mod, span, hir_id);
528     }
529
530     /// Walks the attributes in a crate.
531     pub fn walk_attributes(self, visitor: &mut impl Visitor<'hir>) {
532         let krate = self.krate();
533         for (&id, attrs) in krate.attrs.iter() {
534             for a in *attrs {
535                 visitor.visit_attribute(id, a)
536             }
537         }
538     }
539
540     pub fn visit_item_likes_in_module<V>(&self, module: LocalDefId, visitor: &mut V)
541     where
542         V: ItemLikeVisitor<'hir>,
543     {
544         let module = self.tcx.hir_module_items(module);
545
546         for id in &module.items {
547             visitor.visit_item(self.item(*id));
548         }
549
550         for id in &module.trait_items {
551             visitor.visit_trait_item(self.trait_item(*id));
552         }
553
554         for id in &module.impl_items {
555             visitor.visit_impl_item(self.impl_item(*id));
556         }
557
558         for id in &module.foreign_items {
559             visitor.visit_foreign_item(self.foreign_item(*id));
560         }
561     }
562
563     pub fn for_each_module(&self, f: impl Fn(LocalDefId)) {
564         let mut queue = BTreeSet::default();
565         queue.insert(CRATE_DEF_ID);
566
567         while let Some(id) = queue.pop_first() {
568             f(id);
569             let items = self.tcx.hir_module_items(id);
570             queue.extend(items.submodules.iter().copied())
571         }
572     }
573
574     pub fn par_for_each_module(&self, f: impl Fn(LocalDefId) + sync::Sync) {
575         use rustc_data_structures::sync::ParallelIterator;
576         par_iter_submodules(self.tcx, CRATE_DEF_ID, &f);
577
578         fn par_iter_submodules<F>(tcx: TyCtxt<'_>, module: LocalDefId, f: &F)
579         where
580             F: Fn(LocalDefId) + sync::Sync,
581         {
582             (*f)(module);
583             let items = tcx.hir_module_items(module);
584             par_iter(&items.submodules).for_each(|&sm| par_iter_submodules(tcx, sm, f));
585         }
586     }
587
588     /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
589     /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`.
590     pub fn parent_iter(&self, current_id: HirId) -> ParentHirIterator<'_, 'hir> {
591         ParentHirIterator { current_id, map: self }
592     }
593
594     /// Returns an iterator for the nodes in the ancestor tree of the `current_id`
595     /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`.
596     pub fn parent_owner_iter(&self, current_id: HirId) -> ParentOwnerIterator<'_, 'hir> {
597         ParentOwnerIterator { current_id, map: self }
598     }
599
600     /// Checks if the node is left-hand side of an assignment.
601     pub fn is_lhs(&self, id: HirId) -> bool {
602         match self.find(self.get_parent_node(id)) {
603             Some(Node::Expr(expr)) => match expr.kind {
604                 ExprKind::Assign(lhs, _rhs, _span) => lhs.hir_id == id,
605                 _ => false,
606             },
607             _ => false,
608         }
609     }
610
611     /// Whether the expression pointed at by `hir_id` belongs to a `const` evaluation context.
612     /// Used exclusively for diagnostics, to avoid suggestion function calls.
613     pub fn is_inside_const_context(&self, hir_id: HirId) -> bool {
614         self.body_const_context(self.local_def_id(self.enclosing_body_owner(hir_id))).is_some()
615     }
616
617     /// Retrieves the `HirId` for `id`'s enclosing method, unless there's a
618     /// `while` or `loop` before reaching it, as block tail returns are not
619     /// available in them.
620     ///
621     /// ```
622     /// fn foo(x: usize) -> bool {
623     ///     if x == 1 {
624     ///         true  // If `get_return_block` gets passed the `id` corresponding
625     ///     } else {  // to this, it will return `foo`'s `HirId`.
626     ///         false
627     ///     }
628     /// }
629     /// ```
630     ///
631     /// ```
632     /// fn foo(x: usize) -> bool {
633     ///     loop {
634     ///         true  // If `get_return_block` gets passed the `id` corresponding
635     ///     }         // to this, it will return `None`.
636     ///     false
637     /// }
638     /// ```
639     pub fn get_return_block(&self, id: HirId) -> Option<HirId> {
640         let mut iter = self.parent_iter(id).peekable();
641         let mut ignore_tail = false;
642         if let Some(node) = self.find(id) {
643             if let Node::Expr(Expr { kind: ExprKind::Ret(_), .. }) = node {
644                 // When dealing with `return` statements, we don't care about climbing only tail
645                 // expressions.
646                 ignore_tail = true;
647             }
648         }
649         while let Some((hir_id, node)) = iter.next() {
650             if let (Some((_, next_node)), false) = (iter.peek(), ignore_tail) {
651                 match next_node {
652                     Node::Block(Block { expr: None, .. }) => return None,
653                     // The current node is not the tail expression of its parent.
654                     Node::Block(Block { expr: Some(e), .. }) if hir_id != e.hir_id => return None,
655                     _ => {}
656                 }
657             }
658             match node {
659                 Node::Item(_)
660                 | Node::ForeignItem(_)
661                 | Node::TraitItem(_)
662                 | Node::Expr(Expr { kind: ExprKind::Closure(..), .. })
663                 | Node::ImplItem(_) => return Some(hir_id),
664                 // Ignore `return`s on the first iteration
665                 Node::Expr(Expr { kind: ExprKind::Loop(..) | ExprKind::Ret(..), .. })
666                 | Node::Local(_) => {
667                     return None;
668                 }
669                 _ => {}
670             }
671         }
672         None
673     }
674
675     /// Retrieves the `HirId` for `id`'s parent item, or `id` itself if no
676     /// parent item is in this map. The "parent item" is the closest parent node
677     /// in the HIR which is recorded by the map and is an item, either an item
678     /// in a module, trait, or impl.
679     pub fn get_parent_item(&self, hir_id: HirId) -> HirId {
680         if let Some((hir_id, _node)) = self.parent_owner_iter(hir_id).next() {
681             hir_id
682         } else {
683             CRATE_HIR_ID
684         }
685     }
686
687     /// Returns the `HirId` of `id`'s nearest module parent, or `id` itself if no
688     /// module parent is in this map.
689     pub(super) fn get_module_parent_node(&self, hir_id: HirId) -> HirId {
690         for (hir_id, node) in self.parent_owner_iter(hir_id) {
691             if let OwnerNode::Item(&Item { kind: ItemKind::Mod(_), .. }) = node {
692                 return hir_id;
693             }
694         }
695         CRATE_HIR_ID
696     }
697
698     /// When on an if expression, a match arm tail expression or a match arm, give back
699     /// the enclosing `if` or `match` expression.
700     ///
701     /// Used by error reporting when there's a type error in an if or match arm caused by the
702     /// expression needing to be unit.
703     pub fn get_if_cause(&self, hir_id: HirId) -> Option<&'hir Expr<'hir>> {
704         for (_, node) in self.parent_iter(hir_id) {
705             match node {
706                 Node::Item(_)
707                 | Node::ForeignItem(_)
708                 | Node::TraitItem(_)
709                 | Node::ImplItem(_)
710                 | Node::Stmt(Stmt { kind: StmtKind::Local(_), .. }) => break,
711                 Node::Expr(expr @ Expr { kind: ExprKind::If(..) | ExprKind::Match(..), .. }) => {
712                     return Some(expr);
713                 }
714                 _ => {}
715             }
716         }
717         None
718     }
719
720     /// Returns the nearest enclosing scope. A scope is roughly an item or block.
721     pub fn get_enclosing_scope(&self, hir_id: HirId) -> Option<HirId> {
722         for (hir_id, node) in self.parent_iter(hir_id) {
723             if let Node::Item(Item {
724                 kind:
725                     ItemKind::Fn(..)
726                     | ItemKind::Const(..)
727                     | ItemKind::Static(..)
728                     | ItemKind::Mod(..)
729                     | ItemKind::Enum(..)
730                     | ItemKind::Struct(..)
731                     | ItemKind::Union(..)
732                     | ItemKind::Trait(..)
733                     | ItemKind::Impl { .. },
734                 ..
735             })
736             | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(..), .. })
737             | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(..), .. })
738             | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(..), .. })
739             | Node::Block(_) = node
740             {
741                 return Some(hir_id);
742             }
743         }
744         None
745     }
746
747     /// Returns the defining scope for an opaque type definition.
748     pub fn get_defining_scope(&self, id: HirId) -> HirId {
749         let mut scope = id;
750         loop {
751             scope = self.get_enclosing_scope(scope).unwrap_or(CRATE_HIR_ID);
752             if scope == CRATE_HIR_ID || !matches!(self.get(scope), Node::Block(_)) {
753                 return scope;
754             }
755         }
756     }
757
758     pub fn get_parent_did(&self, id: HirId) -> LocalDefId {
759         self.local_def_id(self.get_parent_item(id))
760     }
761
762     pub fn get_foreign_abi(&self, hir_id: HirId) -> Abi {
763         let parent = self.get_parent_item(hir_id);
764         if let Some(node) = self.tcx.hir_owner(self.local_def_id(parent)) {
765             if let OwnerNode::Item(Item { kind: ItemKind::ForeignMod { abi, .. }, .. }) = node.node
766             {
767                 return *abi;
768             }
769         }
770         bug!("expected foreign mod or inlined parent, found {}", self.node_to_string(parent))
771     }
772
773     pub fn expect_item(&self, id: HirId) -> &'hir Item<'hir> {
774         match self.tcx.hir_owner(id.expect_owner()) {
775             Some(Owner { node: OwnerNode::Item(item) }) => item,
776             _ => bug!("expected item, found {}", self.node_to_string(id)),
777         }
778     }
779
780     pub fn expect_impl_item(&self, id: HirId) -> &'hir ImplItem<'hir> {
781         match self.tcx.hir_owner(id.expect_owner()) {
782             Some(Owner { node: OwnerNode::ImplItem(item) }) => item,
783             _ => bug!("expected impl item, found {}", self.node_to_string(id)),
784         }
785     }
786
787     pub fn expect_trait_item(&self, id: HirId) -> &'hir TraitItem<'hir> {
788         match self.tcx.hir_owner(id.expect_owner()) {
789             Some(Owner { node: OwnerNode::TraitItem(item) }) => item,
790             _ => bug!("expected trait item, found {}", self.node_to_string(id)),
791         }
792     }
793
794     pub fn expect_variant(&self, id: HirId) -> &'hir Variant<'hir> {
795         match self.find(id) {
796             Some(Node::Variant(variant)) => variant,
797             _ => bug!("expected variant, found {}", self.node_to_string(id)),
798         }
799     }
800
801     pub fn expect_foreign_item(&self, id: HirId) -> &'hir ForeignItem<'hir> {
802         match self.tcx.hir_owner(id.expect_owner()) {
803             Some(Owner { node: OwnerNode::ForeignItem(item) }) => item,
804             _ => bug!("expected foreign item, found {}", self.node_to_string(id)),
805         }
806     }
807
808     pub fn expect_expr(&self, id: HirId) -> &'hir Expr<'hir> {
809         match self.find(id) {
810             Some(Node::Expr(expr)) => expr,
811             _ => bug!("expected expr, found {}", self.node_to_string(id)),
812         }
813     }
814
815     pub fn opt_name(&self, id: HirId) -> Option<Symbol> {
816         Some(match self.get(id) {
817             Node::Item(i) => i.ident.name,
818             Node::ForeignItem(fi) => fi.ident.name,
819             Node::ImplItem(ii) => ii.ident.name,
820             Node::TraitItem(ti) => ti.ident.name,
821             Node::Variant(v) => v.ident.name,
822             Node::Field(f) => f.ident.name,
823             Node::Lifetime(lt) => lt.name.ident().name,
824             Node::GenericParam(param) => param.name.ident().name,
825             Node::Binding(&Pat { kind: PatKind::Binding(_, _, l, _), .. }) => l.name,
826             Node::Ctor(..) => self.name(self.get_parent_item(id)),
827             _ => return None,
828         })
829     }
830
831     pub fn name(&self, id: HirId) -> Symbol {
832         match self.opt_name(id) {
833             Some(name) => name,
834             None => bug!("no name for {}", self.node_to_string(id)),
835         }
836     }
837
838     /// Given a node ID, gets a list of attributes associated with the AST
839     /// corresponding to the node-ID.
840     pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] {
841         self.tcx.hir_attrs(id.owner).get(id.local_id)
842     }
843
844     /// Gets the span of the definition of the specified HIR node.
845     /// This is used by `tcx.get_span`
846     pub fn span(&self, hir_id: HirId) -> Span {
847         self.opt_span(hir_id)
848             .unwrap_or_else(|| bug!("hir::map::Map::span: id not in map: {:?}", hir_id))
849     }
850
851     pub fn opt_span(&self, hir_id: HirId) -> Option<Span> {
852         let span = match self.find(hir_id)? {
853             Node::Param(param) => param.span,
854             Node::Item(item) => match &item.kind {
855                 ItemKind::Fn(sig, _, _) => sig.span,
856                 _ => item.span,
857             },
858             Node::ForeignItem(foreign_item) => foreign_item.span,
859             Node::TraitItem(trait_item) => match &trait_item.kind {
860                 TraitItemKind::Fn(sig, _) => sig.span,
861                 _ => trait_item.span,
862             },
863             Node::ImplItem(impl_item) => match &impl_item.kind {
864                 ImplItemKind::Fn(sig, _) => sig.span,
865                 _ => impl_item.span,
866             },
867             Node::Variant(variant) => variant.span,
868             Node::Field(field) => field.span,
869             Node::AnonConst(constant) => self.body(constant.body).value.span,
870             Node::Expr(expr) => expr.span,
871             Node::Stmt(stmt) => stmt.span,
872             Node::PathSegment(seg) => seg.ident.span,
873             Node::Ty(ty) => ty.span,
874             Node::TraitRef(tr) => tr.path.span,
875             Node::Binding(pat) => pat.span,
876             Node::Pat(pat) => pat.span,
877             Node::Arm(arm) => arm.span,
878             Node::Block(block) => block.span,
879             Node::Ctor(..) => match self.find(self.get_parent_node(hir_id))? {
880                 Node::Item(item) => item.span,
881                 Node::Variant(variant) => variant.span,
882                 _ => unreachable!(),
883             },
884             Node::Lifetime(lifetime) => lifetime.span,
885             Node::GenericParam(param) => param.span,
886             Node::Visibility(&Spanned {
887                 node: VisibilityKind::Restricted { ref path, .. },
888                 ..
889             }) => path.span,
890             Node::Infer(i) => i.span,
891             Node::Visibility(v) => bug!("unexpected Visibility {:?}", v),
892             Node::Local(local) => local.span,
893             Node::Crate(item) => item.inner,
894         };
895         Some(span)
896     }
897
898     /// Like `hir.span()`, but includes the body of function items
899     /// (instead of just the function header)
900     pub fn span_with_body(&self, hir_id: HirId) -> Span {
901         match self.find(hir_id) {
902             Some(Node::TraitItem(item)) => item.span,
903             Some(Node::ImplItem(impl_item)) => impl_item.span,
904             Some(Node::Item(item)) => item.span,
905             Some(_) => self.span(hir_id),
906             _ => bug!("hir::map::Map::span_with_body: id not in map: {:?}", hir_id),
907         }
908     }
909
910     pub fn span_if_local(&self, id: DefId) -> Option<Span> {
911         id.as_local().and_then(|id| self.opt_span(self.local_def_id_to_hir_id(id)))
912     }
913
914     pub fn res_span(&self, res: Res) -> Option<Span> {
915         match res {
916             Res::Err => None,
917             Res::Local(id) => Some(self.span(id)),
918             res => self.span_if_local(res.opt_def_id()?),
919         }
920     }
921
922     /// Get a representation of this `id` for debugging purposes.
923     /// NOTE: Do NOT use this in diagnostics!
924     pub fn node_to_string(&self, id: HirId) -> String {
925         hir_id_to_string(self, id)
926     }
927
928     /// Returns the HirId of `N` in `struct Foo<const N: usize = { ... }>` when
929     /// called with the HirId for the `{ ... }` anon const
930     pub fn opt_const_param_default_param_hir_id(&self, anon_const: HirId) -> Option<HirId> {
931         match self.get(self.get_parent_node(anon_const)) {
932             Node::GenericParam(GenericParam {
933                 hir_id: param_id,
934                 kind: GenericParamKind::Const { .. },
935                 ..
936             }) => Some(*param_id),
937             _ => None,
938         }
939     }
940 }
941
942 impl<'hir> intravisit::Map<'hir> for Map<'hir> {
943     fn find(&self, hir_id: HirId) -> Option<Node<'hir>> {
944         self.find(hir_id)
945     }
946
947     fn body(&self, id: BodyId) -> &'hir Body<'hir> {
948         self.body(id)
949     }
950
951     fn item(&self, id: ItemId) -> &'hir Item<'hir> {
952         self.item(id)
953     }
954
955     fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
956         self.trait_item(id)
957     }
958
959     fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
960         self.impl_item(id)
961     }
962
963     fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
964         self.foreign_item(id)
965     }
966 }
967
968 pub(super) fn index_hir<'tcx>(tcx: TyCtxt<'tcx>, (): ()) -> &'tcx IndexedHir<'tcx> {
969     let _prof_timer = tcx.sess.prof.generic_activity("build_hir_map");
970
971     // We can access untracked state since we are an eval_always query.
972     let hcx = tcx.create_stable_hashing_context();
973     let mut collector = NodeCollector::root(
974         tcx.sess,
975         &**tcx.arena,
976         tcx.untracked_crate,
977         &tcx.untracked_resolutions.definitions,
978         hcx,
979     );
980     let top_mod = tcx.untracked_crate.module();
981     collector.visit_mod(top_mod, top_mod.inner, CRATE_HIR_ID);
982
983     let map = collector.finalize_and_compute_crate_hash();
984     tcx.arena.alloc(map)
985 }
986
987 pub(super) fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh {
988     assert_eq!(crate_num, LOCAL_CRATE);
989
990     // We can access untracked state since we are an eval_always query.
991     let mut hcx = tcx.create_stable_hashing_context();
992
993     let mut hir_body_nodes: Vec<_> = tcx
994         .index_hir(())
995         .map
996         .iter_enumerated()
997         .filter_map(|(def_id, hod)| {
998             let def_path_hash = tcx.untracked_resolutions.definitions.def_path_hash(def_id);
999             let hash = hod.as_ref()?.hash;
1000             Some((def_path_hash, hash, def_id))
1001         })
1002         .collect();
1003     hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
1004
1005     let upstream_crates = upstream_crates(tcx);
1006
1007     // We hash the final, remapped names of all local source files so we
1008     // don't have to include the path prefix remapping commandline args.
1009     // If we included the full mapping in the SVH, we could only have
1010     // reproducible builds by compiling from the same directory. So we just
1011     // hash the result of the mapping instead of the mapping itself.
1012     let mut source_file_names: Vec<_> = tcx
1013         .sess
1014         .source_map()
1015         .files()
1016         .iter()
1017         .filter(|source_file| source_file.cnum == LOCAL_CRATE)
1018         .map(|source_file| source_file.name_hash)
1019         .collect();
1020
1021     source_file_names.sort_unstable();
1022
1023     let mut stable_hasher = StableHasher::new();
1024     for (def_path_hash, fingerprint, def_id) in hir_body_nodes.iter() {
1025         def_path_hash.0.hash_stable(&mut hcx, &mut stable_hasher);
1026         fingerprint.hash_stable(&mut hcx, &mut stable_hasher);
1027         AttributeMap { map: &tcx.untracked_crate.attrs, prefix: *def_id }
1028             .hash_stable(&mut hcx, &mut stable_hasher);
1029         if tcx.sess.opts.debugging_opts.incremental_relative_spans {
1030             let span = tcx.untracked_resolutions.definitions.def_span(*def_id);
1031             debug_assert_eq!(span.parent(), None);
1032             span.hash_stable(&mut hcx, &mut stable_hasher);
1033         }
1034     }
1035     upstream_crates.hash_stable(&mut hcx, &mut stable_hasher);
1036     source_file_names.hash_stable(&mut hcx, &mut stable_hasher);
1037     tcx.sess.opts.dep_tracking_hash(true).hash_stable(&mut hcx, &mut stable_hasher);
1038     tcx.sess.local_stable_crate_id().hash_stable(&mut hcx, &mut stable_hasher);
1039
1040     let crate_hash: Fingerprint = stable_hasher.finish();
1041     Svh::new(crate_hash.to_smaller_hash())
1042 }
1043
1044 fn upstream_crates(tcx: TyCtxt<'_>) -> Vec<(StableCrateId, Svh)> {
1045     let mut upstream_crates: Vec<_> = tcx
1046         .crates(())
1047         .iter()
1048         .map(|&cnum| {
1049             let stable_crate_id = tcx.resolutions(()).cstore.stable_crate_id(cnum);
1050             let hash = tcx.crate_hash(cnum);
1051             (stable_crate_id, hash)
1052         })
1053         .collect();
1054     upstream_crates.sort_unstable_by_key(|&(stable_crate_id, _)| stable_crate_id);
1055     upstream_crates
1056 }
1057
1058 fn hir_id_to_string(map: &Map<'_>, id: HirId) -> String {
1059     let id_str = format!(" (hir_id={})", id);
1060
1061     let path_str = || {
1062         // This functionality is used for debugging, try to use `TyCtxt` to get
1063         // the user-friendly path, otherwise fall back to stringifying `DefPath`.
1064         crate::ty::tls::with_opt(|tcx| {
1065             if let Some(tcx) = tcx {
1066                 let def_id = map.local_def_id(id);
1067                 tcx.def_path_str(def_id.to_def_id())
1068             } else if let Some(path) = map.def_path_from_hir_id(id) {
1069                 path.data.into_iter().map(|elem| elem.to_string()).collect::<Vec<_>>().join("::")
1070             } else {
1071                 String::from("<missing path>")
1072             }
1073         })
1074     };
1075
1076     let span_str = || map.tcx.sess.source_map().span_to_snippet(map.span(id)).unwrap_or_default();
1077     let node_str = |prefix| format!("{} {}{}", prefix, span_str(), id_str);
1078
1079     match map.find(id) {
1080         Some(Node::Item(item)) => {
1081             let item_str = match item.kind {
1082                 ItemKind::ExternCrate(..) => "extern crate",
1083                 ItemKind::Use(..) => "use",
1084                 ItemKind::Static(..) => "static",
1085                 ItemKind::Const(..) => "const",
1086                 ItemKind::Fn(..) => "fn",
1087                 ItemKind::Macro(..) => "macro",
1088                 ItemKind::Mod(..) => "mod",
1089                 ItemKind::ForeignMod { .. } => "foreign mod",
1090                 ItemKind::GlobalAsm(..) => "global asm",
1091                 ItemKind::TyAlias(..) => "ty",
1092                 ItemKind::OpaqueTy(..) => "opaque type",
1093                 ItemKind::Enum(..) => "enum",
1094                 ItemKind::Struct(..) => "struct",
1095                 ItemKind::Union(..) => "union",
1096                 ItemKind::Trait(..) => "trait",
1097                 ItemKind::TraitAlias(..) => "trait alias",
1098                 ItemKind::Impl { .. } => "impl",
1099             };
1100             format!("{} {}{}", item_str, path_str(), id_str)
1101         }
1102         Some(Node::ForeignItem(_)) => format!("foreign item {}{}", path_str(), id_str),
1103         Some(Node::ImplItem(ii)) => match ii.kind {
1104             ImplItemKind::Const(..) => {
1105                 format!("assoc const {} in {}{}", ii.ident, path_str(), id_str)
1106             }
1107             ImplItemKind::Fn(..) => format!("method {} in {}{}", ii.ident, path_str(), id_str),
1108             ImplItemKind::TyAlias(_) => {
1109                 format!("assoc type {} in {}{}", ii.ident, path_str(), id_str)
1110             }
1111         },
1112         Some(Node::TraitItem(ti)) => {
1113             let kind = match ti.kind {
1114                 TraitItemKind::Const(..) => "assoc constant",
1115                 TraitItemKind::Fn(..) => "trait method",
1116                 TraitItemKind::Type(..) => "assoc type",
1117             };
1118
1119             format!("{} {} in {}{}", kind, ti.ident, path_str(), id_str)
1120         }
1121         Some(Node::Variant(ref variant)) => {
1122             format!("variant {} in {}{}", variant.ident, path_str(), id_str)
1123         }
1124         Some(Node::Field(ref field)) => {
1125             format!("field {} in {}{}", field.ident, path_str(), id_str)
1126         }
1127         Some(Node::AnonConst(_)) => node_str("const"),
1128         Some(Node::Expr(_)) => node_str("expr"),
1129         Some(Node::Stmt(_)) => node_str("stmt"),
1130         Some(Node::PathSegment(_)) => node_str("path segment"),
1131         Some(Node::Ty(_)) => node_str("type"),
1132         Some(Node::TraitRef(_)) => node_str("trait ref"),
1133         Some(Node::Binding(_)) => node_str("local"),
1134         Some(Node::Pat(_)) => node_str("pat"),
1135         Some(Node::Param(_)) => node_str("param"),
1136         Some(Node::Arm(_)) => node_str("arm"),
1137         Some(Node::Block(_)) => node_str("block"),
1138         Some(Node::Infer(_)) => node_str("infer"),
1139         Some(Node::Local(_)) => node_str("local"),
1140         Some(Node::Ctor(..)) => format!("ctor {}{}", path_str(), id_str),
1141         Some(Node::Lifetime(_)) => node_str("lifetime"),
1142         Some(Node::GenericParam(ref param)) => format!("generic_param {:?}{}", param, id_str),
1143         Some(Node::Visibility(ref vis)) => format!("visibility {:?}{}", vis, id_str),
1144         Some(Node::Crate(..)) => String::from("root_crate"),
1145         None => format!("unknown node{}", id_str),
1146     }
1147 }
1148
1149 pub(super) fn hir_module_items(tcx: TyCtxt<'_>, module_id: LocalDefId) -> ModuleItems {
1150     let mut collector = ModuleCollector {
1151         tcx,
1152         submodules: BTreeSet::default(),
1153         items: BTreeSet::default(),
1154         trait_items: BTreeSet::default(),
1155         impl_items: BTreeSet::default(),
1156         foreign_items: BTreeSet::default(),
1157     };
1158
1159     let (hir_mod, span, hir_id) = tcx.hir().get_module(module_id);
1160     collector.visit_mod(hir_mod, span, hir_id);
1161
1162     let ModuleCollector { submodules, items, trait_items, impl_items, foreign_items, .. } =
1163         collector;
1164     return ModuleItems { submodules, items, trait_items, impl_items, foreign_items };
1165
1166     struct ModuleCollector<'tcx> {
1167         tcx: TyCtxt<'tcx>,
1168         submodules: BTreeSet<LocalDefId>,
1169         items: BTreeSet<ItemId>,
1170         trait_items: BTreeSet<TraitItemId>,
1171         impl_items: BTreeSet<ImplItemId>,
1172         foreign_items: BTreeSet<ForeignItemId>,
1173     }
1174
1175     impl<'hir> Visitor<'hir> for ModuleCollector<'hir> {
1176         type Map = Map<'hir>;
1177
1178         fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
1179             intravisit::NestedVisitorMap::All(self.tcx.hir())
1180         }
1181
1182         fn visit_item(&mut self, item: &'hir Item<'hir>) {
1183             self.items.insert(item.item_id());
1184             if let ItemKind::Mod(..) = item.kind {
1185                 // If this declares another module, do not recurse inside it.
1186                 self.submodules.insert(item.def_id);
1187             } else {
1188                 intravisit::walk_item(self, item)
1189             }
1190         }
1191
1192         fn visit_trait_item(&mut self, item: &'hir TraitItem<'hir>) {
1193             self.trait_items.insert(item.trait_item_id());
1194             intravisit::walk_trait_item(self, item)
1195         }
1196
1197         fn visit_impl_item(&mut self, item: &'hir ImplItem<'hir>) {
1198             self.impl_items.insert(item.impl_item_id());
1199             intravisit::walk_impl_item(self, item)
1200         }
1201
1202         fn visit_foreign_item(&mut self, item: &'hir ForeignItem<'hir>) {
1203             self.foreign_items.insert(item.foreign_item_id());
1204             intravisit::walk_foreign_item(self, item)
1205         }
1206     }
1207 }