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