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