1use rustc_abi::ExternAbi;
6use rustc_ast::visit::{VisitorResult, walk_list};
7use rustc_attr_ir::{Attribute, find_attr};
8use rustc_data_structures::fingerprint::Fingerprint;
9use rustc_data_structures::stable_hash::{StableHash, StableHasher};
10use rustc_data_structures::steal::Steal;
11use rustc_data_structures::svh::Svh;
12use rustc_data_structures::sync::{DynSend, DynSync, par_for_each_in, try_par_for_each_in};
13use rustc_hir::def::{DefKind, Res};
14use rustc_hir::def_id::{DefId, LocalDefId, LocalModId};
15use rustc_hir::definitions::{DefKey, DefPath, DefPathHash};
16use rustc_hir::intravisit::Visitor;
17use rustc_hir::lints::DelayedLints;
18use rustc_hir::*;
19use rustc_span::def_id::{CRATE_MOD_ID, StableCrateId};
20use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol, bug, kw, span_bug, with_metavar_spans};
21
22use crate::hir::def_id::LOCAL_CRATE;
23use crate::hir::{ModuleItems, ProjectedMaybeOwner, nested_filter};
24use crate::middle::debugger_visualizer::DebuggerVisualizerFile;
25use crate::query::{IntoQueryKey, LocalCrate};
26use crate::ty::{self, TyCtxt};
27
28struct ParentHirIterator<'tcx> {
31 current_id: HirId,
32 tcx: TyCtxt<'tcx>,
33 current_owner_nodes: Option<&'tcx OwnerNodes<'tcx>>,
36}
37
38impl<'tcx> ParentHirIterator<'tcx> {
39 fn new(tcx: TyCtxt<'tcx>, current_id: HirId) -> ParentHirIterator<'tcx> {
40 ParentHirIterator { current_id, tcx, current_owner_nodes: None }
41 }
42}
43
44impl<'tcx> Iterator for ParentHirIterator<'tcx> {
45 type Item = HirId;
46
47 fn next(&mut self) -> Option<Self::Item> {
48 if self.current_id == CRATE_HIR_ID {
49 return None;
50 }
51
52 let HirId { owner, local_id } = self.current_id;
53
54 let parent_id = if local_id == ItemLocalId::ZERO {
55 self.current_owner_nodes = None;
57 self.tcx.hir_owner_parent(owner)
58 } else {
59 let owner_nodes =
60 self.current_owner_nodes.get_or_insert_with(|| self.tcx.hir_owner_nodes(owner));
61 let parent_local_id = owner_nodes.nodes[local_id].parent;
62 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);
64 HirId { owner, local_id: parent_local_id }
65 };
66
67 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);
68
69 self.current_id = parent_id;
70 Some(parent_id)
71 }
72}
73
74pub struct ParentOwnerIterator<'tcx> {
77 current_id: HirId,
78 tcx: TyCtxt<'tcx>,
79}
80
81impl<'tcx> Iterator for ParentOwnerIterator<'tcx> {
82 type Item = (OwnerId, OwnerNode<'tcx>);
83
84 fn next(&mut self) -> Option<Self::Item> {
85 if self.current_id.local_id.index() != 0 {
86 self.current_id.local_id = ItemLocalId::ZERO;
87 let node = self.tcx.hir_owner_node(self.current_id.owner);
88 return Some((self.current_id.owner, node));
89 }
90 if self.current_id == CRATE_HIR_ID {
91 return None;
92 }
93
94 let parent_id = self.tcx.hir_def_key(self.current_id.owner.def_id).parent;
95 let parent_id = parent_id.map_or(CRATE_OWNER_ID, |local_def_index| {
96 let def_id = LocalDefId { local_def_index };
97 self.tcx.local_def_id_to_hir_id(def_id).owner
98 });
99 self.current_id = HirId::make_owner(parent_id.def_id);
100
101 let node = self.tcx.hir_owner_node(self.current_id.owner);
102 Some((self.current_id.owner, node))
103 }
104}
105
106impl<'tcx> TyCtxt<'tcx> {
107 #[inline]
108 pub fn local_def_id_to_hir_id(self, def_id: impl IntoQueryKey<LocalDefId>) -> HirId {
109 let def_id = def_id.into_query_key();
110 match self.hir_owner(def_id) {
111 ProjectedMaybeOwner::Owner(_) => HirId::make_owner(def_id),
112 ProjectedMaybeOwner::NonOwner(hir_id) => hir_id,
113 }
114 }
115
116 #[inline]
120 pub fn opt_ast_lowering_delayed_lints(self, id: OwnerId) -> Option<&'tcx Steal<DelayedLints>> {
121 self.dep_graph.assert_eval_always();
122 self.hir_owner(id.def_id).as_owner().map(|o| o.delayed_lints)
123 }
124
125 #[inline]
126 pub fn in_scope_traits_map(
127 self,
128 id: OwnerId,
129 ) -> Option<&'tcx ItemLocalMap<&'tcx [TraitCandidate<'tcx>]>> {
130 self.hir_owner(id.def_id).as_owner().map(|o| o.trait_map)
131 }
132
133 #[inline]
134 pub fn opt_hir_owner_nodes(self, def_id: LocalDefId) -> Option<&'tcx OwnerNodes<'tcx>> {
135 self.hir_owner(def_id).as_owner().map(|o| o.nodes)
136 }
137
138 #[inline]
139 fn expect_hir_owner_nodes(self, def_id: LocalDefId) -> &'tcx OwnerNodes<'tcx> {
140 self.opt_hir_owner_nodes(def_id)
141 .unwrap_or_else(|| ::rustc_span::macros::bug_impl(Some(self.def_span(def_id)),
format_args!("{0:?} is not an owner", def_id), Location::caller())span_bug!(self.def_span(def_id), "{def_id:?} is not an owner"))
142 }
143
144 #[inline]
145 pub fn hir_owner_nodes(self, owner_id: OwnerId) -> &'tcx OwnerNodes<'tcx> {
146 self.expect_hir_owner_nodes(owner_id.def_id)
147 }
148
149 #[inline]
150 fn opt_hir_owner_node(self, def_id: LocalDefId) -> Option<OwnerNode<'tcx>> {
151 self.opt_hir_owner_nodes(def_id).map(|nodes| nodes.node())
152 }
153
154 #[inline]
155 pub fn expect_hir_owner_node(self, def_id: LocalDefId) -> OwnerNode<'tcx> {
156 self.expect_hir_owner_nodes(def_id).node()
157 }
158
159 #[inline]
160 pub fn hir_owner_node(self, owner_id: OwnerId) -> OwnerNode<'tcx> {
161 self.hir_owner_nodes(owner_id).node()
162 }
163
164 pub fn hir_node(self, id: HirId) -> Node<'tcx> {
166 self.hir_owner_nodes(id.owner).nodes[id.local_id].node
167 }
168
169 #[inline]
171 pub fn hir_node_by_def_id(self, id: LocalDefId) -> Node<'tcx> {
172 self.hir_node(self.local_def_id_to_hir_id(id))
173 }
174
175 pub fn parent_hir_id(self, hir_id: HirId) -> HirId {
180 let HirId { owner, local_id } = hir_id;
181 if local_id == ItemLocalId::ZERO {
182 self.hir_owner_parent(owner)
183 } else {
184 let parent_local_id = self.hir_owner_nodes(owner).nodes[local_id].parent;
185 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);
187 HirId { owner, local_id: parent_local_id }
188 }
189 }
190
191 pub fn parent_hir_node(self, hir_id: HirId) -> Node<'tcx> {
194 self.hir_node(self.parent_hir_id(hir_id))
195 }
196
197 #[inline]
198 pub fn hir_root_module(self) -> &'tcx Mod<'tcx> {
199 match self.hir_owner_node(CRATE_OWNER_ID) {
200 OwnerNode::Crate(item) => item,
201 _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller())bug!(),
202 }
203 }
204
205 #[inline]
206 pub fn hir_free_items(self) -> impl Iterator<Item = ItemId> {
207 self.hir_crate_items(()).free_items.iter().copied()
208 }
209
210 #[inline]
211 pub fn hir_module_free_items(self, module: LocalModId) -> impl Iterator<Item = ItemId> {
212 self.hir_module_items(module).free_items()
213 }
214
215 pub fn hir_def_key(self, def_id: LocalDefId) -> DefKey {
216 self.definitions_untracked().def_key(def_id)
218 }
219
220 pub fn hir_def_path(self, def_id: LocalDefId) -> DefPath {
221 self.definitions_untracked().def_path(def_id)
223 }
224
225 #[inline]
226 pub fn hir_def_path_hash(self, def_id: LocalDefId) -> DefPathHash {
227 self.definitions_untracked().def_path_hash(def_id)
229 }
230
231 pub fn hir_get_if_local(self, id: DefId) -> Option<Node<'tcx>> {
232 id.as_local().map(|id| self.hir_node_by_def_id(id))
233 }
234
235 pub fn hir_get_generics(self, id: LocalDefId) -> Option<&'tcx Generics<'tcx>> {
236 self.opt_hir_owner_node(id)?.generics()
237 }
238
239 pub fn hir_item(self, id: ItemId) -> &'tcx Item<'tcx> {
240 self.hir_owner_node(id.owner_id).expect_item()
241 }
242
243 pub fn hir_trait_item(self, id: TraitItemId) -> &'tcx TraitItem<'tcx> {
244 self.hir_owner_node(id.owner_id).expect_trait_item()
245 }
246
247 pub fn hir_impl_item(self, id: ImplItemId) -> &'tcx ImplItem<'tcx> {
248 self.hir_owner_node(id.owner_id).expect_impl_item()
249 }
250
251 pub fn hir_foreign_item(self, id: ForeignItemId) -> &'tcx ForeignItem<'tcx> {
252 self.hir_owner_node(id.owner_id).expect_foreign_item()
253 }
254
255 pub fn hir_body(self, id: BodyId) -> &'tcx Body<'tcx> {
256 self.hir_owner_nodes(id.hir_id.owner).bodies[&id.hir_id.local_id]
257 }
258
259 #[track_caller]
260 pub fn hir_fn_decl_by_hir_id(self, hir_id: HirId) -> Option<&'tcx FnDecl<'tcx>> {
261 self.hir_node(hir_id).fn_decl()
262 }
263
264 #[track_caller]
265 pub fn hir_fn_sig_by_hir_id(self, hir_id: HirId) -> Option<&'tcx FnSig<'tcx>> {
266 self.hir_node(hir_id).fn_sig()
267 }
268
269 #[track_caller]
270 pub fn hir_enclosing_body_owner(self, hir_id: HirId) -> LocalDefId {
271 for (_, node) in self.hir_parent_iter(hir_id) {
272 if let Some((def_id, _)) = node.associated_body() {
273 return def_id;
274 }
275 }
276
277 ::rustc_span::macros::bug_impl(None,
format_args!("no `hir_enclosing_body_owner` for hir_id `{0}`", hir_id),
Location::caller());bug!("no `hir_enclosing_body_owner` for hir_id `{}`", hir_id);
278 }
279
280 pub fn hir_body_owner(self, BodyId { hir_id }: BodyId) -> HirId {
284 let parent = self.parent_hir_id(hir_id);
285 {
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:?}");
286 parent
287 }
288
289 pub fn hir_body_owner_def_id(self, BodyId { hir_id }: BodyId) -> LocalDefId {
290 self.parent_hir_node(hir_id).associated_body().unwrap().0
291 }
292
293 pub fn hir_maybe_body_owned_by(self, id: LocalDefId) -> Option<&'tcx Body<'tcx>> {
296 Some(self.hir_body(self.hir_node_by_def_id(id).body_id()?))
297 }
298
299 #[track_caller]
301 pub fn hir_body_owned_by(self, id: LocalDefId) -> &'tcx Body<'tcx> {
302 self.hir_maybe_body_owned_by(id).unwrap_or_else(|| {
303 let hir_id = self.local_def_id_to_hir_id(id);
304 ::rustc_span::macros::bug_impl(Some(self.hir_span(hir_id)),
format_args!("body_owned_by: {0} has no associated body",
self.hir_id_to_string(hir_id)), Location::caller());span_bug!(
305 self.hir_span(hir_id),
306 "body_owned_by: {} has no associated body",
307 self.hir_id_to_string(hir_id)
308 );
309 })
310 }
311
312 pub fn hir_body_param_idents(self, id: BodyId) -> impl Iterator<Item = Option<Ident>> {
313 self.hir_body(id).params.iter().map(|param| match param.pat.kind {
314 PatKind::Binding(_, _, ident, _) => Some(ident),
315 PatKind::Wild => Some(Ident::new(kw::Underscore, param.pat.span)),
316 _ => None,
317 })
318 }
319
320 pub fn hir_body_owner_kind(self, def_id: impl Into<DefId>) -> BodyOwnerKind {
324 let def_id = def_id.into();
325 match self.def_kind(def_id) {
326 DefKind::Const | DefKind::AssocConst => BodyOwnerKind::Const { inline: false },
327 DefKind::AnonConst => BodyOwnerKind::Const {
328 inline: self.anon_const_kind(def_id) == ty::AnonConstKind::NonTypeSystemInline,
329 },
330 DefKind::Ctor(..) | DefKind::Fn | DefKind::AssocFn => BodyOwnerKind::Fn,
331 DefKind::Closure | DefKind::SyntheticCoroutineBody => BodyOwnerKind::Closure,
332 DefKind::Static { safety: _, mutability, nested: false } => {
333 BodyOwnerKind::Static(mutability)
334 }
335 DefKind::GlobalAsm => BodyOwnerKind::GlobalAsm,
336 dk => ::rustc_span::macros::bug_impl(None,
format_args!("{0:?} is not a body node: {1:?}", def_id, dk),
Location::caller())bug!("{:?} is not a body node: {:?}", def_id, dk),
337 }
338 }
339
340 pub fn hir_body_const_context(self, local_def_id: LocalDefId) -> Option<ConstContext> {
348 let def_id = local_def_id.into();
349 let ccx = match self.hir_body_owner_kind(def_id) {
350 BodyOwnerKind::Const { inline } => {
351 ConstContext::Const { allow_const_fn_promotion: !inline }
352 }
353 BodyOwnerKind::Static(mutability) => ConstContext::Static(mutability),
354
355 BodyOwnerKind::Fn if self.is_constructor(def_id) => return None,
356 BodyOwnerKind::Fn | BodyOwnerKind::Closure if self.is_const_fn(def_id) => {
357 if #[allow(non_exhaustive_omitted_patterns)] match self.constness(def_id) {
rustc_hir::Constness::Const { always: true } => true,
_ => false,
}matches!(self.constness(def_id), rustc_hir::Constness::Const { always: true }) {
358 ConstContext::Const { allow_const_fn_promotion: false }
359 } else {
360 ConstContext::ConstFn
361 }
362 }
363 BodyOwnerKind::Fn | BodyOwnerKind::Closure | BodyOwnerKind::GlobalAsm => return None,
364 };
365
366 Some(ccx)
367 }
368
369 #[inline]
372 pub fn hir_body_owners(self) -> impl Iterator<Item = LocalDefId> {
373 self.hir_crate_items(()).body_owners.iter().copied()
374 }
375
376 #[inline]
377 pub fn par_hir_body_owners(self, f: impl Fn(LocalDefId) + DynSend + DynSync) {
378 par_for_each_in(&self.hir_crate_items(()).body_owners[..], |&&def_id| f(def_id));
379 }
380
381 pub fn hir_ty_param_owner(self, def_id: LocalDefId) -> LocalDefId {
382 let def_kind = self.def_kind(def_id);
383 match def_kind {
384 DefKind::Trait | DefKind::TraitAlias => def_id,
385 DefKind::LifetimeParam | DefKind::TyParam | DefKind::ConstParam => {
386 self.local_parent(def_id)
387 }
388 _ => ::rustc_span::macros::bug_impl(None,
format_args!("ty_param_owner: {0:?} is a {1:?} not a type parameter",
def_id, def_kind), Location::caller())bug!("ty_param_owner: {:?} is a {:?} not a type parameter", def_id, def_kind),
389 }
390 }
391
392 pub fn hir_ty_param_name(self, def_id: LocalDefId) -> Symbol {
393 let def_kind = self.def_kind(def_id);
394 match def_kind {
395 DefKind::Trait | DefKind::TraitAlias => kw::SelfUpper,
396 DefKind::LifetimeParam | DefKind::TyParam | DefKind::ConstParam => {
397 self.item_name(def_id.to_def_id())
398 }
399 _ => ::rustc_span::macros::bug_impl(None,
format_args!("ty_param_name: {0:?} is a {1:?} not a type parameter",
def_id, def_kind), Location::caller())bug!("ty_param_name: {:?} is a {:?} not a type parameter", def_id, def_kind),
400 }
401 }
402
403 pub fn hir_krate_attrs(self) -> &'tcx [Attribute] {
407 self.hir_attrs(CRATE_HIR_ID)
408 }
409
410 pub fn hir_rustc_coherence_is_core(self) -> bool {
411 {
{
'done:
{
for i in self.hir_krate_attrs() {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcCoherenceIsCore) =>
{
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
}find_attr!(self.hir_krate_attrs(), RustcCoherenceIsCore)
412 }
413
414 pub fn hir_get_module(self, module: LocalModId) -> (&'tcx Mod<'tcx>, Span) {
415 match self.hir_owner_node(module.into()) {
416 OwnerNode::Item(&Item { span, kind: ItemKind::Mod(_, m), .. }) => (m, span),
417 OwnerNode::Crate(item) => (item, item.spans.inner_span),
418 node => { ::core::panicking::panic_fmt(format_args!("not a module: {0:?}", node)); }panic!("not a module: {node:?}"),
419 }
420 }
421
422 pub fn hir_walk_toplevel_module<V>(self, visitor: &mut V) -> V::Result
424 where
425 V: Visitor<'tcx>,
426 {
427 let (top_mod, span) = self.hir_get_module(CRATE_MOD_ID);
428 visitor.visit_mod(top_mod, span, CRATE_MOD_ID)
429 }
430
431 pub fn hir_walk_attributes<V>(self, visitor: &mut V) -> V::Result
433 where
434 V: Visitor<'tcx>,
435 {
436 let krate = self.hir_crate_items(());
437 for owner in krate.owners() {
438 let attrs = self.hir_attr_map(owner);
439 for attrs in attrs.map.values() {
440 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);
441 }
442 }
443 V::Result::output()
444 }
445
446 pub fn hir_visit_all_item_likes_in_crate<V>(self, visitor: &mut V) -> V::Result
457 where
458 V: Visitor<'tcx>,
459 {
460 let krate = self.hir_crate_items(());
461 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)));
462 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!(
463 visitor,
464 visit_trait_item,
465 krate.trait_items().map(|id| self.hir_trait_item(id))
466 );
467 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)));
468 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!(
469 visitor,
470 visit_foreign_item,
471 krate.foreign_items().map(|id| self.hir_foreign_item(id))
472 );
473 V::Result::output()
474 }
475
476 pub fn hir_visit_item_likes_in_module<V>(self, module: LocalModId, visitor: &mut V) -> V::Result
479 where
480 V: Visitor<'tcx>,
481 {
482 let module = self.hir_module_items(module);
483 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)));
484 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!(
485 visitor,
486 visit_trait_item,
487 module.trait_items().map(|id| self.hir_trait_item(id))
488 );
489 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)));
490 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!(
491 visitor,
492 visit_foreign_item,
493 module.foreign_items().map(|id| self.hir_foreign_item(id))
494 );
495 V::Result::output()
496 }
497
498 pub fn hir_for_each_module(self, mut f: impl FnMut(LocalModId)) {
499 let crate_items = self.hir_crate_items(());
500 for &module in crate_items.submodules.iter() {
501 f(module)
502 }
503 }
504
505 #[inline]
506 pub fn par_hir_for_each_module(self, f: impl Fn(LocalModId) + DynSend + DynSync) {
507 let crate_items = self.hir_crate_items(());
508 par_for_each_in(&crate_items.submodules[..], |&&module| f(module));
509 }
510
511 #[inline]
512 pub fn try_par_hir_for_each_module(
513 self,
514 f: impl Fn(LocalModId) -> Result<(), ErrorGuaranteed> + DynSend + DynSync,
515 ) -> Result<(), ErrorGuaranteed> {
516 let crate_items = self.hir_crate_items(());
517 try_par_for_each_in(&crate_items.submodules[..], |&&module| f(module))
518 }
519
520 #[inline]
523 pub fn hir_parent_id_iter(self, current_id: HirId) -> impl Iterator<Item = HirId> {
524 ParentHirIterator::new(self, current_id)
525 }
526
527 #[inline]
530 pub fn hir_parent_iter(self, current_id: HirId) -> impl Iterator<Item = (HirId, Node<'tcx>)> {
531 self.hir_parent_id_iter(current_id).map(move |id| (id, self.hir_node(id)))
532 }
533
534 #[inline]
537 pub fn hir_parent_owner_iter(self, current_id: HirId) -> ParentOwnerIterator<'tcx> {
538 ParentOwnerIterator { current_id, tcx: self }
539 }
540
541 pub fn hir_is_lhs(self, id: HirId) -> bool {
543 match self.parent_hir_node(id) {
544 Node::Expr(expr) => match expr.kind {
545 ExprKind::Assign(lhs, _rhs, _span) => lhs.hir_id == id,
546 _ => false,
547 },
548 _ => false,
549 }
550 }
551
552 pub fn hir_is_inside_const_context(self, hir_id: HirId) -> bool {
555 self.hir_body_const_context(self.hir_enclosing_body_owner(hir_id)).is_some()
556 }
557
558 pub fn hir_get_fn_id_for_return_block(self, id: HirId) -> Option<HirId> {
585 let enclosing_body_owner = self.local_def_id_to_hir_id(self.hir_enclosing_body_owner(id));
586
587 let mut iter = [id].into_iter().chain(self.hir_parent_id_iter(id)).peekable();
589 while let Some(cur_id) = iter.next() {
590 if enclosing_body_owner == cur_id {
591 break;
592 }
593
594 if let Node::Expr(Expr { kind: ExprKind::Ret(_), .. }) = self.hir_node(cur_id) {
597 break;
598 }
599
600 if let Some(&parent_id) = iter.peek() {
603 match self.hir_node(parent_id) {
604 Node::Block(Block { expr: Some(e), .. }) if cur_id != e.hir_id => return None,
607 Node::Block(Block { expr: Some(e), .. })
608 if #[allow(non_exhaustive_omitted_patterns)] match e.kind {
ExprKind::If(_, _, None) => true,
_ => false,
}matches!(e.kind, ExprKind::If(_, _, None)) =>
609 {
610 return None;
611 }
612
613 Node::Block(Block { expr: None, .. })
616 | Node::Expr(Expr { kind: ExprKind::Loop(..), .. })
617 | Node::LetStmt(..) => return None,
618
619 _ => {}
620 }
621 }
622 }
623
624 Some(enclosing_body_owner)
625 }
626
627 pub fn hir_get_parent_item(self, hir_id: HirId) -> OwnerId {
632 if hir_id.local_id != ItemLocalId::ZERO {
633 hir_id.owner
635 } else if let Some((def_id, _node)) = self.hir_parent_owner_iter(hir_id).next() {
636 def_id
637 } else {
638 CRATE_OWNER_ID
639 }
640 }
641
642 pub fn hir_get_if_cause(self, hir_id: HirId) -> Option<&'tcx Expr<'tcx>> {
648 for (_, node) in self.hir_parent_iter(hir_id) {
649 match node {
650 Node::Item(_)
651 | Node::ForeignItem(_)
652 | Node::TraitItem(_)
653 | Node::ImplItem(_)
654 | Node::Stmt(Stmt { kind: StmtKind::Let(_), .. }) => break,
655 Node::Expr(expr @ Expr { kind: ExprKind::If(..) | ExprKind::Match(..), .. }) => {
656 return Some(expr);
657 }
658 _ => {}
659 }
660 }
661 None
662 }
663
664 pub fn hir_get_enclosing_scope(self, hir_id: HirId) -> Option<HirId> {
666 for (hir_id, node) in self.hir_parent_iter(hir_id) {
667 if let Node::Item(Item {
668 kind:
669 ItemKind::Fn { .. }
670 | ItemKind::Const(..)
671 | ItemKind::Static(..)
672 | ItemKind::Mod(..)
673 | ItemKind::Enum(..)
674 | ItemKind::Struct(..)
675 | ItemKind::Union(..)
676 | ItemKind::Trait { .. }
677 | ItemKind::Impl { .. },
678 ..
679 })
680 | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(..), .. })
681 | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(..), .. })
682 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(..), .. })
683 | Node::Block(_) = node
684 {
685 return Some(hir_id);
686 }
687 }
688 None
689 }
690
691 pub fn hir_get_defining_scope(self, id: HirId) -> HirId {
693 let mut scope = id;
694 loop {
695 scope = self.hir_get_enclosing_scope(scope).unwrap_or(CRATE_HIR_ID);
696 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(_)) {
697 return scope;
698 }
699 }
700 }
701
702 pub fn hir_id_to_string(self, id: HirId) -> String {
705 let path_str = |def_id: LocalDefId| self.def_path_str(def_id);
706
707 let span_str =
708 || self.sess.source_map().span_to_snippet(self.hir_span(id)).unwrap_or_default();
709 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());
710
711 match self.hir_node(id) {
712 Node::Item(item) => {
713 let item_str = match item.kind {
714 ItemKind::ExternCrate(..) => "extern crate",
715 ItemKind::Use(..) => "use",
716 ItemKind::Static(..) => "static",
717 ItemKind::Const(..) => "const",
718 ItemKind::Fn { .. } => "fn",
719 ItemKind::Macro(..) => "macro",
720 ItemKind::Mod(..) => "mod",
721 ItemKind::ForeignMod { .. } => "foreign mod",
722 ItemKind::GlobalAsm { .. } => "global asm",
723 ItemKind::TyAlias(..) => "ty",
724 ItemKind::Enum(..) => "enum",
725 ItemKind::Struct(..) => "struct",
726 ItemKind::Union(..) => "union",
727 ItemKind::Trait { .. } => "trait",
728 ItemKind::TraitAlias(..) => "trait alias",
729 ItemKind::Impl { .. } => "impl",
730 ItemKind::TestBinderConstraints { .. } => "test_binder_constraints!",
731 };
732 ::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))
733 }
734 Node::ForeignItem(item) => {
735 ::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))
736 }
737 Node::ImplItem(ii) => {
738 let kind = match ii.kind {
739 ImplItemKind::Const(..) => "associated constant",
740 ImplItemKind::Fn(fn_sig, _) => match fn_sig.decl.implicit_self() {
741 ImplicitSelfKind::None => "associated function",
742 _ => "method",
743 },
744 ImplItemKind::Type(_) => "associated type",
745 };
746 ::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))
747 }
748 Node::TraitItem(ti) => {
749 let kind = match ti.kind {
750 TraitItemKind::Const(..) => "associated constant",
751 TraitItemKind::Fn(fn_sig, _) => match fn_sig.decl.implicit_self() {
752 ImplicitSelfKind::None => "associated function",
753 _ => "trait method",
754 },
755 TraitItemKind::Type(..) => "associated type",
756 };
757
758 ::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))
759 }
760 Node::Variant(variant) => {
761 ::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))
762 }
763 Node::Field(field) => {
764 ::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))
765 }
766 Node::AnonConst(_) => node_str("const"),
767 Node::ConstBlock(_) => node_str("const"),
768 Node::ConstArg(_) => node_str("const"),
769 Node::Expr(_) => node_str("expr"),
770 Node::ExprField(_) => node_str("expr field"),
771 Node::ConstArgExprField(_) => node_str("const arg expr field"),
772 Node::Stmt(_) => node_str("stmt"),
773 Node::PathSegment(_) => node_str("path segment"),
774 Node::Ty(_) => node_str("type"),
775 Node::AssocItemConstraint(_) => node_str("assoc item constraint"),
776 Node::TraitRef(_) => node_str("trait ref"),
777 Node::OpaqueTy(_) => node_str("opaque type"),
778 Node::Pat(_) => node_str("pat"),
779 Node::TyPat(_) => node_str("pat ty"),
780 Node::PatField(_) => node_str("pattern field"),
781 Node::PatExpr(_) => node_str("pattern literal"),
782 Node::Param(_) => node_str("param"),
783 Node::Arm(_) => node_str("arm"),
784 Node::Block(_) => node_str("block"),
785 Node::Infer(_) => node_str("infer"),
786 Node::LetStmt(_) => node_str("local"),
787 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!(
788 "{id} (ctor {})",
789 ctor.ctor_def_id().map_or("<missing path>".into(), |def_id| path_str(def_id)),
790 ),
791 Node::Lifetime(_) => node_str("lifetime"),
792 Node::GenericParam(param) => {
793 ::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))
794 }
795 Node::Crate(..) => String::from("(root_crate)"),
796 Node::WherePredicate(_) => node_str("where predicate"),
797 Node::NestedUseTree(_) => node_str("use"),
798 Node::PreciseCapturingNonLifetimeArg(_param) => node_str("parameter"),
799 Node::TestBinderForall(_) => node_str("forall"),
800 Node::TestBinderExists(_) => node_str("exists"),
801 Node::TestBinderBoundTypeConstraint(_) => node_str("test bound type constraint"),
802 Node::Synthetic => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
803 Node::Err(_) => node_str("error"),
804 }
805 }
806
807 pub fn hir_get_foreign_abi(self, hir_id: HirId) -> ExternAbi {
808 let parent = self.hir_get_parent_item(hir_id);
809 if let OwnerNode::Item(Item { kind: ItemKind::ForeignMod { abi, .. }, .. }) =
810 self.hir_owner_node(parent)
811 {
812 return *abi;
813 }
814 ::rustc_span::macros::bug_impl(None,
format_args!("expected foreign mod or inlined parent, found {0}",
self.hir_id_to_string(HirId::make_owner(parent.def_id))),
Location::caller())bug!(
815 "expected foreign mod or inlined parent, found {}",
816 self.hir_id_to_string(HirId::make_owner(parent.def_id))
817 )
818 }
819
820 pub fn hir_expect_item(self, id: LocalDefId) -> &'tcx Item<'tcx> {
821 match self.expect_hir_owner_node(id) {
822 OwnerNode::Item(item) => item,
823 _ => ::rustc_span::macros::bug_impl(None,
format_args!("expected item, found {0}",
self.hir_id_to_string(HirId::make_owner(id))), Location::caller())bug!("expected item, found {}", self.hir_id_to_string(HirId::make_owner(id))),
824 }
825 }
826
827 pub fn hir_expect_impl_item(self, id: LocalDefId) -> &'tcx ImplItem<'tcx> {
828 match self.expect_hir_owner_node(id) {
829 OwnerNode::ImplItem(item) => item,
830 _ => ::rustc_span::macros::bug_impl(None,
format_args!("expected impl item, found {0}",
self.hir_id_to_string(HirId::make_owner(id))), Location::caller())bug!("expected impl item, found {}", self.hir_id_to_string(HirId::make_owner(id))),
831 }
832 }
833
834 pub fn hir_expect_trait_item(self, id: LocalDefId) -> &'tcx TraitItem<'tcx> {
835 match self.expect_hir_owner_node(id) {
836 OwnerNode::TraitItem(item) => item,
837 _ => {
838 ::rustc_span::macros::bug_impl(None,
format_args!("expected trait item, found {0}",
self.hir_id_to_string(HirId::make_owner(id))), Location::caller())bug!("expected trait item, found {}", self.hir_id_to_string(HirId::make_owner(id)))
839 }
840 }
841 }
842
843 pub fn hir_get_fn_output(self, def_id: LocalDefId) -> Option<&'tcx FnRetTy<'tcx>> {
844 Some(&self.opt_hir_owner_node(def_id)?.fn_decl()?.output)
845 }
846
847 #[track_caller]
848 pub fn hir_expect_opaque_ty(self, id: LocalDefId) -> &'tcx OpaqueTy<'tcx> {
849 match self.hir_node_by_def_id(id) {
850 Node::OpaqueTy(opaq) => opaq,
851 _ => {
852 ::rustc_span::macros::bug_impl(None,
format_args!("expected opaque type definition, found {0}",
self.hir_id_to_string(self.local_def_id_to_hir_id(id))),
Location::caller())bug!(
853 "expected opaque type definition, found {}",
854 self.hir_id_to_string(self.local_def_id_to_hir_id(id))
855 )
856 }
857 }
858 }
859
860 pub fn hir_expect_expr(self, id: HirId) -> &'tcx Expr<'tcx> {
861 match self.hir_node(id) {
862 Node::Expr(expr) => expr,
863 _ => ::rustc_span::macros::bug_impl(None,
format_args!("expected expr, found {0}", self.hir_id_to_string(id)),
Location::caller())bug!("expected expr, found {}", self.hir_id_to_string(id)),
864 }
865 }
866
867 pub fn hir_opt_delegation_sig_id(self, def_id: LocalDefId) -> Option<DefId> {
868 self.opt_hir_owner_node(def_id)?.fn_decl()?.opt_delegation_sig_id()
869 }
870
871 pub fn hir_opt_delegation_info(self, def_id: LocalDefId) -> Option<&'tcx DelegationInfo> {
872 self.opt_hir_owner_node(def_id)?.fn_decl()?.opt_delegation_info()
873 }
874
875 pub fn hir_delegation_info(self, delegation_id: LocalDefId) -> &'tcx DelegationInfo {
876 self.hir_opt_delegation_info(delegation_id).expect("processing delegation")
877 }
878
879 #[inline]
880 fn hir_opt_ident(self, id: HirId) -> Option<Ident> {
881 match self.hir_node(id) {
882 Node::Pat(&Pat { kind: PatKind::Binding(_, _, ident, _), .. }) => Some(ident),
883 Node::Ctor(..) => match self.parent_hir_node(id) {
886 Node::Item(item) => Some(item.kind.ident().unwrap()),
887 Node::Variant(variant) => Some(variant.ident),
888 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
889 },
890 node => node.ident(),
891 }
892 }
893
894 #[inline]
895 pub(super) fn hir_opt_ident_span(self, id: HirId) -> Option<Span> {
896 self.hir_opt_ident(id).map(|ident| ident.span)
897 }
898
899 #[inline]
900 pub fn hir_ident(self, id: HirId) -> Ident {
901 self.hir_opt_ident(id).unwrap()
902 }
903
904 #[inline]
905 pub fn hir_opt_name(self, id: HirId) -> Option<Symbol> {
906 self.hir_opt_ident(id).map(|ident| ident.name)
907 }
908
909 pub fn hir_name(self, id: HirId) -> Symbol {
910 self.hir_opt_name(id).unwrap_or_else(|| ::rustc_span::macros::bug_impl(None,
format_args!("no name for {0}", self.hir_id_to_string(id)),
Location::caller())bug!("no name for {}", self.hir_id_to_string(id)))
911 }
912
913 pub fn hir_attrs(self, id: HirId) -> &'tcx [Attribute] {
915 self.hir_attr_map(id.owner).get(id.local_id)
916 }
917
918 pub fn hir_span(self, hir_id: HirId) -> Span {
921 fn until_within(outer: Span, end: Span) -> Span {
922 if let Some(end) = end.find_ancestor_inside(outer) {
923 outer.with_hi(end.hi())
924 } else {
925 outer
926 }
927 }
928
929 fn named_span(item_span: Span, ident: Ident, generics: Option<&Generics<'_>>) -> Span {
930 let mut span = until_within(item_span, ident.span);
931 if let Some(g) = generics
932 && !g.span.is_dummy()
933 && let Some(g_span) = g.span.find_ancestor_inside(item_span)
934 {
935 span = span.to(g_span);
936 }
937 span
938 }
939
940 let span = match self.hir_node(hir_id) {
941 Node::Item(Item { kind: ItemKind::Fn { sig, .. }, span: outer_span, .. })
943 | Node::TraitItem(TraitItem {
944 kind: TraitItemKind::Fn(sig, ..),
945 span: outer_span,
946 ..
947 })
948 | Node::ImplItem(ImplItem {
949 kind: ImplItemKind::Fn(sig, ..), span: outer_span, ..
950 })
951 | Node::ForeignItem(ForeignItem {
952 kind: ForeignItemKind::Fn(sig, ..),
953 span: outer_span,
954 ..
955 }) => {
956 sig.span.find_ancestor_in_same_ctxt(*outer_span).unwrap_or(*outer_span)
959 }
960 Node::Item(Item {
962 kind: ItemKind::Impl(Impl { generics, .. }),
963 span: outer_span,
964 ..
965 }) => until_within(*outer_span, generics.where_clause_span),
966 Node::Item(Item {
968 kind: ItemKind::Const(_, _, ty, _) | ItemKind::Static(_, _, ty, _),
969 span: outer_span,
970 ..
971 })
972 | Node::TraitItem(TraitItem {
973 kind: TraitItemKind::Const(ty, ..),
974 span: outer_span,
975 ..
976 })
977 | Node::ImplItem(ImplItem {
978 kind: ImplItemKind::Const(ty, ..),
979 span: outer_span,
980 ..
981 })
982 | Node::ForeignItem(ForeignItem {
983 kind: ForeignItemKind::Static(ty, ..),
984 span: outer_span,
985 ..
986 }) => until_within(*outer_span, ty.span),
987 Node::Item(Item {
989 kind: ItemKind::Trait { generics, bounds, .. },
990 span: outer_span,
991 ..
992 })
993 | Node::TraitItem(TraitItem {
994 kind: TraitItemKind::Type(bounds, _),
995 generics,
996 span: outer_span,
997 ..
998 }) => {
999 let end = if let Some(b) = bounds.last() { b.span() } else { generics.span };
1000 until_within(*outer_span, end)
1001 }
1002 Node::Item(item) => match &item.kind {
1004 ItemKind::Use(use_tree) => {
1005 use_tree.prefix.span.find_ancestor_in_same_ctxt(item.span).unwrap_or(item.span)
1008 }
1009 _ => {
1010 if let Some(ident) = item.kind.ident() {
1011 named_span(item.span, ident, item.kind.generics())
1012 } else {
1013 item.span
1014 }
1015 }
1016 },
1017 Node::Variant(variant) => named_span(variant.span, variant.ident, None),
1018 Node::ImplItem(item) => named_span(item.span, item.ident, Some(item.generics)),
1019 Node::ForeignItem(item) => named_span(item.span, item.ident, None),
1020 Node::Ctor(_) => return self.hir_span(self.parent_hir_id(hir_id)),
1021 Node::Expr(Expr {
1022 kind: ExprKind::Closure(Closure { fn_decl_span, .. }),
1023 span,
1024 ..
1025 }) => {
1026 fn_decl_span.find_ancestor_inside_same_ctxt(*span).unwrap_or(*span)
1028 }
1029 _ => self.hir_span_with_body(hir_id),
1030 };
1031 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());
1032 span
1033 }
1034
1035 pub fn hir_span_with_body(self, hir_id: HirId) -> Span {
1038 match self.hir_node(hir_id) {
1039 Node::Param(param) => param.span,
1040 Node::Item(item) => item.span,
1041 Node::ForeignItem(foreign_item) => foreign_item.span,
1042 Node::TraitItem(trait_item) => trait_item.span,
1043 Node::ImplItem(impl_item) => impl_item.span,
1044 Node::Variant(variant) => variant.span,
1045 Node::Field(field) => field.span,
1046 Node::AnonConst(constant) => constant.span,
1047 Node::ConstBlock(constant) => self.hir_body(constant.body).value.span,
1048 Node::ConstArg(const_arg) => const_arg.span,
1049 Node::Expr(expr) => expr.span,
1050 Node::ExprField(field) => field.span,
1051 Node::ConstArgExprField(field) => field.span,
1052 Node::Stmt(stmt) => stmt.span,
1053 Node::PathSegment(seg) => {
1054 let ident_span = seg.ident.span;
1055 ident_span
1056 .with_hi(seg.args.map_or_else(|| ident_span.hi(), |args| args.span_ext.hi()))
1057 }
1058 Node::Ty(ty) => ty.span,
1059 Node::AssocItemConstraint(constraint) => constraint.span,
1060 Node::TraitRef(tr) => tr.path.span,
1061 Node::OpaqueTy(op) => op.span,
1062 Node::Pat(pat) => pat.span,
1063 Node::TyPat(pat) => pat.span,
1064 Node::PatField(field) => field.span,
1065 Node::PatExpr(lit) => lit.span,
1066 Node::Arm(arm) => arm.span,
1067 Node::Block(block) => block.span,
1068 Node::Ctor(..) => self.hir_span_with_body(self.parent_hir_id(hir_id)),
1069 Node::Lifetime(lifetime) => lifetime.ident.span,
1070 Node::GenericParam(param) => param.span,
1071 Node::Infer(i) => i.span,
1072 Node::LetStmt(local) => local.span,
1073 Node::Crate(item) => item.spans.inner_span,
1074 Node::WherePredicate(pred) => pred.span,
1075 Node::PreciseCapturingNonLifetimeArg(param) => param.ident.span,
1076 Node::NestedUseTree(tree) => tree.prefix.span,
1077 Node::TestBinderForall(forall) => forall.span,
1078 Node::TestBinderExists(exists) => exists.span,
1079 Node::TestBinderBoundTypeConstraint(bound_type) => bound_type.span,
1080 Node::Synthetic => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1081 Node::Err(span) => span,
1082 }
1083 }
1084
1085 pub fn hir_span_if_local(self, id: DefId) -> Option<Span> {
1086 id.is_local().then(|| self.def_span(id))
1087 }
1088
1089 pub fn hir_res_span(self, res: Res) -> Option<Span> {
1090 match res {
1091 Res::Err => None,
1092 Res::Local(id) => Some(self.hir_span(id)),
1093 res => self.hir_span_if_local(res.opt_def_id()?),
1094 }
1095 }
1096
1097 pub fn hir_opt_const_param_default_param_def_id(self, anon_const: HirId) -> Option<LocalDefId> {
1100 let const_arg = self.parent_hir_id(anon_const);
1101 match self.parent_hir_node(const_arg) {
1102 Node::GenericParam(GenericParam {
1103 def_id: param_id,
1104 kind: GenericParamKind::Const { .. },
1105 ..
1106 }) => Some(*param_id),
1107 _ => None,
1108 }
1109 }
1110
1111 pub fn hir_maybe_get_struct_pattern_shorthand_field(self, expr: &Expr<'_>) -> Option<Symbol> {
1112 let local = match expr {
1113 Expr {
1114 kind:
1115 ExprKind::Path(QPath::Resolved(
1116 None,
1117 Path {
1118 res: def::Res::Local(_), segments: [PathSegment { ident, .. }], ..
1119 },
1120 )),
1121 ..
1122 } => Some(ident),
1123 _ => None,
1124 }?;
1125
1126 match self.parent_hir_node(expr.hir_id) {
1127 Node::ExprField(field) => {
1128 if field.ident.name == local.name && field.is_shorthand {
1129 return Some(local.name);
1130 }
1131 }
1132 _ => {}
1133 }
1134
1135 None
1136 }
1137}
1138
1139impl<'tcx> intravisit::HirTyCtxt<'tcx> for TyCtxt<'tcx> {
1140 fn hir_node(&self, hir_id: HirId) -> Node<'tcx> {
1141 (*self).hir_node(hir_id)
1142 }
1143
1144 fn hir_body(&self, id: BodyId) -> &'tcx Body<'tcx> {
1145 (*self).hir_body(id)
1146 }
1147
1148 fn hir_item(&self, id: ItemId) -> &'tcx Item<'tcx> {
1149 (*self).hir_item(id)
1150 }
1151
1152 fn hir_trait_item(&self, id: TraitItemId) -> &'tcx TraitItem<'tcx> {
1153 (*self).hir_trait_item(id)
1154 }
1155
1156 fn hir_impl_item(&self, id: ImplItemId) -> &'tcx ImplItem<'tcx> {
1157 (*self).hir_impl_item(id)
1158 }
1159
1160 fn hir_foreign_item(&self, id: ForeignItemId) -> &'tcx ForeignItem<'tcx> {
1161 (*self).hir_foreign_item(id)
1162 }
1163}
1164
1165pub(super) fn crate_hash(tcx: TyCtxt<'_>, _: LocalCrate) -> Svh {
1166 if !tcx.sess.opts.unstable_opts.metadata_crate_hash {
1169 return legacy_crate_hash(tcx);
1170 }
1171
1172 if tcx.needs_metadata() {
1175 *tcx.untracked()
1176 .local_crate_hash
1177 .get()
1178 .expect("crate_hash(LOCAL_CRATE) called before metadata encoding")
1179 } else {
1180 let hir_body_hash = compute_hir_hash(tcx);
1183
1184 let upstream_crates = upstream_crates(tcx);
1185
1186 let crate_hash: Fingerprint = tcx.with_stable_hashing_context(|mut hcx| {
1187 let mut stable_hasher = StableHasher::new();
1188 hir_body_hash.stable_hash(&mut hcx, &mut stable_hasher);
1189 upstream_crates.stable_hash(&mut hcx, &mut stable_hasher);
1190 tcx.sess.opts.dep_tracking_hash(true).stable_hash(&mut hcx, &mut stable_hasher);
1191 tcx.stable_crate_id(LOCAL_CRATE).stable_hash(&mut hcx, &mut stable_hasher);
1192
1193 stable_hasher.finish()
1194 });
1195
1196 Svh::new(crate_hash)
1197 }
1198}
1199
1200fn legacy_crate_hash(tcx: TyCtxt<'_>) -> Svh {
1205 let krate = tcx.hir_crate_items(());
1206
1207 let upstream_crates = upstream_crates(tcx);
1208 let resolutions = tcx.resolutions(());
1209
1210 let mut source_file_names: Vec<_> = tcx
1216 .sess
1217 .source_map()
1218 .files()
1219 .iter()
1220 .filter(|source_file| source_file.cnum == LOCAL_CRATE)
1221 .map(|source_file| source_file.stable_id)
1222 .collect();
1223
1224 source_file_names.sort_unstable();
1225
1226 let debugger_visualizers: Vec<_> = tcx
1232 .debugger_visualizers(LOCAL_CRATE)
1233 .iter()
1234 .map(DebuggerVisualizerFile::path_erased)
1238 .collect();
1239
1240 let crate_hash: Fingerprint = tcx.with_stable_hashing_context(|mut hcx| {
1241 let mut stable_hasher = StableHasher::new();
1242 for owner in krate.owners() {
1244 if let Some(info) = tcx.lower_to_hir(owner.def_id).as_owner() {
1245 info.stable_hash(&mut hcx, &mut stable_hasher);
1246 }
1247 }
1248 upstream_crates.stable_hash(&mut hcx, &mut stable_hasher);
1249 source_file_names.stable_hash(&mut hcx, &mut stable_hasher);
1250 debugger_visualizers.stable_hash(&mut hcx, &mut stable_hasher);
1251 if tcx.sess.opts.incremental.is_some() {
1252 let definitions = tcx.untracked().definitions.freeze();
1253 let mut owner_spans: Vec<_> = tcx
1254 .hir_crate_items(())
1255 .definitions()
1256 .map(|def_id| {
1257 let def_path_hash = definitions.def_path_hash(def_id);
1258 let span = tcx.source_span(def_id);
1259 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);
1260 (def_path_hash, span)
1261 })
1262 .collect();
1263 owner_spans.sort_unstable_by_key(|bn| bn.0);
1264 owner_spans.stable_hash(&mut hcx, &mut stable_hasher);
1265 }
1266 tcx.sess.opts.dep_tracking_hash(true).stable_hash(&mut hcx, &mut stable_hasher);
1267 tcx.stable_crate_id(LOCAL_CRATE).stable_hash(&mut hcx, &mut stable_hasher);
1268 resolutions.visibilities_for_hashing.stable_hash(&mut hcx, &mut stable_hasher);
1273 with_metavar_spans(|mspans| {
1274 mspans.freeze_and_get_read_spans().stable_hash(&mut hcx, &mut stable_hasher);
1275 });
1276 stable_hasher.finish()
1277 });
1278
1279 Svh::new(crate_hash)
1280}
1281
1282pub fn compute_hir_hash(tcx: TyCtxt<'_>) -> Fingerprint {
1288 tcx.hir_crate_items(())
1289 .owners()
1290 .filter_map(|owner| Some(tcx.lower_to_hir(owner.def_id).as_owner()?.fingerprint()))
1291 .reduce(Fingerprint::combine_commutative)
1292 .expect("HIR hash requested without any content")
1293}
1294
1295fn upstream_crates(tcx: TyCtxt<'_>) -> Vec<(StableCrateId, Svh)> {
1296 let mut upstream_crates: Vec<_> = tcx
1297 .crates(())
1298 .iter()
1299 .map(|&cnum| {
1300 let stable_crate_id = tcx.stable_crate_id(cnum);
1301 let hash = tcx.crate_hash(cnum);
1302 (stable_crate_id, hash)
1303 })
1304 .collect();
1305 upstream_crates.sort_unstable_by_key(|&(stable_crate_id, _)| stable_crate_id);
1306 upstream_crates
1307}
1308
1309pub(super) fn hir_module_items(tcx: TyCtxt<'_>, module_id: LocalModId) -> ModuleItems {
1310 let mut collector = ItemCollector::new(tcx, false);
1311
1312 let (hir_mod, span) = tcx.hir_get_module(module_id);
1313 collector.visit_mod(hir_mod, span, module_id);
1314
1315 let ItemCollector {
1316 submodules,
1317 items,
1318 trait_items,
1319 impl_items,
1320 foreign_items,
1321 body_owners,
1322 opaques,
1323 nested_bodies,
1324 eiis,
1325 proc_macro_decls,
1326 ..
1327 } = collector;
1328
1329 ModuleItems {
1330 add_root: false,
1331 submodules: submodules.into_boxed_slice(),
1332 free_items: items.into_boxed_slice(),
1333 trait_items: trait_items.into_boxed_slice(),
1334 impl_items: impl_items.into_boxed_slice(),
1335 foreign_items: foreign_items.into_boxed_slice(),
1336 body_owners: body_owners.into_boxed_slice(),
1337 opaques: opaques.into_boxed_slice(),
1338 nested_bodies: nested_bodies.into_boxed_slice(),
1339 eiis: eiis.into_boxed_slice(),
1340 proc_macro_decls,
1341 }
1342}
1343
1344pub(crate) fn hir_crate_items(tcx: TyCtxt<'_>, _: ()) -> ModuleItems {
1345 let mut collector = ItemCollector::new(tcx, true);
1346
1347 collector.submodules.push(CRATE_MOD_ID);
1351 tcx.hir_walk_toplevel_module(&mut collector);
1352
1353 let ItemCollector {
1354 submodules,
1355 items,
1356 trait_items,
1357 impl_items,
1358 foreign_items,
1359 body_owners,
1360 opaques,
1361 nested_bodies,
1362 eiis,
1363 proc_macro_decls,
1364 ..
1365 } = collector;
1366
1367 ModuleItems {
1368 add_root: true,
1369 submodules: submodules.into_boxed_slice(),
1370 free_items: items.into_boxed_slice(),
1371 trait_items: trait_items.into_boxed_slice(),
1372 impl_items: impl_items.into_boxed_slice(),
1373 foreign_items: foreign_items.into_boxed_slice(),
1374 body_owners: body_owners.into_boxed_slice(),
1375 opaques: opaques.into_boxed_slice(),
1376 nested_bodies: nested_bodies.into_boxed_slice(),
1377 eiis: eiis.into_boxed_slice(),
1378 proc_macro_decls,
1379 }
1380}
1381
1382struct ItemCollector<'tcx> {
1383 crate_collector: bool,
1388 tcx: TyCtxt<'tcx>,
1389 submodules: Vec<LocalModId> = ::alloc::vec::Vec::new()vec![],
1390 items: Vec<ItemId> = ::alloc::vec::Vec::new()vec![],
1391 trait_items: Vec<TraitItemId> = ::alloc::vec::Vec::new()vec![],
1392 impl_items: Vec<ImplItemId> = ::alloc::vec::Vec::new()vec![],
1393 foreign_items: Vec<ForeignItemId> = ::alloc::vec::Vec::new()vec![],
1394 body_owners: Vec<LocalDefId> = ::alloc::vec::Vec::new()vec![],
1395 opaques: Vec<LocalDefId> = ::alloc::vec::Vec::new()vec![],
1396 nested_bodies: Vec<LocalDefId> = ::alloc::vec::Vec::new()vec![],
1397 eiis: Vec<LocalDefId> = ::alloc::vec::Vec::new()vec![],
1398 proc_macro_decls: Option<LocalDefId> = None,
1399}
1400
1401impl<'tcx> ItemCollector<'tcx> {
1402 fn new(tcx: TyCtxt<'tcx>, crate_collector: bool) -> ItemCollector<'tcx> {
1403 ItemCollector { crate_collector, tcx, .. }
1404 }
1405}
1406
1407impl<'hir> Visitor<'hir> for ItemCollector<'hir> {
1408 type NestedFilter = nested_filter::All;
1409
1410 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
1411 self.tcx
1412 }
1413
1414 fn visit_item(&mut self, item: &'hir Item<'hir>) {
1415 if Node::Item(item).associated_body().is_some() {
1416 self.body_owners.push(item.owner_id.def_id);
1417 }
1418
1419 let item_id = item.item_id();
1420
1421 if self.crate_collector
1422 && self.proc_macro_decls.is_none()
1423 && {
{
'done:
{
for i in
::rustc_attr_ir::HasAttrs::get_attrs(item_id.hir_id(),
&self.tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcProcMacroDecls) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(self.tcx, item_id.hir_id(), RustcProcMacroDecls)
1424 {
1425 self.proc_macro_decls = Some(item_id.owner_id.def_id);
1426 }
1427
1428 self.items.push(item_id);
1429
1430 if let ItemKind::Static(..) | ItemKind::Fn { .. } | ItemKind::Macro(..) = &item.kind
1431 && item.eii
1432 {
1433 self.eiis.push(item.owner_id.def_id)
1434 }
1435
1436 if let ItemKind::Mod(_, module) = &item.kind {
1438 self.submodules.push(LocalModId::new_unchecked(item.owner_id.def_id));
1439 if self.crate_collector {
1441 intravisit::walk_mod(self, module);
1442 }
1443 } else {
1444 intravisit::walk_item(self, item)
1445 }
1446 }
1447
1448 fn visit_foreign_item(&mut self, item: &'hir ForeignItem<'hir>) {
1449 self.foreign_items.push(item.foreign_item_id());
1450 intravisit::walk_foreign_item(self, item)
1451 }
1452
1453 fn visit_anon_const(&mut self, c: &'hir AnonConst) {
1454 self.body_owners.push(c.def_id);
1455 intravisit::walk_anon_const(self, c)
1456 }
1457
1458 fn visit_inline_const(&mut self, c: &'hir ConstBlock) {
1459 self.body_owners.push(c.def_id);
1460 self.nested_bodies.push(c.def_id);
1461 intravisit::walk_inline_const(self, c)
1462 }
1463
1464 fn visit_opaque_ty(&mut self, o: &'hir OpaqueTy<'hir>) {
1465 self.opaques.push(o.def_id);
1466 intravisit::walk_opaque_ty(self, o)
1467 }
1468
1469 fn visit_expr(&mut self, ex: &'hir Expr<'hir>) {
1470 if let ExprKind::Closure(closure) = ex.kind {
1471 self.body_owners.push(closure.def_id);
1472 self.nested_bodies.push(closure.def_id);
1473 }
1474 intravisit::walk_expr(self, ex)
1475 }
1476
1477 fn visit_trait_item(&mut self, item: &'hir TraitItem<'hir>) {
1478 if Node::TraitItem(item).associated_body().is_some() {
1479 self.body_owners.push(item.owner_id.def_id);
1480 }
1481
1482 self.trait_items.push(item.trait_item_id());
1483
1484 intravisit::walk_trait_item(self, item)
1485 }
1486
1487 fn visit_impl_item(&mut self, item: &'hir ImplItem<'hir>) {
1488 if Node::ImplItem(item).associated_body().is_some() {
1489 self.body_owners.push(item.owner_id.def_id);
1490 }
1491
1492 self.impl_items.push(item.impl_item_id());
1493
1494 intravisit::walk_impl_item(self, item)
1495 }
1496}