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