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