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