1use rustc_abi::ExternAbi;
6use rustc_ast::visit::{VisitorResult, walk_list};
7use rustc_data_structures::fingerprint::Fingerprint;
8use rustc_data_structures::fx::FxIndexSet;
9use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
10use rustc_data_structures::svh::Svh;
11use rustc_data_structures::sync::{DynSend, DynSync, par_for_each_in, try_par_for_each_in};
12use rustc_hir::def::{DefKind, Res};
13use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId, LocalModDefId};
14use rustc_hir::definitions::{DefKey, DefPath, DefPathHash};
15use rustc_hir::intravisit::Visitor;
16use rustc_hir::*;
17use rustc_hir_pretty as pprust_hir;
18use rustc_span::def_id::StableCrateId;
19use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol, kw, with_metavar_spans};
20
21use crate::hir::{ModuleItems, nested_filter};
22use crate::middle::debugger_visualizer::DebuggerVisualizerFile;
23use crate::query::LocalCrate;
24use crate::ty::TyCtxt;
25
26struct ParentHirIterator<'tcx> {
29 current_id: HirId,
30 tcx: TyCtxt<'tcx>,
31 current_owner_nodes: Option<&'tcx OwnerNodes<'tcx>>,
34}
35
36impl<'tcx> ParentHirIterator<'tcx> {
37 fn new(tcx: TyCtxt<'tcx>, current_id: HirId) -> ParentHirIterator<'tcx> {
38 ParentHirIterator { current_id, tcx, current_owner_nodes: None }
39 }
40}
41
42impl<'tcx> Iterator for ParentHirIterator<'tcx> {
43 type Item = HirId;
44
45 fn next(&mut self) -> Option<Self::Item> {
46 if self.current_id == CRATE_HIR_ID {
47 return None;
48 }
49
50 let HirId { owner, local_id } = self.current_id;
51
52 let parent_id = if local_id == ItemLocalId::ZERO {
53 self.current_owner_nodes = None;
55 self.tcx.hir_owner_parent(owner)
56 } else {
57 let owner_nodes =
58 self.current_owner_nodes.get_or_insert_with(|| self.tcx.hir_owner_nodes(owner));
59 let parent_local_id = owner_nodes.nodes[local_id].parent;
60 if true {
match (&parent_local_id, &local_id) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};debug_assert_ne!(parent_local_id, local_id);
62 HirId { owner, local_id: parent_local_id }
63 };
64
65 if true {
match (&parent_id, &self.current_id) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};debug_assert_ne!(parent_id, self.current_id);
66
67 self.current_id = parent_id;
68 Some(parent_id)
69 }
70}
71
72pub struct ParentOwnerIterator<'tcx> {
75 current_id: HirId,
76 tcx: TyCtxt<'tcx>,
77}
78
79impl<'tcx> Iterator for ParentOwnerIterator<'tcx> {
80 type Item = (OwnerId, OwnerNode<'tcx>);
81
82 fn next(&mut self) -> Option<Self::Item> {
83 if self.current_id.local_id.index() != 0 {
84 self.current_id.local_id = ItemLocalId::ZERO;
85 let node = self.tcx.hir_owner_node(self.current_id.owner);
86 return Some((self.current_id.owner, node));
87 }
88 if self.current_id == CRATE_HIR_ID {
89 return None;
90 }
91
92 let parent_id = self.tcx.hir_def_key(self.current_id.owner.def_id).parent;
93 let parent_id = parent_id.map_or(CRATE_OWNER_ID, |local_def_index| {
94 let def_id = LocalDefId { local_def_index };
95 self.tcx.local_def_id_to_hir_id(def_id).owner
96 });
97 self.current_id = HirId::make_owner(parent_id.def_id);
98
99 let node = self.tcx.hir_owner_node(self.current_id.owner);
100 Some((self.current_id.owner, node))
101 }
102}
103
104impl<'tcx> TyCtxt<'tcx> {
105 #[inline]
106 fn expect_hir_owner_nodes(self, def_id: LocalDefId) -> &'tcx OwnerNodes<'tcx> {
107 self.opt_hir_owner_nodes(def_id)
108 .unwrap_or_else(|| crate::util::bug::span_bug_fmt(self.def_span(def_id),
format_args!("{0:?} is not an owner", def_id))span_bug!(self.def_span(def_id), "{def_id:?} is not an owner"))
109 }
110
111 #[inline]
112 pub fn hir_owner_nodes(self, owner_id: OwnerId) -> &'tcx OwnerNodes<'tcx> {
113 self.expect_hir_owner_nodes(owner_id.def_id)
114 }
115
116 #[inline]
117 fn opt_hir_owner_node(self, def_id: LocalDefId) -> Option<OwnerNode<'tcx>> {
118 self.opt_hir_owner_nodes(def_id).map(|nodes| nodes.node())
119 }
120
121 #[inline]
122 pub fn expect_hir_owner_node(self, def_id: LocalDefId) -> OwnerNode<'tcx> {
123 self.expect_hir_owner_nodes(def_id).node()
124 }
125
126 #[inline]
127 pub fn hir_owner_node(self, owner_id: OwnerId) -> OwnerNode<'tcx> {
128 self.hir_owner_nodes(owner_id).node()
129 }
130
131 pub fn hir_node(self, id: HirId) -> Node<'tcx> {
133 self.hir_owner_nodes(id.owner).nodes[id.local_id].node
134 }
135
136 #[inline]
138 pub fn hir_node_by_def_id(self, id: LocalDefId) -> Node<'tcx> {
139 self.hir_node(self.local_def_id_to_hir_id(id))
140 }
141
142 pub fn parent_hir_id(self, hir_id: HirId) -> HirId {
147 let HirId { owner, local_id } = hir_id;
148 if local_id == ItemLocalId::ZERO {
149 self.hir_owner_parent(owner)
150 } else {
151 let parent_local_id = self.hir_owner_nodes(owner).nodes[local_id].parent;
152 if true {
match (&parent_local_id, &local_id) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};debug_assert_ne!(parent_local_id, local_id);
154 HirId { owner, local_id: parent_local_id }
155 }
156 }
157
158 pub fn parent_hir_node(self, hir_id: HirId) -> Node<'tcx> {
161 self.hir_node(self.parent_hir_id(hir_id))
162 }
163
164 #[inline]
165 pub fn hir_root_module(self) -> &'tcx Mod<'tcx> {
166 match self.hir_owner_node(CRATE_OWNER_ID) {
167 OwnerNode::Crate(item) => item,
168 _ => crate::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
169 }
170 }
171
172 #[inline]
173 pub fn hir_free_items(self) -> impl Iterator<Item = ItemId> {
174 self.hir_crate_items(()).free_items.iter().copied()
175 }
176
177 #[inline]
178 pub fn hir_module_free_items(self, module: LocalModDefId) -> impl Iterator<Item = ItemId> {
179 self.hir_module_items(module).free_items()
180 }
181
182 pub fn hir_def_key(self, def_id: LocalDefId) -> DefKey {
183 self.definitions_untracked().def_key(def_id)
185 }
186
187 pub fn hir_def_path(self, def_id: LocalDefId) -> DefPath {
188 self.definitions_untracked().def_path(def_id)
190 }
191
192 #[inline]
193 pub fn hir_def_path_hash(self, def_id: LocalDefId) -> DefPathHash {
194 self.definitions_untracked().def_path_hash(def_id)
196 }
197
198 pub fn hir_get_if_local(self, id: DefId) -> Option<Node<'tcx>> {
199 id.as_local().map(|id| self.hir_node_by_def_id(id))
200 }
201
202 pub fn hir_get_generics(self, id: LocalDefId) -> Option<&'tcx Generics<'tcx>> {
203 self.opt_hir_owner_node(id)?.generics()
204 }
205
206 pub fn hir_item(self, id: ItemId) -> &'tcx Item<'tcx> {
207 self.hir_owner_node(id.owner_id).expect_item()
208 }
209
210 pub fn hir_trait_item(self, id: TraitItemId) -> &'tcx TraitItem<'tcx> {
211 self.hir_owner_node(id.owner_id).expect_trait_item()
212 }
213
214 pub fn hir_impl_item(self, id: ImplItemId) -> &'tcx ImplItem<'tcx> {
215 self.hir_owner_node(id.owner_id).expect_impl_item()
216 }
217
218 pub fn hir_foreign_item(self, id: ForeignItemId) -> &'tcx ForeignItem<'tcx> {
219 self.hir_owner_node(id.owner_id).expect_foreign_item()
220 }
221
222 pub fn hir_body(self, id: BodyId) -> &'tcx Body<'tcx> {
223 self.hir_owner_nodes(id.hir_id.owner).bodies[&id.hir_id.local_id]
224 }
225
226 #[track_caller]
227 pub fn hir_fn_decl_by_hir_id(self, hir_id: HirId) -> Option<&'tcx FnDecl<'tcx>> {
228 self.hir_node(hir_id).fn_decl()
229 }
230
231 #[track_caller]
232 pub fn hir_fn_sig_by_hir_id(self, hir_id: HirId) -> Option<&'tcx FnSig<'tcx>> {
233 self.hir_node(hir_id).fn_sig()
234 }
235
236 #[track_caller]
237 pub fn hir_enclosing_body_owner(self, hir_id: HirId) -> LocalDefId {
238 for (_, node) in self.hir_parent_iter(hir_id) {
239 if let Some((def_id, _)) = node.associated_body() {
240 return def_id;
241 }
242 }
243
244 crate::util::bug::bug_fmt(format_args!("no `hir_enclosing_body_owner` for hir_id `{0}`",
hir_id));bug!("no `hir_enclosing_body_owner` for hir_id `{}`", hir_id);
245 }
246
247 pub fn hir_body_owner(self, BodyId { hir_id }: BodyId) -> HirId {
251 let parent = self.parent_hir_id(hir_id);
252 match (&self.hir_node(parent).body_id().unwrap().hir_id, &hir_id) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::Some(format_args!("{0:?}", hir_id)));
}
}
};assert_eq!(self.hir_node(parent).body_id().unwrap().hir_id, hir_id, "{hir_id:?}");
253 parent
254 }
255
256 pub fn hir_body_owner_def_id(self, BodyId { hir_id }: BodyId) -> LocalDefId {
257 self.parent_hir_node(hir_id).associated_body().unwrap().0
258 }
259
260 pub fn hir_maybe_body_owned_by(self, id: LocalDefId) -> Option<&'tcx Body<'tcx>> {
263 Some(self.hir_body(self.hir_node_by_def_id(id).body_id()?))
264 }
265
266 #[track_caller]
268 pub fn hir_body_owned_by(self, id: LocalDefId) -> &'tcx Body<'tcx> {
269 self.hir_maybe_body_owned_by(id).unwrap_or_else(|| {
270 let hir_id = self.local_def_id_to_hir_id(id);
271 crate::util::bug::span_bug_fmt(self.hir_span(hir_id),
format_args!("body_owned_by: {0} has no associated body",
self.hir_id_to_string(hir_id)));span_bug!(
272 self.hir_span(hir_id),
273 "body_owned_by: {} has no associated body",
274 self.hir_id_to_string(hir_id)
275 );
276 })
277 }
278
279 pub fn hir_body_param_idents(self, id: BodyId) -> impl Iterator<Item = Option<Ident>> {
280 self.hir_body(id).params.iter().map(|param| match param.pat.kind {
281 PatKind::Binding(_, _, ident, _) => Some(ident),
282 PatKind::Wild => Some(Ident::new(kw::Underscore, param.pat.span)),
283 _ => None,
284 })
285 }
286
287 pub fn hir_body_owner_kind(self, def_id: impl Into<DefId>) -> BodyOwnerKind {
291 let def_id = def_id.into();
292 match self.def_kind(def_id) {
293 DefKind::Const { .. } | DefKind::AssocConst { .. } | DefKind::AnonConst => {
294 BodyOwnerKind::Const { inline: false }
295 }
296 DefKind::InlineConst => BodyOwnerKind::Const { inline: true },
297 DefKind::Ctor(..) | DefKind::Fn | DefKind::AssocFn => BodyOwnerKind::Fn,
298 DefKind::Closure | DefKind::SyntheticCoroutineBody => BodyOwnerKind::Closure,
299 DefKind::Static { safety: _, mutability, nested: false } => {
300 BodyOwnerKind::Static(mutability)
301 }
302 DefKind::GlobalAsm => BodyOwnerKind::GlobalAsm,
303 dk => crate::util::bug::bug_fmt(format_args!("{0:?} is not a body node: {1:?}",
def_id, dk))bug!("{:?} is not a body node: {:?}", def_id, dk),
304 }
305 }
306
307 pub fn hir_body_const_context(self, local_def_id: LocalDefId) -> Option<ConstContext> {
315 let def_id = local_def_id.into();
316 let ccx = match self.hir_body_owner_kind(def_id) {
317 BodyOwnerKind::Const { inline } => ConstContext::Const { inline },
318 BodyOwnerKind::Static(mutability) => ConstContext::Static(mutability),
319
320 BodyOwnerKind::Fn if self.is_constructor(def_id) => return None,
321 BodyOwnerKind::Closure if self.is_const_fn(def_id) => {
323 return self.hir_body_const_context(self.local_parent(local_def_id));
324 }
325 BodyOwnerKind::Fn if self.is_const_fn(def_id) => ConstContext::ConstFn,
326 BodyOwnerKind::Fn | BodyOwnerKind::Closure | BodyOwnerKind::GlobalAsm => return None,
327 };
328
329 Some(ccx)
330 }
331
332 #[inline]
335 pub fn hir_body_owners(self) -> impl Iterator<Item = LocalDefId> {
336 self.hir_crate_items(()).body_owners.iter().copied()
337 }
338
339 #[inline]
340 pub fn par_hir_body_owners(self, f: impl Fn(LocalDefId) + DynSend + DynSync) {
341 par_for_each_in(&self.hir_crate_items(()).body_owners[..], |&&def_id| f(def_id));
342 }
343
344 pub fn hir_ty_param_owner(self, def_id: LocalDefId) -> LocalDefId {
345 let def_kind = self.def_kind(def_id);
346 match def_kind {
347 DefKind::Trait | DefKind::TraitAlias => def_id,
348 DefKind::LifetimeParam | DefKind::TyParam | DefKind::ConstParam => {
349 self.local_parent(def_id)
350 }
351 _ => crate::util::bug::bug_fmt(format_args!("ty_param_owner: {0:?} is a {1:?} not a type parameter",
def_id, def_kind))bug!("ty_param_owner: {:?} is a {:?} not a type parameter", def_id, def_kind),
352 }
353 }
354
355 pub fn hir_ty_param_name(self, def_id: LocalDefId) -> Symbol {
356 let def_kind = self.def_kind(def_id);
357 match def_kind {
358 DefKind::Trait | DefKind::TraitAlias => kw::SelfUpper,
359 DefKind::LifetimeParam | DefKind::TyParam | DefKind::ConstParam => {
360 self.item_name(def_id.to_def_id())
361 }
362 _ => crate::util::bug::bug_fmt(format_args!("ty_param_name: {0:?} is a {1:?} not a type parameter",
def_id, def_kind))bug!("ty_param_name: {:?} is a {:?} not a type parameter", def_id, def_kind),
363 }
364 }
365
366 pub fn hir_krate_attrs(self) -> &'tcx [Attribute] {
370 self.hir_attrs(CRATE_HIR_ID)
371 }
372
373 pub fn hir_rustc_coherence_is_core(self) -> bool {
374 {
{
'done:
{
for i in self.hir_krate_attrs() {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcCoherenceIsCore(..)) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
}find_attr!(self.hir_krate_attrs(), RustcCoherenceIsCore(..))
375 }
376
377 pub fn hir_get_module(self, module: LocalModDefId) -> (&'tcx Mod<'tcx>, Span, HirId) {
378 let hir_id = HirId::make_owner(module.to_local_def_id());
379 match self.hir_owner_node(hir_id.owner) {
380 OwnerNode::Item(&Item { span, kind: ItemKind::Mod(_, m), .. }) => (m, span, hir_id),
381 OwnerNode::Crate(item) => (item, item.spans.inner_span, hir_id),
382 node => { ::core::panicking::panic_fmt(format_args!("not a module: {0:?}", node)); }panic!("not a module: {node:?}"),
383 }
384 }
385
386 pub fn hir_walk_toplevel_module<V>(self, visitor: &mut V) -> V::Result
388 where
389 V: Visitor<'tcx>,
390 {
391 let (top_mod, span, hir_id) = self.hir_get_module(LocalModDefId::CRATE_DEF_ID);
392 visitor.visit_mod(top_mod, span, hir_id)
393 }
394
395 pub fn hir_walk_attributes<V>(self, visitor: &mut V) -> V::Result
397 where
398 V: Visitor<'tcx>,
399 {
400 let krate = self.hir_crate_items(());
401 for owner in krate.owners() {
402 let attrs = self.hir_attr_map(owner);
403 for attrs in attrs.map.values() {
404 for elem in *attrs {
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_attribute(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
};walk_list!(visitor, visit_attribute, *attrs);
405 }
406 }
407 V::Result::output()
408 }
409
410 pub fn hir_visit_all_item_likes_in_crate<V>(self, visitor: &mut V) -> V::Result
421 where
422 V: Visitor<'tcx>,
423 {
424 let krate = self.hir_crate_items(());
425 for elem in krate.free_items().map(|id| self.hir_item(id)) {
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_item(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
};walk_list!(visitor, visit_item, krate.free_items().map(|id| self.hir_item(id)));
426 for elem in krate.trait_items().map(|id| self.hir_trait_item(id)) {
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_trait_item(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
};walk_list!(
427 visitor,
428 visit_trait_item,
429 krate.trait_items().map(|id| self.hir_trait_item(id))
430 );
431 for elem in krate.impl_items().map(|id| self.hir_impl_item(id)) {
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_impl_item(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
};walk_list!(visitor, visit_impl_item, krate.impl_items().map(|id| self.hir_impl_item(id)));
432 for elem in krate.foreign_items().map(|id| self.hir_foreign_item(id)) {
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_foreign_item(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
};walk_list!(
433 visitor,
434 visit_foreign_item,
435 krate.foreign_items().map(|id| self.hir_foreign_item(id))
436 );
437 V::Result::output()
438 }
439
440 pub fn hir_visit_item_likes_in_module<V>(
443 self,
444 module: LocalModDefId,
445 visitor: &mut V,
446 ) -> V::Result
447 where
448 V: Visitor<'tcx>,
449 {
450 let module = self.hir_module_items(module);
451 for elem in module.free_items().map(|id| self.hir_item(id)) {
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_item(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
};walk_list!(visitor, visit_item, module.free_items().map(|id| self.hir_item(id)));
452 for elem in module.trait_items().map(|id| self.hir_trait_item(id)) {
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_trait_item(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
};walk_list!(
453 visitor,
454 visit_trait_item,
455 module.trait_items().map(|id| self.hir_trait_item(id))
456 );
457 for elem in module.impl_items().map(|id| self.hir_impl_item(id)) {
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_impl_item(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
};walk_list!(visitor, visit_impl_item, module.impl_items().map(|id| self.hir_impl_item(id)));
458 for elem in module.foreign_items().map(|id| self.hir_foreign_item(id)) {
match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_foreign_item(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
};walk_list!(
459 visitor,
460 visit_foreign_item,
461 module.foreign_items().map(|id| self.hir_foreign_item(id))
462 );
463 V::Result::output()
464 }
465
466 pub fn hir_for_each_module(self, mut f: impl FnMut(LocalModDefId)) {
467 let crate_items = self.hir_crate_items(());
468 for module in crate_items.submodules.iter() {
469 f(LocalModDefId::new_unchecked(module.def_id))
470 }
471 }
472
473 #[inline]
474 pub fn par_hir_for_each_module(self, f: impl Fn(LocalModDefId) + DynSend + DynSync) {
475 let crate_items = self.hir_crate_items(());
476 par_for_each_in(&crate_items.submodules[..], |module| {
477 f(LocalModDefId::new_unchecked(module.def_id))
478 })
479 }
480
481 #[inline]
482 pub fn try_par_hir_for_each_module(
483 self,
484 f: impl Fn(LocalModDefId) -> Result<(), ErrorGuaranteed> + DynSend + DynSync,
485 ) -> Result<(), ErrorGuaranteed> {
486 let crate_items = self.hir_crate_items(());
487 try_par_for_each_in(&crate_items.submodules[..], |module| {
488 f(LocalModDefId::new_unchecked(module.def_id))
489 })
490 }
491
492 #[inline]
495 pub fn hir_parent_id_iter(self, current_id: HirId) -> impl Iterator<Item = HirId> {
496 ParentHirIterator::new(self, current_id)
497 }
498
499 #[inline]
502 pub fn hir_parent_iter(self, current_id: HirId) -> impl Iterator<Item = (HirId, Node<'tcx>)> {
503 self.hir_parent_id_iter(current_id).map(move |id| (id, self.hir_node(id)))
504 }
505
506 #[inline]
509 pub fn hir_parent_owner_iter(self, current_id: HirId) -> ParentOwnerIterator<'tcx> {
510 ParentOwnerIterator { current_id, tcx: self }
511 }
512
513 pub fn hir_is_lhs(self, id: HirId) -> bool {
515 match self.parent_hir_node(id) {
516 Node::Expr(expr) => match expr.kind {
517 ExprKind::Assign(lhs, _rhs, _span) => lhs.hir_id == id,
518 _ => false,
519 },
520 _ => false,
521 }
522 }
523
524 pub fn hir_is_inside_const_context(self, hir_id: HirId) -> bool {
527 self.hir_body_const_context(self.hir_enclosing_body_owner(hir_id)).is_some()
528 }
529
530 pub fn hir_get_fn_id_for_return_block(self, id: HirId) -> Option<HirId> {
557 let enclosing_body_owner = self.local_def_id_to_hir_id(self.hir_enclosing_body_owner(id));
558
559 let mut iter = [id].into_iter().chain(self.hir_parent_id_iter(id)).peekable();
561 while let Some(cur_id) = iter.next() {
562 if enclosing_body_owner == cur_id {
563 break;
564 }
565
566 if let Node::Expr(Expr { kind: ExprKind::Ret(_), .. }) = self.hir_node(cur_id) {
569 break;
570 }
571
572 if let Some(&parent_id) = iter.peek() {
575 match self.hir_node(parent_id) {
576 Node::Block(Block { expr: Some(e), .. }) if cur_id != e.hir_id => return None,
579 Node::Block(Block { expr: Some(e), .. })
580 if #[allow(non_exhaustive_omitted_patterns)] match e.kind {
ExprKind::If(_, _, None) => true,
_ => false,
}matches!(e.kind, ExprKind::If(_, _, None)) =>
581 {
582 return None;
583 }
584
585 Node::Block(Block { expr: None, .. })
588 | Node::Expr(Expr { kind: ExprKind::Loop(..), .. })
589 | Node::LetStmt(..) => return None,
590
591 _ => {}
592 }
593 }
594 }
595
596 Some(enclosing_body_owner)
597 }
598
599 pub fn hir_get_parent_item(self, hir_id: HirId) -> OwnerId {
604 if hir_id.local_id != ItemLocalId::ZERO {
605 hir_id.owner
607 } else if let Some((def_id, _node)) = self.hir_parent_owner_iter(hir_id).next() {
608 def_id
609 } else {
610 CRATE_OWNER_ID
611 }
612 }
613
614 pub fn hir_get_if_cause(self, hir_id: HirId) -> Option<&'tcx Expr<'tcx>> {
620 for (_, node) in self.hir_parent_iter(hir_id) {
621 match node {
622 Node::Item(_)
623 | Node::ForeignItem(_)
624 | Node::TraitItem(_)
625 | Node::ImplItem(_)
626 | Node::Stmt(Stmt { kind: StmtKind::Let(_), .. }) => break,
627 Node::Expr(expr @ Expr { kind: ExprKind::If(..) | ExprKind::Match(..), .. }) => {
628 return Some(expr);
629 }
630 _ => {}
631 }
632 }
633 None
634 }
635
636 pub fn hir_get_enclosing_scope(self, hir_id: HirId) -> Option<HirId> {
638 for (hir_id, node) in self.hir_parent_iter(hir_id) {
639 if let Node::Item(Item {
640 kind:
641 ItemKind::Fn { .. }
642 | ItemKind::Const(..)
643 | ItemKind::Static(..)
644 | ItemKind::Mod(..)
645 | ItemKind::Enum(..)
646 | ItemKind::Struct(..)
647 | ItemKind::Union(..)
648 | ItemKind::Trait(..)
649 | ItemKind::Impl { .. },
650 ..
651 })
652 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(..), .. })
653 | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(..), .. })
654 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(..), .. })
655 | Node::Block(_) = node
656 {
657 return Some(hir_id);
658 }
659 }
660 None
661 }
662
663 pub fn hir_get_defining_scope(self, id: HirId) -> HirId {
665 let mut scope = id;
666 loop {
667 scope = self.hir_get_enclosing_scope(scope).unwrap_or(CRATE_HIR_ID);
668 if scope == CRATE_HIR_ID || !#[allow(non_exhaustive_omitted_patterns)] match self.hir_node(scope) {
Node::Block(_) => true,
_ => false,
}matches!(self.hir_node(scope), Node::Block(_)) {
669 return scope;
670 }
671 }
672 }
673
674 pub fn hir_id_to_string(self, id: HirId) -> String {
677 let path_str = |def_id: LocalDefId| self.def_path_str(def_id);
678
679 let span_str =
680 || self.sess.source_map().span_to_snippet(self.hir_span(id)).unwrap_or_default();
681 let node_str = |prefix| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1} ({2} `{0}`)", span_str(), id,
prefix))
})format!("{id} ({prefix} `{}`)", span_str());
682
683 match self.hir_node(id) {
684 Node::Item(item) => {
685 let item_str = match item.kind {
686 ItemKind::ExternCrate(..) => "extern crate",
687 ItemKind::Use(..) => "use",
688 ItemKind::Static(..) => "static",
689 ItemKind::Const(..) => "const",
690 ItemKind::Fn { .. } => "fn",
691 ItemKind::Macro(..) => "macro",
692 ItemKind::Mod(..) => "mod",
693 ItemKind::ForeignMod { .. } => "foreign mod",
694 ItemKind::GlobalAsm { .. } => "global asm",
695 ItemKind::TyAlias(..) => "ty",
696 ItemKind::Enum(..) => "enum",
697 ItemKind::Struct(..) => "struct",
698 ItemKind::Union(..) => "union",
699 ItemKind::Trait(..) => "trait",
700 ItemKind::TraitAlias(..) => "trait alias",
701 ItemKind::Impl { .. } => "impl",
702 };
703 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1} ({2} {0})",
path_str(item.owner_id.def_id), id, item_str))
})format!("{id} ({item_str} {})", path_str(item.owner_id.def_id))
704 }
705 Node::ForeignItem(item) => {
706 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1} (foreign item {0})",
path_str(item.owner_id.def_id), id))
})format!("{id} (foreign item {})", path_str(item.owner_id.def_id))
707 }
708 Node::ImplItem(ii) => {
709 let kind = match ii.kind {
710 ImplItemKind::Const(..) => "associated constant",
711 ImplItemKind::Fn(fn_sig, _) => match fn_sig.decl.implicit_self {
712 ImplicitSelfKind::None => "associated function",
713 _ => "method",
714 },
715 ImplItemKind::Type(_) => "associated type",
716 };
717 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{2} ({3} `{0}` in {1})", ii.ident,
path_str(ii.owner_id.def_id), id, kind))
})format!("{id} ({kind} `{}` in {})", ii.ident, path_str(ii.owner_id.def_id))
718 }
719 Node::TraitItem(ti) => {
720 let kind = match ti.kind {
721 TraitItemKind::Const(..) => "associated constant",
722 TraitItemKind::Fn(fn_sig, _) => match fn_sig.decl.implicit_self {
723 ImplicitSelfKind::None => "associated function",
724 _ => "trait method",
725 },
726 TraitItemKind::Type(..) => "associated type",
727 };
728
729 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{2} ({3} `{0}` in {1})", ti.ident,
path_str(ti.owner_id.def_id), id, kind))
})format!("{id} ({kind} `{}` in {})", ti.ident, path_str(ti.owner_id.def_id))
730 }
731 Node::Variant(variant) => {
732 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{2} (variant `{0}` in {1})",
variant.ident, path_str(variant.def_id), id))
})format!("{id} (variant `{}` in {})", variant.ident, path_str(variant.def_id))
733 }
734 Node::Field(field) => {
735 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{2} (field `{0}` in {1})",
field.ident, path_str(field.def_id), id))
})format!("{id} (field `{}` in {})", field.ident, path_str(field.def_id))
736 }
737 Node::AnonConst(_) => node_str("const"),
738 Node::ConstBlock(_) => node_str("const"),
739 Node::ConstArg(_) => node_str("const"),
740 Node::Expr(_) => node_str("expr"),
741 Node::ExprField(_) => node_str("expr field"),
742 Node::ConstArgExprField(_) => node_str("const arg expr field"),
743 Node::Stmt(_) => node_str("stmt"),
744 Node::PathSegment(_) => node_str("path segment"),
745 Node::Ty(_) => node_str("type"),
746 Node::AssocItemConstraint(_) => node_str("assoc item constraint"),
747 Node::TraitRef(_) => node_str("trait ref"),
748 Node::OpaqueTy(_) => node_str("opaque type"),
749 Node::Pat(_) => node_str("pat"),
750 Node::TyPat(_) => node_str("pat ty"),
751 Node::PatField(_) => node_str("pattern field"),
752 Node::PatExpr(_) => node_str("pattern literal"),
753 Node::Param(_) => node_str("param"),
754 Node::Arm(_) => node_str("arm"),
755 Node::Block(_) => node_str("block"),
756 Node::Infer(_) => node_str("infer"),
757 Node::LetStmt(_) => node_str("local"),
758 Node::Ctor(ctor) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1} (ctor {0})",
ctor.ctor_def_id().map_or("<missing path>".into(),
|def_id| path_str(def_id)), id))
})format!(
759 "{id} (ctor {})",
760 ctor.ctor_def_id().map_or("<missing path>".into(), |def_id| path_str(def_id)),
761 ),
762 Node::Lifetime(_) => node_str("lifetime"),
763 Node::GenericParam(param) => {
764 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1} (generic_param {0})",
path_str(param.def_id), id))
})format!("{id} (generic_param {})", path_str(param.def_id))
765 }
766 Node::Crate(..) => String::from("(root_crate)"),
767 Node::WherePredicate(_) => node_str("where predicate"),
768 Node::Synthetic => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
769 Node::Err(_) => node_str("error"),
770 Node::PreciseCapturingNonLifetimeArg(_param) => node_str("parameter"),
771 }
772 }
773
774 pub fn hir_get_foreign_abi(self, hir_id: HirId) -> ExternAbi {
775 let parent = self.hir_get_parent_item(hir_id);
776 if let OwnerNode::Item(Item { kind: ItemKind::ForeignMod { abi, .. }, .. }) =
777 self.hir_owner_node(parent)
778 {
779 return *abi;
780 }
781 crate::util::bug::bug_fmt(format_args!("expected foreign mod or inlined parent, found {0}",
self.hir_id_to_string(HirId::make_owner(parent.def_id))))bug!(
782 "expected foreign mod or inlined parent, found {}",
783 self.hir_id_to_string(HirId::make_owner(parent.def_id))
784 )
785 }
786
787 pub fn hir_expect_item(self, id: LocalDefId) -> &'tcx Item<'tcx> {
788 match self.expect_hir_owner_node(id) {
789 OwnerNode::Item(item) => item,
790 _ => crate::util::bug::bug_fmt(format_args!("expected item, found {0}",
self.hir_id_to_string(HirId::make_owner(id))))bug!("expected item, found {}", self.hir_id_to_string(HirId::make_owner(id))),
791 }
792 }
793
794 pub fn hir_expect_impl_item(self, id: LocalDefId) -> &'tcx ImplItem<'tcx> {
795 match self.expect_hir_owner_node(id) {
796 OwnerNode::ImplItem(item) => item,
797 _ => crate::util::bug::bug_fmt(format_args!("expected impl item, found {0}",
self.hir_id_to_string(HirId::make_owner(id))))bug!("expected impl item, found {}", self.hir_id_to_string(HirId::make_owner(id))),
798 }
799 }
800
801 pub fn hir_expect_trait_item(self, id: LocalDefId) -> &'tcx TraitItem<'tcx> {
802 match self.expect_hir_owner_node(id) {
803 OwnerNode::TraitItem(item) => item,
804 _ => {
805 crate::util::bug::bug_fmt(format_args!("expected trait item, found {0}",
self.hir_id_to_string(HirId::make_owner(id))))bug!("expected trait item, found {}", self.hir_id_to_string(HirId::make_owner(id)))
806 }
807 }
808 }
809
810 pub fn hir_get_fn_output(self, def_id: LocalDefId) -> Option<&'tcx FnRetTy<'tcx>> {
811 Some(&self.opt_hir_owner_node(def_id)?.fn_decl()?.output)
812 }
813
814 #[track_caller]
815 pub fn hir_expect_opaque_ty(self, id: LocalDefId) -> &'tcx OpaqueTy<'tcx> {
816 match self.hir_node_by_def_id(id) {
817 Node::OpaqueTy(opaq) => opaq,
818 _ => {
819 crate::util::bug::bug_fmt(format_args!("expected opaque type definition, found {0}",
self.hir_id_to_string(self.local_def_id_to_hir_id(id))))bug!(
820 "expected opaque type definition, found {}",
821 self.hir_id_to_string(self.local_def_id_to_hir_id(id))
822 )
823 }
824 }
825 }
826
827 pub fn hir_expect_expr(self, id: HirId) -> &'tcx Expr<'tcx> {
828 match self.hir_node(id) {
829 Node::Expr(expr) => expr,
830 _ => crate::util::bug::bug_fmt(format_args!("expected expr, found {0}",
self.hir_id_to_string(id)))bug!("expected expr, found {}", self.hir_id_to_string(id)),
831 }
832 }
833
834 pub fn hir_opt_delegation_sig_id(self, def_id: LocalDefId) -> Option<DefId> {
835 self.opt_hir_owner_node(def_id)?.fn_decl()?.opt_delegation_sig_id()
836 }
837
838 #[inline]
839 fn hir_opt_ident(self, id: HirId) -> Option<Ident> {
840 match self.hir_node(id) {
841 Node::Pat(&Pat { kind: PatKind::Binding(_, _, ident, _), .. }) => Some(ident),
842 Node::Ctor(..) => match self.parent_hir_node(id) {
845 Node::Item(item) => Some(item.kind.ident().unwrap()),
846 Node::Variant(variant) => Some(variant.ident),
847 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
848 },
849 node => node.ident(),
850 }
851 }
852
853 #[inline]
854 pub(super) fn hir_opt_ident_span(self, id: HirId) -> Option<Span> {
855 self.hir_opt_ident(id).map(|ident| ident.span)
856 }
857
858 #[inline]
859 pub fn hir_ident(self, id: HirId) -> Ident {
860 self.hir_opt_ident(id).unwrap()
861 }
862
863 #[inline]
864 pub fn hir_opt_name(self, id: HirId) -> Option<Symbol> {
865 self.hir_opt_ident(id).map(|ident| ident.name)
866 }
867
868 pub fn hir_name(self, id: HirId) -> Symbol {
869 self.hir_opt_name(id).unwrap_or_else(|| crate::util::bug::bug_fmt(format_args!("no name for {0}",
self.hir_id_to_string(id)))bug!("no name for {}", self.hir_id_to_string(id)))
870 }
871
872 pub fn hir_attrs(self, id: HirId) -> &'tcx [Attribute] {
875 self.hir_attr_map(id.owner).get(id.local_id)
876 }
877
878 pub fn hir_span(self, hir_id: HirId) -> Span {
881 fn until_within(outer: Span, end: Span) -> Span {
882 if let Some(end) = end.find_ancestor_inside(outer) {
883 outer.with_hi(end.hi())
884 } else {
885 outer
886 }
887 }
888
889 fn named_span(item_span: Span, ident: Ident, generics: Option<&Generics<'_>>) -> Span {
890 let mut span = until_within(item_span, ident.span);
891 if let Some(g) = generics
892 && !g.span.is_dummy()
893 && let Some(g_span) = g.span.find_ancestor_inside(item_span)
894 {
895 span = span.to(g_span);
896 }
897 span
898 }
899
900 let span = match self.hir_node(hir_id) {
901 Node::Item(Item { kind: ItemKind::Fn { sig, .. }, span: outer_span, .. })
903 | Node::TraitItem(TraitItem {
904 kind: TraitItemKind::Fn(sig, ..),
905 span: outer_span,
906 ..
907 })
908 | Node::ImplItem(ImplItem {
909 kind: ImplItemKind::Fn(sig, ..), span: outer_span, ..
910 })
911 | Node::ForeignItem(ForeignItem {
912 kind: ForeignItemKind::Fn(sig, ..),
913 span: outer_span,
914 ..
915 }) => {
916 sig.span.find_ancestor_in_same_ctxt(*outer_span).unwrap_or(*outer_span)
919 }
920 Node::Item(Item {
922 kind: ItemKind::Impl(Impl { generics, .. }),
923 span: outer_span,
924 ..
925 }) => until_within(*outer_span, generics.where_clause_span),
926 Node::Item(Item {
928 kind: ItemKind::Const(_, _, ty, _) | ItemKind::Static(_, _, ty, _),
929 span: outer_span,
930 ..
931 })
932 | Node::TraitItem(TraitItem {
933 kind: TraitItemKind::Const(ty, ..),
934 span: outer_span,
935 ..
936 })
937 | Node::ImplItem(ImplItem {
938 kind: ImplItemKind::Const(ty, ..),
939 span: outer_span,
940 ..
941 })
942 | Node::ForeignItem(ForeignItem {
943 kind: ForeignItemKind::Static(ty, ..),
944 span: outer_span,
945 ..
946 }) => until_within(*outer_span, ty.span),
947 Node::Item(Item {
949 kind: ItemKind::Trait(_, _, _, _, generics, bounds, _),
950 span: outer_span,
951 ..
952 })
953 | Node::TraitItem(TraitItem {
954 kind: TraitItemKind::Type(bounds, _),
955 generics,
956 span: outer_span,
957 ..
958 }) => {
959 let end = if let Some(b) = bounds.last() { b.span() } else { generics.span };
960 until_within(*outer_span, end)
961 }
962 Node::Item(item) => match &item.kind {
964 ItemKind::Use(path, _) => {
965 path.span.find_ancestor_in_same_ctxt(item.span).unwrap_or(item.span)
968 }
969 _ => {
970 if let Some(ident) = item.kind.ident() {
971 named_span(item.span, ident, item.kind.generics())
972 } else {
973 item.span
974 }
975 }
976 },
977 Node::Variant(variant) => named_span(variant.span, variant.ident, None),
978 Node::ImplItem(item) => named_span(item.span, item.ident, Some(item.generics)),
979 Node::ForeignItem(item) => named_span(item.span, item.ident, None),
980 Node::Ctor(_) => return self.hir_span(self.parent_hir_id(hir_id)),
981 Node::Expr(Expr {
982 kind: ExprKind::Closure(Closure { fn_decl_span, .. }),
983 span,
984 ..
985 }) => {
986 fn_decl_span.find_ancestor_inside(*span).unwrap_or(*span)
988 }
989 _ => self.hir_span_with_body(hir_id),
990 };
991 if true {
match (&span.ctxt(), &self.hir_span_with_body(hir_id).ctxt()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};debug_assert_eq!(span.ctxt(), self.hir_span_with_body(hir_id).ctxt());
992 span
993 }
994
995 pub fn hir_span_with_body(self, hir_id: HirId) -> Span {
998 match self.hir_node(hir_id) {
999 Node::Param(param) => param.span,
1000 Node::Item(item) => item.span,
1001 Node::ForeignItem(foreign_item) => foreign_item.span,
1002 Node::TraitItem(trait_item) => trait_item.span,
1003 Node::ImplItem(impl_item) => impl_item.span,
1004 Node::Variant(variant) => variant.span,
1005 Node::Field(field) => field.span,
1006 Node::AnonConst(constant) => constant.span,
1007 Node::ConstBlock(constant) => self.hir_body(constant.body).value.span,
1008 Node::ConstArg(const_arg) => const_arg.span,
1009 Node::Expr(expr) => expr.span,
1010 Node::ExprField(field) => field.span,
1011 Node::ConstArgExprField(field) => field.span,
1012 Node::Stmt(stmt) => stmt.span,
1013 Node::PathSegment(seg) => {
1014 let ident_span = seg.ident.span;
1015 ident_span
1016 .with_hi(seg.args.map_or_else(|| ident_span.hi(), |args| args.span_ext.hi()))
1017 }
1018 Node::Ty(ty) => ty.span,
1019 Node::AssocItemConstraint(constraint) => constraint.span,
1020 Node::TraitRef(tr) => tr.path.span,
1021 Node::OpaqueTy(op) => op.span,
1022 Node::Pat(pat) => pat.span,
1023 Node::TyPat(pat) => pat.span,
1024 Node::PatField(field) => field.span,
1025 Node::PatExpr(lit) => lit.span,
1026 Node::Arm(arm) => arm.span,
1027 Node::Block(block) => block.span,
1028 Node::Ctor(..) => self.hir_span_with_body(self.parent_hir_id(hir_id)),
1029 Node::Lifetime(lifetime) => lifetime.ident.span,
1030 Node::GenericParam(param) => param.span,
1031 Node::Infer(i) => i.span,
1032 Node::LetStmt(local) => local.span,
1033 Node::Crate(item) => item.spans.inner_span,
1034 Node::WherePredicate(pred) => pred.span,
1035 Node::PreciseCapturingNonLifetimeArg(param) => param.ident.span,
1036 Node::Synthetic => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1037 Node::Err(span) => span,
1038 }
1039 }
1040
1041 pub fn hir_span_if_local(self, id: DefId) -> Option<Span> {
1042 id.is_local().then(|| self.def_span(id))
1043 }
1044
1045 pub fn hir_res_span(self, res: Res) -> Option<Span> {
1046 match res {
1047 Res::Err => None,
1048 Res::Local(id) => Some(self.hir_span(id)),
1049 res => self.hir_span_if_local(res.opt_def_id()?),
1050 }
1051 }
1052
1053 pub fn hir_opt_const_param_default_param_def_id(self, anon_const: HirId) -> Option<LocalDefId> {
1056 let const_arg = self.parent_hir_id(anon_const);
1057 match self.parent_hir_node(const_arg) {
1058 Node::GenericParam(GenericParam {
1059 def_id: param_id,
1060 kind: GenericParamKind::Const { .. },
1061 ..
1062 }) => Some(*param_id),
1063 _ => None,
1064 }
1065 }
1066
1067 pub fn hir_maybe_get_struct_pattern_shorthand_field(self, expr: &Expr<'_>) -> Option<Symbol> {
1068 let local = match expr {
1069 Expr {
1070 kind:
1071 ExprKind::Path(QPath::Resolved(
1072 None,
1073 Path {
1074 res: def::Res::Local(_), segments: [PathSegment { ident, .. }], ..
1075 },
1076 )),
1077 ..
1078 } => Some(ident),
1079 _ => None,
1080 }?;
1081
1082 match self.parent_hir_node(expr.hir_id) {
1083 Node::ExprField(field) => {
1084 if field.ident.name == local.name && field.is_shorthand {
1085 return Some(local.name);
1086 }
1087 }
1088 _ => {}
1089 }
1090
1091 None
1092 }
1093}
1094
1095impl<'tcx> intravisit::HirTyCtxt<'tcx> for TyCtxt<'tcx> {
1096 fn hir_node(&self, hir_id: HirId) -> Node<'tcx> {
1097 (*self).hir_node(hir_id)
1098 }
1099
1100 fn hir_body(&self, id: BodyId) -> &'tcx Body<'tcx> {
1101 (*self).hir_body(id)
1102 }
1103
1104 fn hir_item(&self, id: ItemId) -> &'tcx Item<'tcx> {
1105 (*self).hir_item(id)
1106 }
1107
1108 fn hir_trait_item(&self, id: TraitItemId) -> &'tcx TraitItem<'tcx> {
1109 (*self).hir_trait_item(id)
1110 }
1111
1112 fn hir_impl_item(&self, id: ImplItemId) -> &'tcx ImplItem<'tcx> {
1113 (*self).hir_impl_item(id)
1114 }
1115
1116 fn hir_foreign_item(&self, id: ForeignItemId) -> &'tcx ForeignItem<'tcx> {
1117 (*self).hir_foreign_item(id)
1118 }
1119}
1120
1121impl<'tcx> pprust_hir::PpAnn for TyCtxt<'tcx> {
1122 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
1123 pprust_hir::PpAnn::nested(&(self as &dyn intravisit::HirTyCtxt<'_>), state, nested)
1124 }
1125}
1126
1127pub(super) fn crate_hash(tcx: TyCtxt<'_>, _: LocalCrate) -> Svh {
1128 let krate = tcx.hir_crate(());
1129 let hir_body_hash = krate.opt_hir_hash.expect("HIR hash missing while computing crate hash");
1130
1131 let upstream_crates = upstream_crates(tcx);
1132
1133 let resolutions = tcx.resolutions(());
1134
1135 let mut source_file_names: Vec<_> = tcx
1141 .sess
1142 .source_map()
1143 .files()
1144 .iter()
1145 .filter(|source_file| source_file.cnum == LOCAL_CRATE)
1146 .map(|source_file| source_file.stable_id)
1147 .collect();
1148
1149 source_file_names.sort_unstable();
1150
1151 let debugger_visualizers: Vec<_> = tcx
1157 .debugger_visualizers(LOCAL_CRATE)
1158 .iter()
1159 .map(DebuggerVisualizerFile::path_erased)
1163 .collect();
1164
1165 let crate_hash: Fingerprint = tcx.with_stable_hashing_context(|mut hcx| {
1166 let mut stable_hasher = StableHasher::new();
1167 hir_body_hash.hash_stable(&mut hcx, &mut stable_hasher);
1168 upstream_crates.hash_stable(&mut hcx, &mut stable_hasher);
1169 source_file_names.hash_stable(&mut hcx, &mut stable_hasher);
1170 debugger_visualizers.hash_stable(&mut hcx, &mut stable_hasher);
1171 if tcx.sess.opts.incremental.is_some() {
1172 let definitions = tcx.untracked().definitions.freeze();
1173 let mut owner_spans: Vec<_> = tcx
1174 .hir_crate_items(())
1175 .definitions()
1176 .map(|def_id| {
1177 let def_path_hash = definitions.def_path_hash(def_id);
1178 let span = tcx.source_span(def_id);
1179 if true {
match (&span.parent(), &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};debug_assert_eq!(span.parent(), None);
1180 (def_path_hash, span)
1181 })
1182 .collect();
1183 owner_spans.sort_unstable_by_key(|bn| bn.0);
1184 owner_spans.hash_stable(&mut hcx, &mut stable_hasher);
1185 }
1186 tcx.sess.opts.dep_tracking_hash(true).hash_stable(&mut hcx, &mut stable_hasher);
1187 tcx.stable_crate_id(LOCAL_CRATE).hash_stable(&mut hcx, &mut stable_hasher);
1188 resolutions.visibilities_for_hashing.hash_stable(&mut hcx, &mut stable_hasher);
1193 with_metavar_spans(|mspans| {
1194 mspans.freeze_and_get_read_spans().hash_stable(&mut hcx, &mut stable_hasher);
1195 });
1196 stable_hasher.finish()
1197 });
1198
1199 Svh::new(crate_hash)
1200}
1201
1202fn upstream_crates(tcx: TyCtxt<'_>) -> Vec<(StableCrateId, Svh)> {
1203 let mut upstream_crates: Vec<_> = tcx
1204 .crates(())
1205 .iter()
1206 .map(|&cnum| {
1207 let stable_crate_id = tcx.stable_crate_id(cnum);
1208 let hash = tcx.crate_hash(cnum);
1209 (stable_crate_id, hash)
1210 })
1211 .collect();
1212 upstream_crates.sort_unstable_by_key(|&(stable_crate_id, _)| stable_crate_id);
1213 upstream_crates
1214}
1215
1216pub(super) fn hir_module_items(tcx: TyCtxt<'_>, module_id: LocalModDefId) -> ModuleItems {
1217 let mut collector = ItemCollector::new(tcx, false);
1218
1219 let (hir_mod, span, hir_id) = tcx.hir_get_module(module_id);
1220 collector.visit_mod(hir_mod, span, hir_id);
1221
1222 let ItemCollector {
1223 submodules,
1224 items,
1225 trait_items,
1226 impl_items,
1227 foreign_items,
1228 body_owners,
1229 opaques,
1230 nested_bodies,
1231 eiis,
1232 ..
1233 } = collector;
1234 ModuleItems {
1235 add_root: false,
1236 submodules: submodules.into_boxed_slice(),
1237 free_items: items.into_boxed_slice(),
1238 trait_items: trait_items.into_boxed_slice(),
1239 impl_items: impl_items.into_boxed_slice(),
1240 foreign_items: foreign_items.into_boxed_slice(),
1241 body_owners: body_owners.into_boxed_slice(),
1242 opaques: opaques.into_boxed_slice(),
1243 nested_bodies: nested_bodies.into_boxed_slice(),
1244 delayed_lint_items: Box::new([]),
1245 eiis: eiis.into_boxed_slice(),
1246 }
1247}
1248
1249pub(crate) fn hir_crate_items(tcx: TyCtxt<'_>, _: ()) -> ModuleItems {
1250 let mut collector = ItemCollector::new(tcx, true);
1251
1252 collector.submodules.push(CRATE_OWNER_ID);
1256 tcx.hir_walk_toplevel_module(&mut collector);
1257
1258 let ItemCollector {
1259 submodules,
1260 items,
1261 trait_items,
1262 impl_items,
1263 foreign_items,
1264 body_owners,
1265 opaques,
1266 nested_bodies,
1267 mut delayed_lint_items,
1268 eiis,
1269 ..
1270 } = collector;
1271
1272 delayed_lint_items.push(CRATE_OWNER_ID);
1279
1280 ModuleItems {
1281 add_root: true,
1282 submodules: submodules.into_boxed_slice(),
1283 free_items: items.into_boxed_slice(),
1284 trait_items: trait_items.into_boxed_slice(),
1285 impl_items: impl_items.into_boxed_slice(),
1286 foreign_items: foreign_items.into_boxed_slice(),
1287 body_owners: body_owners.into_boxed_slice(),
1288 opaques: opaques.into_boxed_slice(),
1289 nested_bodies: nested_bodies.into_boxed_slice(),
1290 delayed_lint_items: delayed_lint_items.into_boxed_slice(),
1291 eiis: eiis.into_boxed_slice(),
1292 }
1293}
1294
1295struct ItemCollector<'tcx> {
1296 crate_collector: bool,
1299 tcx: TyCtxt<'tcx>,
1300 submodules: Vec<OwnerId>,
1301 items: Vec<ItemId>,
1302 trait_items: Vec<TraitItemId>,
1303 impl_items: Vec<ImplItemId>,
1304 foreign_items: Vec<ForeignItemId>,
1305 body_owners: Vec<LocalDefId>,
1306 opaques: Vec<LocalDefId>,
1307 nested_bodies: Vec<LocalDefId>,
1308 delayed_lint_items: Vec<OwnerId>,
1309 eiis: Vec<LocalDefId>,
1310 delayed_ids: Option<&'tcx FxIndexSet<LocalDefId>>,
1311}
1312
1313impl<'tcx> ItemCollector<'tcx> {
1314 fn new(tcx: TyCtxt<'tcx>, crate_collector: bool) -> ItemCollector<'tcx> {
1315 let mut collector = ItemCollector {
1316 crate_collector,
1317 tcx,
1318 submodules: Vec::default(),
1319 items: Vec::default(),
1320 trait_items: Vec::default(),
1321 impl_items: Vec::default(),
1322 foreign_items: Vec::default(),
1323 body_owners: Vec::default(),
1324 opaques: Vec::default(),
1325 nested_bodies: Vec::default(),
1326 delayed_lint_items: Vec::default(),
1327 eiis: Vec::default(),
1328 delayed_ids: None,
1329 };
1330
1331 if crate_collector {
1332 let krate = tcx.hir_crate(());
1333 collector.delayed_ids = Some(&krate.delayed_ids);
1334
1335 let delayed_kinds =
1336 krate.delayed_ids.iter().copied().map(|id| (id, krate.owners[id].expect_delayed()));
1337
1338 for (def_id, kind) in delayed_kinds {
1340 let owner_id = OwnerId { def_id };
1341
1342 match kind {
1343 DelayedOwnerKind::Item => collector.items.push(ItemId { owner_id }),
1344 DelayedOwnerKind::ImplItem => {
1345 collector.impl_items.push(ImplItemId { owner_id })
1346 }
1347 DelayedOwnerKind::TraitItem => {
1348 collector.trait_items.push(TraitItemId { owner_id })
1349 }
1350 };
1351
1352 collector.body_owners.push(def_id);
1353 }
1354 }
1355
1356 collector
1357 }
1358}
1359
1360impl<'hir> Visitor<'hir> for ItemCollector<'hir> {
1361 type NestedFilter = nested_filter::All;
1362
1363 #[inline]
1364 fn visit_if_delayed(&self, def_id: LocalDefId) -> bool {
1365 !self.crate_collector || self.delayed_ids.is_none_or(|ids| !ids.contains(&def_id))
1366 }
1367
1368 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
1369 self.tcx
1370 }
1371
1372 fn visit_item(&mut self, item: &'hir Item<'hir>) {
1373 if Node::Item(item).associated_body().is_some() {
1374 self.body_owners.push(item.owner_id.def_id);
1375 }
1376
1377 self.items.push(item.item_id());
1378 if self.crate_collector && item.has_delayed_lints {
1379 self.delayed_lint_items.push(item.item_id().owner_id);
1380 }
1381
1382 if let ItemKind::Static(..) | ItemKind::Fn { .. } | ItemKind::Macro(..) = &item.kind
1383 && item.eii
1384 {
1385 self.eiis.push(item.owner_id.def_id)
1386 }
1387
1388 if let ItemKind::Mod(_, module) = &item.kind {
1390 self.submodules.push(item.owner_id);
1391 if self.crate_collector {
1393 intravisit::walk_mod(self, module);
1394 }
1395 } else {
1396 intravisit::walk_item(self, item)
1397 }
1398 }
1399
1400 fn visit_foreign_item(&mut self, item: &'hir ForeignItem<'hir>) {
1401 self.foreign_items.push(item.foreign_item_id());
1402 if self.crate_collector && item.has_delayed_lints {
1403 self.delayed_lint_items.push(item.foreign_item_id().owner_id);
1404 }
1405 intravisit::walk_foreign_item(self, item)
1406 }
1407
1408 fn visit_anon_const(&mut self, c: &'hir AnonConst) {
1409 self.body_owners.push(c.def_id);
1410 intravisit::walk_anon_const(self, c)
1411 }
1412
1413 fn visit_inline_const(&mut self, c: &'hir ConstBlock) {
1414 self.body_owners.push(c.def_id);
1415 self.nested_bodies.push(c.def_id);
1416 intravisit::walk_inline_const(self, c)
1417 }
1418
1419 fn visit_opaque_ty(&mut self, o: &'hir OpaqueTy<'hir>) {
1420 self.opaques.push(o.def_id);
1421 intravisit::walk_opaque_ty(self, o)
1422 }
1423
1424 fn visit_expr(&mut self, ex: &'hir Expr<'hir>) {
1425 if let ExprKind::Closure(closure) = ex.kind {
1426 self.body_owners.push(closure.def_id);
1427 self.nested_bodies.push(closure.def_id);
1428 }
1429 intravisit::walk_expr(self, ex)
1430 }
1431
1432 fn visit_trait_item(&mut self, item: &'hir TraitItem<'hir>) {
1433 if Node::TraitItem(item).associated_body().is_some() {
1434 self.body_owners.push(item.owner_id.def_id);
1435 }
1436
1437 self.trait_items.push(item.trait_item_id());
1438 if self.crate_collector && item.has_delayed_lints {
1439 self.delayed_lint_items.push(item.trait_item_id().owner_id);
1440 }
1441
1442 intravisit::walk_trait_item(self, item)
1443 }
1444
1445 fn visit_impl_item(&mut self, item: &'hir ImplItem<'hir>) {
1446 if Node::ImplItem(item).associated_body().is_some() {
1447 self.body_owners.push(item.owner_id.def_id);
1448 }
1449
1450 self.impl_items.push(item.impl_item_id());
1451 if self.crate_collector && item.has_delayed_lints {
1452 self.delayed_lint_items.push(item.impl_item_id().owner_id);
1453 }
1454
1455 intravisit::walk_impl_item(self, item)
1456 }
1457}