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