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