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