1use std::mem;
7use std::ops::ControlFlow;
8
9use hir::def_id::{LocalDefIdMap, LocalDefIdSet};
10use rustc_abi::FieldIdx;
11use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
12use rustc_errors::{ErrorGuaranteed, MultiSpan};
13use rustc_hir::def::{CtorOf, DefKind, Res};
14use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId};
15use rustc_hir::intravisit::{self, Visitor};
16use rustc_hir::{self as hir, ForeignItemId, ItemId, Node, PatKind, QPath, find_attr};
17use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
18use rustc_middle::middle::dead_code::{DeadCodeLivenessSnapshot, DeadCodeLivenessSummary};
19use rustc_middle::middle::privacy::Level;
20use rustc_middle::query::Providers;
21use rustc_middle::ty::{self, AssocTag, TyCtxt};
22use rustc_middle::{bug, span_bug};
23use rustc_session::config::CrateType;
24use rustc_session::lint::builtin::{DEAD_CODE, DEAD_CODE_PUB_IN_BINARY};
25use rustc_session::lint::{self, Lint, StableLintExpectationId};
26use rustc_span::{Symbol, kw};
27
28use crate::errors::{
29 ChangeFields, DeadCodePubInBinaryNote, IgnoredDerivedImpls, MultipleDeadCodes, ParentInfo,
30 UselessAssignment,
31};
32
33fn should_explore(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
37 match tcx.def_kind(def_id) {
38 DefKind::Mod
39 | DefKind::Struct
40 | DefKind::Union
41 | DefKind::Enum
42 | DefKind::Variant
43 | DefKind::Trait
44 | DefKind::TyAlias
45 | DefKind::ForeignTy
46 | DefKind::TraitAlias
47 | DefKind::AssocTy
48 | DefKind::Fn
49 | DefKind::Const { .. }
50 | DefKind::Static { .. }
51 | DefKind::AssocFn
52 | DefKind::AssocConst { .. }
53 | DefKind::Macro(_)
54 | DefKind::GlobalAsm
55 | DefKind::Impl { .. }
56 | DefKind::OpaqueTy
57 | DefKind::AnonConst
58 | DefKind::InlineConst
59 | DefKind::ExternCrate
60 | DefKind::Use
61 | DefKind::Ctor(..)
62 | DefKind::ForeignMod => true,
63
64 DefKind::TyParam
65 | DefKind::ConstParam
66 | DefKind::Field
67 | DefKind::LifetimeParam
68 | DefKind::Closure
69 | DefKind::SyntheticCoroutineBody => false,
70 }
71}
72
73#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ComesFromAllowExpect {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ComesFromAllowExpect::Yes => "Yes",
ComesFromAllowExpect::No => "No",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for ComesFromAllowExpect { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ComesFromAllowExpect {
#[inline]
fn clone(&self) -> ComesFromAllowExpect { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::Eq for ComesFromAllowExpect {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for ComesFromAllowExpect {
#[inline]
fn eq(&self, other: &ComesFromAllowExpect) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::hash::Hash for ComesFromAllowExpect {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state)
}
}Hash)]
76enum ComesFromAllowExpect {
77 Yes,
78 No,
79}
80
81#[derive(#[automatically_derived]
impl ::core::fmt::Debug for WorkItem {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "WorkItem",
"id", &self.id, "propagated", &self.propagated, "own", &&self.own)
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for WorkItem { }Copy, #[automatically_derived]
impl ::core::clone::Clone for WorkItem {
#[inline]
fn clone(&self) -> WorkItem {
let _: ::core::clone::AssertParamIsClone<LocalDefId>;
let _: ::core::clone::AssertParamIsClone<ComesFromAllowExpect>;
*self
}
}Clone, #[automatically_derived]
impl ::core::cmp::Eq for WorkItem {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<LocalDefId>;
let _: ::core::cmp::AssertParamIsEq<ComesFromAllowExpect>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for WorkItem {
#[inline]
fn eq(&self, other: &WorkItem) -> bool {
self.id == other.id && self.propagated == other.propagated &&
self.own == other.own
}
}PartialEq, #[automatically_derived]
impl ::core::hash::Hash for WorkItem {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.id, state);
::core::hash::Hash::hash(&self.propagated, state);
::core::hash::Hash::hash(&self.own, state)
}
}Hash)]
110struct WorkItem {
111 id: LocalDefId,
112 propagated: ComesFromAllowExpect,
113 own: ComesFromAllowExpect,
114}
115
116struct MarkSymbolVisitor<'tcx> {
117 worklist: Vec<WorkItem>,
118 tcx: TyCtxt<'tcx>,
119 maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
120 scanned: FxHashSet<(LocalDefId, ComesFromAllowExpect)>,
121 live_symbols: LocalDefIdSet,
122 repr_unconditionally_treats_fields_as_live: bool,
123 repr_has_repr_simd: bool,
124 in_pat: bool,
125 ignore_variant_stack: Vec<DefId>,
126 ignored_derived_traits: LocalDefIdMap<FxIndexSet<DefId>>,
130 propagated_comes_from_allow_expect: ComesFromAllowExpect,
131}
132
133impl<'tcx> MarkSymbolVisitor<'tcx> {
134 #[track_caller]
138 fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
139 self.maybe_typeck_results
140 .expect("`MarkSymbolVisitor::typeck_results` called outside of body")
141 }
142
143 fn own_comes_from_allow_expect(&self, def_id: LocalDefId) -> ComesFromAllowExpect {
147 if self.propagated_comes_from_allow_expect == ComesFromAllowExpect::Yes
148 && let Some(ComesFromAllowExpect::Yes) =
149 has_allow_dead_code_or_lang_attr(self.tcx, def_id)
150 {
151 ComesFromAllowExpect::Yes
152 } else {
153 ComesFromAllowExpect::No
154 }
155 }
156
157 fn check_def_id(&mut self, def_id: DefId) {
158 if let Some(def_id) = def_id.as_local() {
159 let own_comes_from_allow_expect = self.own_comes_from_allow_expect(def_id);
160
161 if should_explore(self.tcx, def_id) {
162 self.worklist.push(WorkItem {
163 id: def_id,
164 propagated: self.propagated_comes_from_allow_expect,
165 own: own_comes_from_allow_expect,
166 });
167 }
168
169 if own_comes_from_allow_expect == ComesFromAllowExpect::No {
170 self.live_symbols.insert(def_id);
171 }
172 }
173 }
174
175 fn insert_def_id(&mut self, def_id: DefId) {
176 if let Some(def_id) = def_id.as_local() {
177 if true {
if !!should_explore(self.tcx, def_id) {
::core::panicking::panic("assertion failed: !should_explore(self.tcx, def_id)")
};
};debug_assert!(!should_explore(self.tcx, def_id));
178
179 if self.own_comes_from_allow_expect(def_id) == ComesFromAllowExpect::No {
180 self.live_symbols.insert(def_id);
181 }
182 }
183 }
184
185 fn handle_res(&mut self, res: Res) {
186 match res {
187 Res::PrimTy(..) | Res::SelfCtor(..) | Res::Local(..) => {}
188 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), ctor_def_id) => {
189 if self.in_pat {
192 return;
193 }
194 let variant_id = self.tcx.parent(ctor_def_id);
195 let enum_id = self.tcx.parent(variant_id);
196 self.check_def_id(enum_id);
197 if !self.ignore_variant_stack.contains(&ctor_def_id) {
198 self.check_def_id(variant_id);
199 }
200 }
201 Res::Def(DefKind::Variant, variant_id) => {
202 if self.in_pat {
205 return;
206 }
207 let enum_id = self.tcx.parent(variant_id);
208 self.check_def_id(enum_id);
209 if !self.ignore_variant_stack.contains(&variant_id) {
210 self.check_def_id(variant_id);
211 }
212 }
213 Res::Def(_, def_id) => self.check_def_id(def_id),
214 Res::SelfTyParam { trait_: t } => self.check_def_id(t),
215 Res::SelfTyAlias { alias_to: i, .. } => self.check_def_id(i),
216 Res::ToolMod | Res::NonMacroAttr(..) | Res::OpenMod(..) | Res::Err => {}
217 }
218 }
219
220 fn lookup_and_handle_method(&mut self, id: hir::HirId) {
221 if let Some(def_id) = self.typeck_results().type_dependent_def_id(id) {
222 self.check_def_id(def_id);
223 } else {
224 if !self.typeck_results().tainted_by_errors.is_some() {
{
::core::panicking::panic_fmt(format_args!("no type-dependent def for method"));
}
};assert!(
225 self.typeck_results().tainted_by_errors.is_some(),
226 "no type-dependent def for method"
227 );
228 }
229 }
230
231 fn handle_field_access(&mut self, lhs: &hir::Expr<'_>, hir_id: hir::HirId) {
232 match self.typeck_results().expr_ty_adjusted(lhs).kind() {
233 ty::Adt(def, _) => {
234 let index = self.typeck_results().field_index(hir_id);
235 self.insert_def_id(def.non_enum_variant().fields[index].did);
236 }
237 ty::Tuple(..) => {}
238 ty::Error(_) => {}
239 kind => ::rustc_middle::util::bug::span_bug_fmt(lhs.span,
format_args!("named field access on non-ADT: {0:?}", kind))span_bug!(lhs.span, "named field access on non-ADT: {kind:?}"),
240 }
241 }
242
243 fn handle_assign(&mut self, expr: &'tcx hir::Expr<'tcx>) {
244 if self
245 .typeck_results()
246 .expr_adjustments(expr)
247 .iter()
248 .any(|adj| #[allow(non_exhaustive_omitted_patterns)] match adj.kind {
ty::adjustment::Adjust::Deref(_) => true,
_ => false,
}matches!(adj.kind, ty::adjustment::Adjust::Deref(_)))
249 {
250 let _ = self.visit_expr(expr);
251 } else if let hir::ExprKind::Field(base, ..) = expr.kind {
252 self.handle_assign(base);
254 } else {
255 let _ = self.visit_expr(expr);
256 }
257 }
258
259 fn check_for_self_assign(&mut self, assign: &'tcx hir::Expr<'tcx>) {
260 fn check_for_self_assign_helper<'tcx>(
261 typeck_results: &'tcx ty::TypeckResults<'tcx>,
262 lhs: &'tcx hir::Expr<'tcx>,
263 rhs: &'tcx hir::Expr<'tcx>,
264 ) -> bool {
265 match (&lhs.kind, &rhs.kind) {
266 (hir::ExprKind::Path(qpath_l), hir::ExprKind::Path(qpath_r)) => {
267 if let (Res::Local(id_l), Res::Local(id_r)) = (
268 typeck_results.qpath_res(qpath_l, lhs.hir_id),
269 typeck_results.qpath_res(qpath_r, rhs.hir_id),
270 ) {
271 if id_l == id_r {
272 return true;
273 }
274 }
275 return false;
276 }
277 (hir::ExprKind::Field(lhs_l, ident_l), hir::ExprKind::Field(lhs_r, ident_r)) => {
278 if ident_l == ident_r {
279 return check_for_self_assign_helper(typeck_results, lhs_l, lhs_r);
280 }
281 return false;
282 }
283 _ => {
284 return false;
285 }
286 }
287 }
288
289 if let hir::ExprKind::Assign(lhs, rhs, _) = assign.kind
290 && check_for_self_assign_helper(self.typeck_results(), lhs, rhs)
291 && !assign.span.from_expansion()
292 {
293 let is_field_assign = #[allow(non_exhaustive_omitted_patterns)] match lhs.kind {
hir::ExprKind::Field(..) => true,
_ => false,
}matches!(lhs.kind, hir::ExprKind::Field(..));
294 self.tcx.emit_node_span_lint(
295 lint::builtin::DEAD_CODE,
296 assign.hir_id,
297 assign.span,
298 UselessAssignment { is_field_assign, ty: self.typeck_results().expr_ty(lhs) },
299 )
300 }
301 }
302
303 fn handle_field_pattern_match(
304 &mut self,
305 lhs: &hir::Pat<'_>,
306 res: Res,
307 pats: &[hir::PatField<'_>],
308 ) {
309 let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
310 ty::Adt(adt, _) => {
311 self.check_def_id(adt.did());
316 adt.variant_of_res(res)
317 }
318 _ => ::rustc_middle::util::bug::span_bug_fmt(lhs.span,
format_args!("non-ADT in struct pattern"))span_bug!(lhs.span, "non-ADT in struct pattern"),
319 };
320 for pat in pats {
321 if let PatKind::Wild = pat.pat.kind {
322 continue;
323 }
324 let index = self.typeck_results().field_index(pat.hir_id);
325 self.insert_def_id(variant.fields[index].did);
326 }
327 }
328
329 fn handle_tuple_field_pattern_match(
330 &mut self,
331 lhs: &hir::Pat<'_>,
332 res: Res,
333 pats: &[hir::Pat<'_>],
334 dotdot: hir::DotDotPos,
335 ) {
336 let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
337 ty::Adt(adt, _) => {
338 self.check_def_id(adt.did());
340 adt.variant_of_res(res)
341 }
342 _ => {
343 self.tcx.dcx().span_delayed_bug(lhs.span, "non-ADT in tuple struct pattern");
344 return;
345 }
346 };
347 let dotdot = dotdot.as_opt_usize().unwrap_or(pats.len());
348 let first_n = pats.iter().enumerate().take(dotdot);
349 let missing = variant.fields.len() - pats.len();
350 let last_n = pats.iter().enumerate().skip(dotdot).map(|(idx, pat)| (idx + missing, pat));
351 for (idx, pat) in first_n.chain(last_n) {
352 if let PatKind::Wild = pat.kind {
353 continue;
354 }
355 self.insert_def_id(variant.fields[FieldIdx::from_usize(idx)].did);
356 }
357 }
358
359 fn handle_offset_of(&mut self, expr: &'tcx hir::Expr<'tcx>) {
360 let indices = self
361 .typeck_results()
362 .offset_of_data()
363 .get(expr.hir_id)
364 .expect("no offset_of_data for offset_of");
365
366 for &(current_ty, variant, field) in indices {
367 match current_ty.kind() {
368 ty::Adt(def, _) => {
369 let field = &def.variant(variant).fields[field];
370 self.insert_def_id(field.did);
371 }
372 ty::Tuple(_) => {}
375 _ => ::rustc_middle::util::bug::span_bug_fmt(expr.span,
format_args!("named field access on non-ADT"))span_bug!(expr.span, "named field access on non-ADT"),
376 }
377 }
378 }
379
380 fn mark_live_symbols(&mut self) -> <MarkSymbolVisitor<'tcx> as Visitor<'tcx>>::Result {
381 while let Some(work) = self.worklist.pop() {
382 let WorkItem { mut id, propagated, own } = work;
383 self.propagated_comes_from_allow_expect = propagated;
384
385 if let DefKind::Ctor(..) = self.tcx.def_kind(id) {
388 id = self.tcx.local_parent(id);
389 }
390
391 match own {
413 ComesFromAllowExpect::Yes => {}
414 ComesFromAllowExpect::No => {
415 self.live_symbols.insert(id);
416 }
417 }
418
419 if !self.scanned.insert((id, propagated)) {
420 continue;
421 }
422
423 if self.tcx.is_impl_trait_in_trait(id.to_def_id()) {
425 self.live_symbols.insert(id);
426 continue;
427 }
428
429 self.visit_node(self.tcx.hir_node_by_def_id(id))?;
430 }
431
432 ControlFlow::Continue(())
433 }
434
435 fn should_ignore_impl_item(&mut self, impl_item: &hir::ImplItem<'_>) -> bool {
439 if let hir::ImplItemImplKind::Trait { .. } = impl_item.impl_kind
440 && let impl_of = self.tcx.local_parent(impl_item.owner_id.def_id)
441 && self.tcx.is_automatically_derived(impl_of.to_def_id())
442 && let trait_ref =
443 self.tcx.impl_trait_ref(impl_of).instantiate_identity().skip_norm_wip()
444 && {
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(trait_ref.def_id,
&self.tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcTrivialFieldReads) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(self.tcx, trait_ref.def_id, RustcTrivialFieldReads)
445 {
446 if let ty::Adt(adt_def, _) = trait_ref.self_ty().kind()
447 && let Some(adt_def_id) = adt_def.did().as_local()
448 {
449 self.ignored_derived_traits.entry(adt_def_id).or_default().insert(trait_ref.def_id);
450 }
451 return true;
452 }
453
454 false
455 }
456
457 fn visit_node(
458 &mut self,
459 node: Node<'tcx>,
460 ) -> <MarkSymbolVisitor<'tcx> as Visitor<'tcx>>::Result {
461 if let Node::ImplItem(impl_item) = node
462 && self.should_ignore_impl_item(impl_item)
463 {
464 return ControlFlow::Continue(());
465 }
466
467 let unconditionally_treated_fields_as_live =
468 self.repr_unconditionally_treats_fields_as_live;
469 let had_repr_simd = self.repr_has_repr_simd;
470 self.repr_unconditionally_treats_fields_as_live = false;
471 self.repr_has_repr_simd = false;
472 let walk_result = match node {
473 Node::Item(item) => match item.kind {
474 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
475 let def = self.tcx.adt_def(item.owner_id);
476 self.repr_unconditionally_treats_fields_as_live =
477 def.repr().c() || def.repr().transparent();
478 self.repr_has_repr_simd = def.repr().simd();
479
480 intravisit::walk_item(self, item)
481 }
482 hir::ItemKind::ForeignMod { .. } => ControlFlow::Continue(()),
483 hir::ItemKind::Trait { items: trait_item_refs, .. } => {
484 for trait_item in trait_item_refs {
486 if self.tcx.def_kind(trait_item.owner_id) == DefKind::AssocTy {
487 self.check_def_id(trait_item.owner_id.to_def_id());
488 }
489 }
490 intravisit::walk_item(self, item)
491 }
492 _ => intravisit::walk_item(self, item),
493 },
494 Node::TraitItem(trait_item) => {
495 let trait_item_id = trait_item.owner_id.to_def_id();
497 if let Some(trait_id) = self.tcx.trait_of_assoc(trait_item_id) {
498 self.check_def_id(trait_id);
499 }
500 intravisit::walk_trait_item(self, trait_item)
501 }
502 Node::ImplItem(impl_item) => {
503 let item = self.tcx.local_parent(impl_item.owner_id.def_id);
504 if let hir::ImplItemImplKind::Inherent { .. } = impl_item.impl_kind {
505 let self_ty = self.tcx.type_of(item).instantiate_identity().skip_norm_wip();
510 match *self_ty.kind() {
511 ty::Adt(def, _) => self.check_def_id(def.did()),
512 ty::Foreign(did) => self.check_def_id(did),
513 ty::Dynamic(data, ..) => {
514 if let Some(def_id) = data.principal_def_id() {
515 self.check_def_id(def_id)
516 }
517 }
518 _ => {}
519 }
520 }
521 intravisit::walk_impl_item(self, impl_item)
522 }
523 Node::ForeignItem(foreign_item) => intravisit::walk_foreign_item(self, foreign_item),
524 Node::OpaqueTy(opaq) => intravisit::walk_opaque_ty(self, opaq),
525 _ => ControlFlow::Continue(()),
526 };
527 self.repr_has_repr_simd = had_repr_simd;
528 self.repr_unconditionally_treats_fields_as_live = unconditionally_treated_fields_as_live;
529
530 walk_result
531 }
532
533 fn mark_as_used_if_union(&mut self, adt: ty::AdtDef<'tcx>, fields: &[hir::ExprField<'_>]) {
534 if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did().is_local() {
535 for field in fields {
536 let index = self.typeck_results().field_index(field.hir_id);
537 self.insert_def_id(adt.non_enum_variant().fields[index].did);
538 }
539 }
540 }
541
542 fn check_impl_or_impl_item_live(&mut self, local_def_id: LocalDefId) -> bool {
547 let (impl_block_id, trait_def_id) = match self.tcx.def_kind(local_def_id) {
548 DefKind::AssocConst { .. } | DefKind::AssocTy | DefKind::AssocFn => {
550 let trait_item_id =
551 self.tcx.trait_item_of(local_def_id).and_then(|def_id| def_id.as_local());
552 (self.tcx.local_parent(local_def_id), trait_item_id)
553 }
554 DefKind::Impl { of_trait: true } => {
556 (local_def_id, self.tcx.impl_trait_id(local_def_id).as_local())
557 }
558 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
559 };
560
561 if let Some(trait_def_id) = trait_def_id
562 && !self.live_symbols.contains(&trait_def_id)
563 {
564 return false;
565 }
566
567 if let ty::Adt(adt, _) =
569 self.tcx.type_of(impl_block_id).instantiate_identity().skip_norm_wip().kind()
570 && let Some(adt_def_id) = adt.did().as_local()
571 && !self.live_symbols.contains(&adt_def_id)
572 {
573 return false;
574 }
575
576 true
577 }
578}
579
580impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
581 type Result = ControlFlow<ErrorGuaranteed>;
582
583 fn visit_nested_body(&mut self, body: hir::BodyId) -> Self::Result {
584 let typeck_results = self.tcx.typeck_body(body);
585
586 if let Some(guar) = typeck_results.tainted_by_errors {
588 return ControlFlow::Break(guar);
589 }
590
591 let old_maybe_typeck_results = self.maybe_typeck_results.replace(typeck_results);
592 let body = self.tcx.hir_body(body);
593 let result = self.visit_body(body);
594 self.maybe_typeck_results = old_maybe_typeck_results;
595
596 result
597 }
598
599 fn visit_variant_data(&mut self, def: &'tcx hir::VariantData<'tcx>) -> Self::Result {
600 let tcx = self.tcx;
601 let unconditionally_treat_fields_as_live = self.repr_unconditionally_treats_fields_as_live;
602 let has_repr_simd = self.repr_has_repr_simd;
603 let effective_visibilities = &tcx.effective_visibilities(());
604 let live_fields = def.fields().iter().filter_map(|f| {
605 let def_id = f.def_id;
606 if unconditionally_treat_fields_as_live || (f.is_positional() && has_repr_simd) {
607 return Some(def_id);
608 }
609 if !effective_visibilities.is_reachable(f.hir_id.owner.def_id) {
610 return None;
611 }
612 if effective_visibilities.is_reachable(def_id) { Some(def_id) } else { None }
613 });
614 self.live_symbols.extend(live_fields);
615
616 intravisit::walk_struct_def(self, def)
617 }
618
619 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) -> Self::Result {
620 match expr.kind {
621 hir::ExprKind::Path(ref qpath @ QPath::TypeRelative(..)) => {
622 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
623 self.handle_res(res);
624 }
625 hir::ExprKind::MethodCall(..) => {
626 self.lookup_and_handle_method(expr.hir_id);
627 }
628 hir::ExprKind::Field(ref lhs, ..) => {
629 if self.typeck_results().opt_field_index(expr.hir_id).is_some() {
630 self.handle_field_access(lhs, expr.hir_id);
631 } else {
632 self.tcx.dcx().span_delayed_bug(expr.span, "couldn't resolve index for field");
633 }
634 }
635 hir::ExprKind::Struct(qpath, fields, _) => {
636 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
637 self.handle_res(res);
638 if let ty::Adt(adt, _) = self.typeck_results().expr_ty(expr).kind() {
639 self.mark_as_used_if_union(*adt, fields);
640 }
641 }
642 hir::ExprKind::Closure(cls) => {
643 self.insert_def_id(cls.def_id.to_def_id());
644 }
645 hir::ExprKind::OffsetOf(..) => {
646 self.handle_offset_of(expr);
647 }
648 hir::ExprKind::Assign(ref lhs, ..) => {
649 self.handle_assign(lhs);
650 self.check_for_self_assign(expr);
651 }
652 _ => (),
653 }
654
655 intravisit::walk_expr(self, expr)
656 }
657
658 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) -> Self::Result {
659 let len = self.ignore_variant_stack.len();
663 self.ignore_variant_stack.extend(arm.pat.necessary_variants());
664 let result = intravisit::walk_arm(self, arm);
665 self.ignore_variant_stack.truncate(len);
666
667 result
668 }
669
670 fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Self::Result {
671 self.in_pat = true;
672 match pat.kind {
673 PatKind::Struct(ref path, fields, _) => {
674 let res = self.typeck_results().qpath_res(path, pat.hir_id);
675 self.handle_field_pattern_match(pat, res, fields);
676 }
677 PatKind::TupleStruct(ref qpath, fields, dotdot) => {
678 let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
679 self.handle_tuple_field_pattern_match(pat, res, fields, dotdot);
680 }
681 _ => (),
682 }
683
684 let result = intravisit::walk_pat(self, pat);
685 self.in_pat = false;
686
687 result
688 }
689
690 fn visit_pat_expr(&mut self, expr: &'tcx rustc_hir::PatExpr<'tcx>) -> Self::Result {
691 match &expr.kind {
692 rustc_hir::PatExprKind::Path(qpath) => {
693 if let ty::Adt(adt, _) = self.typeck_results().node_type(expr.hir_id).kind() {
695 self.check_def_id(adt.did());
696 }
697
698 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
699 self.handle_res(res);
700 }
701 _ => {}
702 }
703 intravisit::walk_pat_expr(self, expr)
704 }
705
706 fn visit_path(&mut self, path: &hir::Path<'tcx>, _: hir::HirId) -> Self::Result {
707 self.handle_res(path.res);
708 intravisit::walk_path(self, path)
709 }
710
711 fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) -> Self::Result {
712 let in_pat = mem::replace(&mut self.in_pat, false);
715
716 self.live_symbols.insert(c.def_id);
717 let result = intravisit::walk_anon_const(self, c);
718
719 self.in_pat = in_pat;
720
721 result
722 }
723
724 fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) -> Self::Result {
725 let in_pat = mem::replace(&mut self.in_pat, false);
728
729 self.live_symbols.insert(c.def_id);
730 let result = intravisit::walk_inline_const(self, c);
731
732 self.in_pat = in_pat;
733
734 result
735 }
736
737 fn visit_trait_ref(&mut self, t: &'tcx hir::TraitRef<'tcx>) -> Self::Result {
738 if let Some(trait_def_id) = t.path.res.opt_def_id()
739 && let Some(segment) = t.path.segments.last()
740 && let Some(args) = segment.args
741 {
742 for constraint in args.constraints {
743 if let Some(local_def_id) = self
744 .tcx
745 .associated_items(trait_def_id)
746 .find_by_ident_and_kind(
747 self.tcx,
748 constraint.ident,
749 AssocTag::Const,
750 trait_def_id,
751 )
752 .and_then(|item| item.def_id.as_local())
753 {
754 self.worklist.push(WorkItem {
755 id: local_def_id,
756 propagated: ComesFromAllowExpect::No,
757 own: ComesFromAllowExpect::No,
758 });
759 }
760 }
761 }
762
763 intravisit::walk_trait_ref(self, t)
764 }
765}
766
767fn has_allow_dead_code_or_lang_attr(
768 tcx: TyCtxt<'_>,
769 def_id: LocalDefId,
770) -> Option<ComesFromAllowExpect> {
771 fn has_allow_expect_dead_code(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
772 let hir_id = tcx.local_def_id_to_hir_id(def_id);
773 let lint_level = tcx.lint_level_spec_at_node(lint::builtin::DEAD_CODE, hir_id).level();
774 #[allow(non_exhaustive_omitted_patterns)] match lint_level {
lint::Allow | lint::Expect => true,
_ => false,
}matches!(lint_level, lint::Allow | lint::Expect)
775 }
776
777 fn has_used_like_attr(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
778 tcx.def_kind(def_id).has_codegen_attrs() && {
779 let cg_attrs = tcx.codegen_fn_attrs(def_id);
780
781 cg_attrs.contains_extern_indicator()
784 || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)
785 || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)
786 }
787 }
788
789 if has_allow_expect_dead_code(tcx, def_id) {
790 Some(ComesFromAllowExpect::Yes)
791 } else if has_used_like_attr(tcx, def_id) || {
{
'done:
{
for i in ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &tcx)
{
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(Lang(..)) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(tcx, def_id, Lang(..)) {
792 Some(ComesFromAllowExpect::No)
793 } else {
794 None
795 }
796}
797
798fn maybe_record_as_seed<'tcx>(
814 tcx: TyCtxt<'tcx>,
815 owner_id: hir::OwnerId,
816 push_into_worklist: &mut impl FnMut(WorkItem),
817 unsolved_items: &mut Vec<LocalDefId>,
818) {
819 let allow_dead_code = has_allow_dead_code_or_lang_attr(tcx, owner_id.def_id);
820 if let Some(comes_from_allow) = allow_dead_code {
821 push_into_worklist(WorkItem {
822 id: owner_id.def_id,
823 propagated: comes_from_allow,
824 own: comes_from_allow,
825 });
826 }
827
828 match tcx.def_kind(owner_id) {
829 DefKind::Enum => {
830 if let Some(comes_from_allow) = allow_dead_code {
831 let adt = tcx.adt_def(owner_id);
832 for variant in adt.variants().iter() {
833 push_into_worklist(WorkItem {
834 id: variant.def_id.expect_local(),
835 propagated: comes_from_allow,
836 own: comes_from_allow,
837 });
838 }
839 }
840 }
841 DefKind::AssocFn | DefKind::AssocConst { .. } | DefKind::AssocTy => {
842 if allow_dead_code.is_none() {
843 let parent = tcx.local_parent(owner_id.def_id);
844 match tcx.def_kind(parent) {
845 DefKind::Impl { of_trait: false } | DefKind::Trait => {}
846 DefKind::Impl { of_trait: true } => {
847 if let Some(trait_item_def_id) =
848 tcx.associated_item(owner_id.def_id).trait_item_def_id()
849 && let Some(trait_item_local_def_id) = trait_item_def_id.as_local()
850 && let Some(comes_from_allow) =
851 has_allow_dead_code_or_lang_attr(tcx, trait_item_local_def_id)
852 {
853 push_into_worklist(WorkItem {
854 id: owner_id.def_id,
855 propagated: comes_from_allow,
856 own: comes_from_allow,
857 });
858 }
859
860 unsolved_items.push(owner_id.def_id);
866 }
867 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
868 }
869 }
870 }
871 DefKind::Impl { of_trait: true } => {
872 if allow_dead_code.is_none() {
873 if let Some(trait_def_id) =
874 tcx.impl_trait_ref(owner_id.def_id).skip_binder().def_id.as_local()
875 && let Some(comes_from_allow) =
876 has_allow_dead_code_or_lang_attr(tcx, trait_def_id)
877 {
878 push_into_worklist(WorkItem {
879 id: owner_id.def_id,
880 propagated: comes_from_allow,
881 own: comes_from_allow,
882 });
883 }
884
885 unsolved_items.push(owner_id.def_id);
886 }
887 }
888 DefKind::GlobalAsm => {
889 push_into_worklist(WorkItem {
891 id: owner_id.def_id,
892 propagated: ComesFromAllowExpect::No,
893 own: ComesFromAllowExpect::No,
894 });
895 }
896 DefKind::Const { .. } => {
897 if tcx.item_name(owner_id.def_id) == kw::Underscore {
898 push_into_worklist(WorkItem {
902 id: owner_id.def_id,
903 propagated: ComesFromAllowExpect::No,
904 own: ComesFromAllowExpect::No,
905 });
906 }
907 }
908 _ => {}
909 }
910}
911
912struct SeedWorklists {
913 worklist: Vec<WorkItem>,
914 deferred_seeds: Vec<WorkItem>,
915 unsolved_items: Vec<LocalDefId>,
916}
917
918fn create_and_seed_worklist(tcx: TyCtxt<'_>) -> SeedWorklists {
919 let mut unsolved_items = Vec::new();
920 let mut deferred_seeds = Vec::new();
921 let mut worklist = Vec::new();
922
923 if let Some((def_id, _)) = tcx.entry_fn(())
924 && let Some(local_def_id) = def_id.as_local()
925 {
926 worklist.push(WorkItem {
927 id: local_def_id,
928 propagated: ComesFromAllowExpect::No,
929 own: ComesFromAllowExpect::No,
930 });
931 }
932
933 for (id, effective_vis) in tcx.effective_visibilities(()).iter() {
934 if effective_vis.is_public_at_level(Level::Reachable) {
935 deferred_seeds.push(WorkItem {
936 id: *id,
937 propagated: ComesFromAllowExpect::No,
938 own: ComesFromAllowExpect::No,
939 });
940 }
941 }
942
943 let mut push_into_worklist = |work_item: WorkItem| match work_item.own {
944 ComesFromAllowExpect::Yes => deferred_seeds.push(work_item),
945 ComesFromAllowExpect::No => worklist.push(work_item),
946 };
947 let crate_items = tcx.hir_crate_items(());
948 for id in crate_items.owners() {
949 maybe_record_as_seed(tcx, id, &mut push_into_worklist, &mut unsolved_items);
950 }
951
952 SeedWorklists { worklist, deferred_seeds, unsolved_items }
953}
954
955fn live_symbols_and_ignored_derived_traits(
956 tcx: TyCtxt<'_>,
957 (): (),
958) -> Result<DeadCodeLivenessSummary, ErrorGuaranteed> {
959 let SeedWorklists { worklist, deferred_seeds, mut unsolved_items } =
960 create_and_seed_worklist(tcx);
961 let mut symbol_visitor = MarkSymbolVisitor {
962 worklist,
963 tcx,
964 maybe_typeck_results: None,
965 scanned: Default::default(),
966 live_symbols: Default::default(),
967 repr_unconditionally_treats_fields_as_live: false,
968 repr_has_repr_simd: false,
969 in_pat: false,
970 ignore_variant_stack: ::alloc::vec::Vec::new()vec![],
971 ignored_derived_traits: Default::default(),
972 propagated_comes_from_allow_expect: ComesFromAllowExpect::No,
973 };
974 mark_live_symbols_and_ignored_derived_traits(&mut symbol_visitor, &mut unsolved_items)?;
975 let pre_deferred_seeding = DeadCodeLivenessSnapshot {
976 live_symbols: symbol_visitor.live_symbols.clone(),
977 ignored_derived_traits: symbol_visitor.ignored_derived_traits.clone(),
978 };
979
980 symbol_visitor.worklist.extend(deferred_seeds);
981 mark_live_symbols_and_ignored_derived_traits(&mut symbol_visitor, &mut unsolved_items)?;
982
983 Ok(DeadCodeLivenessSummary {
984 pre_deferred_seeding,
985 final_result: DeadCodeLivenessSnapshot {
986 live_symbols: symbol_visitor.live_symbols,
987 ignored_derived_traits: symbol_visitor.ignored_derived_traits,
988 },
989 })
990}
991
992fn mark_live_symbols_and_ignored_derived_traits(
993 symbol_visitor: &mut MarkSymbolVisitor<'_>,
994 unsolved_items: &mut Vec<LocalDefId>,
995) -> Result<(), ErrorGuaranteed> {
996 if let ControlFlow::Break(guar) = symbol_visitor.mark_live_symbols() {
997 return Err(guar);
998 }
999
1000 let mut items_to_check: Vec<_> = unsolved_items
1003 .extract_if(.., |&mut local_def_id| {
1004 symbol_visitor.check_impl_or_impl_item_live(local_def_id)
1005 })
1006 .collect();
1007
1008 while !items_to_check.is_empty() {
1009 symbol_visitor.worklist.extend(items_to_check.drain(..).map(|id| WorkItem {
1010 id,
1011 propagated: ComesFromAllowExpect::No,
1012 own: ComesFromAllowExpect::No,
1013 }));
1014 if let ControlFlow::Break(guar) = symbol_visitor.mark_live_symbols() {
1015 return Err(guar);
1016 }
1017
1018 items_to_check.extend(unsolved_items.extract_if(.., |&mut local_def_id| {
1019 symbol_visitor.check_impl_or_impl_item_live(local_def_id)
1020 }));
1021 }
1022
1023 Ok(())
1024}
1025
1026struct DeadItem {
1027 def_id: LocalDefId,
1028 name: Symbol,
1029 level_plus: (lint::Level, Option<StableLintExpectationId>),
1030}
1031
1032struct DeadVisitor<'tcx> {
1033 tcx: TyCtxt<'tcx>,
1034 target_lint: &'static Lint,
1035 live_symbols: &'tcx LocalDefIdSet,
1036 ignored_derived_traits: &'tcx LocalDefIdMap<FxIndexSet<DefId>>,
1037}
1038
1039enum ShouldWarnAboutField {
1040 Yes,
1041 No,
1042}
1043
1044#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ReportOn {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ReportOn::TupleField => "TupleField",
ReportOn::NamedField => "NamedField",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for ReportOn { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ReportOn {
#[inline]
fn clone(&self) -> ReportOn { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ReportOn {
#[inline]
fn eq(&self, other: &ReportOn) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ReportOn {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq)]
1045enum ReportOn {
1046 TupleField,
1048 NamedField,
1050}
1051
1052impl<'tcx> DeadVisitor<'tcx> {
1053 fn should_warn_about_field(&mut self, field: &ty::FieldDef) -> ShouldWarnAboutField {
1054 if self.live_symbols.contains(&field.did.expect_local()) {
1055 return ShouldWarnAboutField::No;
1056 }
1057 let field_type = self.tcx.type_of(field.did).instantiate_identity().skip_norm_wip();
1058 if field_type.is_phantom_data() {
1059 return ShouldWarnAboutField::No;
1060 }
1061 let is_positional = field.name.as_str().starts_with(|c: char| c.is_ascii_digit());
1062 if is_positional
1063 && self
1064 .tcx
1065 .layout_of(
1066 ty::TypingEnv::non_body_analysis(self.tcx, field.did)
1067 .as_query_input(field_type),
1068 )
1069 .map_or(true, |layout| layout.is_zst())
1070 {
1071 return ShouldWarnAboutField::No;
1072 }
1073 ShouldWarnAboutField::Yes
1074 }
1075
1076 fn def_lint_level_plus(
1077 &self,
1078 id: LocalDefId,
1079 ) -> (lint::Level, Option<StableLintExpectationId>) {
1080 let hir_id = self.tcx.local_def_id_to_hir_id(id);
1081 let level_spec = self.tcx.lint_level_spec_at_node(self.target_lint, hir_id);
1082 (level_spec.level(), level_spec.lint_id())
1083 }
1084
1085 fn dead_code_pub_in_binary_note(&self) -> Option<DeadCodePubInBinaryNote> {
1086 self.target_lint.name.eq(DEAD_CODE_PUB_IN_BINARY.name).then_some(DeadCodePubInBinaryNote)
1087 }
1088
1089 fn lint_at_single_level(
1096 &self,
1097 dead_codes: &[&DeadItem],
1098 participle: &str,
1099 parent_item: Option<LocalDefId>,
1100 report_on: ReportOn,
1101 ) {
1102 let Some(&first_item) = dead_codes.first() else { return };
1103 let tcx = self.tcx;
1104
1105 let first_lint_level_plus = first_item.level_plus;
1106 if !dead_codes.iter().skip(1).all(|item|
item.level_plus == first_lint_level_plus) {
::core::panicking::panic("assertion failed: dead_codes.iter().skip(1).all(|item| item.level_plus == first_lint_level_plus)")
};assert!(dead_codes.iter().skip(1).all(|item| item.level_plus == first_lint_level_plus));
1107
1108 let names: Vec<_> = dead_codes.iter().map(|item| item.name).collect();
1109 let spans: Vec<_> = dead_codes
1110 .iter()
1111 .map(|item| {
1112 let span = tcx.def_span(item.def_id);
1113 let ident_span = tcx.def_ident_span(item.def_id);
1114 ident_span.map(|s| s.with_ctxt(span.ctxt())).unwrap_or(span)
1116 })
1117 .collect();
1118
1119 let mut descr = tcx.def_descr(first_item.def_id.to_def_id());
1120 if dead_codes.iter().any(|item| tcx.def_descr(item.def_id.to_def_id()) != descr) {
1123 descr = "associated item"
1124 }
1125
1126 let num = dead_codes.len();
1127 let multiple = num > 6;
1128 let name_list = names.into();
1129
1130 let parent_info = parent_item.map(|parent_item| {
1131 let parent_descr = tcx.def_descr(parent_item.to_def_id());
1132 let span = if let DefKind::Impl { .. } = tcx.def_kind(parent_item) {
1133 tcx.def_span(parent_item)
1134 } else {
1135 tcx.def_ident_span(parent_item).unwrap()
1136 };
1137 ParentInfo { num, descr, parent_descr, span }
1138 });
1139
1140 let mut encl_def_id = parent_item.unwrap_or(first_item.def_id);
1141 if let DefKind::Variant = tcx.def_kind(encl_def_id) {
1143 encl_def_id = tcx.local_parent(encl_def_id);
1144 }
1145
1146 let ignored_derived_impls =
1147 self.ignored_derived_traits.get(&encl_def_id).map(|ign_traits| {
1148 let trait_list = ign_traits
1149 .iter()
1150 .map(|trait_id| self.tcx.item_name(*trait_id))
1151 .collect::<Vec<_>>();
1152 let trait_list_len = trait_list.len();
1153 IgnoredDerivedImpls {
1154 name: self.tcx.item_name(encl_def_id.to_def_id()),
1155 trait_list: trait_list.into(),
1156 trait_list_len,
1157 }
1158 });
1159
1160 let diag = match report_on {
1161 ReportOn::TupleField => {
1162 let tuple_fields = if let Some(parent_id) = parent_item
1163 && let node = tcx.hir_node_by_def_id(parent_id)
1164 && let hir::Node::Item(hir::Item {
1165 kind: hir::ItemKind::Struct(_, _, hir::VariantData::Tuple(fields, _, _)),
1166 ..
1167 }) = node
1168 {
1169 *fields
1170 } else {
1171 &[]
1172 };
1173
1174 let trailing_tuple_fields = if tuple_fields.len() >= dead_codes.len() {
1175 LocalDefIdSet::from_iter(
1176 tuple_fields
1177 .iter()
1178 .skip(tuple_fields.len() - dead_codes.len())
1179 .map(|f| f.def_id),
1180 )
1181 } else {
1182 LocalDefIdSet::default()
1183 };
1184
1185 let fields_suggestion =
1186 if dead_codes.iter().all(|dc| trailing_tuple_fields.contains(&dc.def_id)) {
1189 ChangeFields::Remove { num }
1190 } else {
1191 ChangeFields::ChangeToUnitTypeOrRemove { num, spans: spans.clone() }
1192 };
1193
1194 MultipleDeadCodes::UnusedTupleStructFields {
1195 multiple,
1196 num,
1197 descr,
1198 participle,
1199 name_list,
1200 dead_code_pub_in_binary_note: self.dead_code_pub_in_binary_note(),
1201 change_fields_suggestion: fields_suggestion,
1202 parent_info,
1203 ignored_derived_impls,
1204 }
1205 }
1206 ReportOn::NamedField => {
1207 let enum_variants_with_same_name = dead_codes
1208 .iter()
1209 .filter_map(|dead_item| {
1210 if let DefKind::AssocFn | DefKind::AssocConst { .. } =
1211 tcx.def_kind(dead_item.def_id)
1212 && let impl_did = tcx.local_parent(dead_item.def_id)
1213 && let DefKind::Impl { of_trait: false } = tcx.def_kind(impl_did)
1214 && let ty::Adt(maybe_enum, _) =
1215 tcx.type_of(impl_did).instantiate_identity().skip_norm_wip().kind()
1216 && maybe_enum.is_enum()
1217 && let Some(variant) =
1218 maybe_enum.variants().iter().find(|i| i.name == dead_item.name)
1219 {
1220 Some(crate::errors::EnumVariantSameName {
1221 dead_descr: tcx.def_descr(dead_item.def_id.to_def_id()),
1222 dead_name: dead_item.name,
1223 variant_span: tcx.def_span(variant.def_id),
1224 })
1225 } else {
1226 None
1227 }
1228 })
1229 .collect();
1230
1231 MultipleDeadCodes::DeadCodes {
1232 multiple,
1233 num,
1234 descr,
1235 participle,
1236 name_list,
1237 dead_code_pub_in_binary_note: self.dead_code_pub_in_binary_note(),
1238 parent_info,
1239 ignored_derived_impls,
1240 enum_variants_with_same_name,
1241 }
1242 }
1243 };
1244
1245 let hir_id = tcx.local_def_id_to_hir_id(first_item.def_id);
1246 self.tcx.emit_node_span_lint(self.target_lint, hir_id, MultiSpan::from_spans(spans), diag);
1247 }
1248
1249 fn warn_multiple(
1250 &self,
1251 def_id: LocalDefId,
1252 participle: &str,
1253 dead_codes: Vec<DeadItem>,
1254 report_on: ReportOn,
1255 ) {
1256 let mut dead_codes = dead_codes
1257 .iter()
1258 .filter(|v| !v.name.as_str().starts_with('_'))
1259 .collect::<Vec<&DeadItem>>();
1260 if dead_codes.is_empty() {
1261 return;
1262 }
1263 dead_codes.sort_by_key(|v| v.level_plus.0);
1266 for group in dead_codes.chunk_by(|a, b| a.level_plus == b.level_plus) {
1267 self.lint_at_single_level(&group, participle, Some(def_id), report_on);
1268 }
1269 }
1270
1271 fn warn_dead_code(&mut self, id: LocalDefId, participle: &str) {
1272 let item = DeadItem {
1273 def_id: id,
1274 name: self.tcx.item_name(id.to_def_id()),
1275 level_plus: self.def_lint_level_plus(id),
1276 };
1277 self.lint_at_single_level(&[&item], participle, None, ReportOn::NamedField);
1278 }
1279
1280 fn check_definition(&mut self, def_id: LocalDefId) {
1281 if self.is_live_code(def_id) {
1282 return;
1283 }
1284 match self.tcx.def_kind(def_id) {
1285 DefKind::AssocConst { .. }
1286 | DefKind::AssocTy
1287 | DefKind::AssocFn
1288 | DefKind::Fn
1289 | DefKind::Static { .. }
1290 | DefKind::Const { .. }
1291 | DefKind::TyAlias
1292 | DefKind::Enum
1293 | DefKind::Union
1294 | DefKind::ForeignTy
1295 | DefKind::Trait => self.warn_dead_code(def_id, "used"),
1296 DefKind::Struct => self.warn_dead_code(def_id, "constructed"),
1297 DefKind::Variant | DefKind::Field => ::rustc_middle::util::bug::bug_fmt(format_args!("should be handled specially"))bug!("should be handled specially"),
1298 _ => {}
1299 }
1300 }
1301
1302 fn is_live_code(&self, def_id: LocalDefId) -> bool {
1303 let Some(name) = self.tcx.opt_item_name(def_id.to_def_id()) else {
1306 return true;
1307 };
1308
1309 self.live_symbols.contains(&def_id) || name.as_str().starts_with('_')
1310 }
1311}
1312
1313fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalModDefId) {
1314 let Ok(DeadCodeLivenessSummary { pre_deferred_seeding, final_result }) =
1315 tcx.live_symbols_and_ignored_derived_traits(()).as_ref()
1316 else {
1317 return;
1318 };
1319
1320 let module_items = tcx.hir_module_items(module);
1321
1322 if tcx.crate_types().contains(&CrateType::Executable) {
1323 let is_unused_pub = |def_id: LocalDefId| {
1324 tcx.effective_visibilities(()).is_public_at_level(def_id, Level::Reachable)
1325 && !pre_deferred_seeding.live_symbols.contains(&def_id)
1326 };
1327
1328 lint_dead_codes(
1329 tcx,
1330 DEAD_CODE_PUB_IN_BINARY,
1331 module,
1332 &pre_deferred_seeding.live_symbols,
1333 &pre_deferred_seeding.ignored_derived_traits,
1334 module_items.free_items().filter(|free_item| is_unused_pub(free_item.owner_id.def_id)),
1335 module_items
1336 .foreign_items()
1337 .filter(|foreign_item| is_unused_pub(foreign_item.owner_id.def_id)),
1338 );
1339 }
1340
1341 lint_dead_codes(
1342 tcx,
1343 DEAD_CODE,
1344 module,
1345 &final_result.live_symbols,
1346 &final_result.ignored_derived_traits,
1347 module_items.free_items(),
1348 module_items.foreign_items(),
1349 );
1350}
1351
1352fn lint_dead_codes<'tcx>(
1353 tcx: TyCtxt<'tcx>,
1354 target_lint: &'static Lint,
1355 module: LocalModDefId,
1356 live_symbols: &'tcx LocalDefIdSet,
1357 ignored_derived_traits: &'tcx LocalDefIdMap<FxIndexSet<DefId>>,
1358 free_items: impl Iterator<Item = ItemId>,
1359 foreign_items: impl Iterator<Item = ForeignItemId>,
1360) {
1361 let mut visitor = DeadVisitor { tcx, target_lint, live_symbols, ignored_derived_traits };
1362 for item in free_items {
1363 let def_kind = tcx.def_kind(item.owner_id);
1364
1365 let mut dead_codes = Vec::new();
1366 if def_kind == (DefKind::Impl { of_trait: false })
1372 || (def_kind == DefKind::Trait && live_symbols.contains(&item.owner_id.def_id))
1373 {
1374 for &def_id in tcx.associated_item_def_ids(item.owner_id.def_id) {
1375 if let Some(local_def_id) = def_id.as_local()
1376 && !visitor.is_live_code(local_def_id)
1377 {
1378 let name = tcx.item_name(def_id);
1379 let level_plus = visitor.def_lint_level_plus(local_def_id);
1380 dead_codes.push(DeadItem { def_id: local_def_id, name, level_plus });
1381 }
1382 }
1383 }
1384 if !dead_codes.is_empty() {
1385 visitor.warn_multiple(item.owner_id.def_id, "used", dead_codes, ReportOn::NamedField);
1386 }
1387
1388 if !live_symbols.contains(&item.owner_id.def_id) {
1389 let parent = tcx.local_parent(item.owner_id.def_id);
1390 if parent != module.to_local_def_id() && !live_symbols.contains(&parent) {
1391 continue;
1393 }
1394 visitor.check_definition(item.owner_id.def_id);
1395 continue;
1396 }
1397
1398 if let DefKind::Struct | DefKind::Union | DefKind::Enum = def_kind {
1399 let adt = tcx.adt_def(item.owner_id);
1400 let mut dead_variants = Vec::new();
1401
1402 for variant in adt.variants() {
1403 let def_id = variant.def_id.expect_local();
1404 if !live_symbols.contains(&def_id) {
1405 let level_plus = visitor.def_lint_level_plus(def_id);
1407 dead_variants.push(DeadItem { def_id, name: variant.name, level_plus });
1408 continue;
1409 }
1410
1411 let is_positional = variant.fields.raw.first().is_some_and(|field| {
1412 field.name.as_str().starts_with(|c: char| c.is_ascii_digit())
1413 });
1414 let report_on =
1415 if is_positional { ReportOn::TupleField } else { ReportOn::NamedField };
1416 let dead_fields = variant
1417 .fields
1418 .iter()
1419 .filter_map(|field| {
1420 let def_id = field.did.expect_local();
1421 if let ShouldWarnAboutField::Yes = visitor.should_warn_about_field(field) {
1422 let level_plus = visitor.def_lint_level_plus(def_id);
1423 Some(DeadItem { def_id, name: field.name, level_plus })
1424 } else {
1425 None
1426 }
1427 })
1428 .collect();
1429 visitor.warn_multiple(def_id, "read", dead_fields, report_on);
1430 }
1431
1432 visitor.warn_multiple(
1433 item.owner_id.def_id,
1434 "constructed",
1435 dead_variants,
1436 ReportOn::NamedField,
1437 );
1438 }
1439 }
1440
1441 for foreign_item in foreign_items {
1442 visitor.check_definition(foreign_item.owner_id.def_id);
1443 }
1444}
1445
1446pub(crate) fn provide(providers: &mut Providers) {
1447 *providers =
1448 Providers { live_symbols_and_ignored_derived_traits, check_mod_deathness, ..*providers };
1449}