1use std::mem;
7use std::ops::ControlFlow;
8use std::sync::atomic::Ordering;
9
10use hir::def_id::{LocalDefIdMap, LocalDefIdSet};
11use rustc_abi::FieldIdx;
12use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
13use rustc_errors::{ErrorGuaranteed, MultiSpan};
14use rustc_hir::def::{CtorOf, DefKind, Res};
15use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId};
16use rustc_hir::intravisit::{self, Visitor};
17use rustc_hir::{self as hir, ForeignItemId, ItemId, Node, PatKind, QPath, find_attr};
18use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
19use rustc_middle::middle::dead_code::{DeadCodeLivenessSnapshot, DeadCodeLivenessSummary};
20use rustc_middle::middle::privacy::Level;
21use rustc_middle::query::Providers;
22use rustc_middle::ty::{self, AssocTag, TyCtxt};
23use rustc_middle::{bug, span_bug};
24use rustc_session::config::CrateType;
25use rustc_session::lint::builtin::{DEAD_CODE, DEAD_CODE_PUB_IN_BINARY};
26use rustc_session::lint::{self, Lint, StableLintExpectationId};
27use rustc_span::{Symbol, kw};
28
29use crate::diagnostics::{
30 ChangeFields, DeadCodePubInBinaryNote, IgnoredDerivedImpls, MultipleDeadCodes, ParentInfo,
31 UselessAssignment,
32};
33
34fn should_explore(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
38 match tcx.def_kind(def_id) {
39 DefKind::Mod
40 | DefKind::Struct
41 | DefKind::Union
42 | DefKind::Enum
43 | DefKind::Variant
44 | DefKind::Trait
45 | DefKind::TyAlias
46 | DefKind::ForeignTy
47 | DefKind::TraitAlias
48 | DefKind::AssocTy
49 | DefKind::Fn
50 | DefKind::Const { .. }
51 | DefKind::Static { .. }
52 | DefKind::AssocFn
53 | DefKind::AssocConst { .. }
54 | DefKind::Macro(_)
55 | DefKind::GlobalAsm
56 | DefKind::Impl { .. }
57 | DefKind::OpaqueTy
58 | DefKind::AnonConst
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 if tcx.sess.is_test_crate()
936 && !tcx.sess.removed_rustc_main_attr.load(Ordering::Relaxed)
937 && let Some(main_def) = tcx.resolutions(()).main_def
938 && let Some(def_id) = main_def.opt_fn_def_id()
939 && let Some(local_def_id) = def_id.as_local()
940 {
941 worklist.push(WorkItem {
942 id: local_def_id,
943 propagated: ComesFromAllowExpect::No,
944 own: ComesFromAllowExpect::No,
945 });
946 }
947
948 for (id, effective_vis) in tcx.effective_visibilities(()).iter() {
949 if effective_vis.is_public_at_level(Level::Reachable) {
950 deferred_seeds.push(WorkItem {
951 id: *id,
952 propagated: ComesFromAllowExpect::No,
953 own: ComesFromAllowExpect::No,
954 });
955 }
956 }
957
958 let mut push_into_worklist = |work_item: WorkItem| match work_item.own {
959 ComesFromAllowExpect::Yes => deferred_seeds.push(work_item),
960 ComesFromAllowExpect::No => worklist.push(work_item),
961 };
962 let crate_items = tcx.hir_crate_items(());
963 for id in crate_items.owners() {
964 maybe_record_as_seed(tcx, id, &mut push_into_worklist, &mut unsolved_items);
965 }
966
967 SeedWorklists { worklist, deferred_seeds, unsolved_items }
968}
969
970fn live_symbols_and_ignored_derived_traits(
971 tcx: TyCtxt<'_>,
972 (): (),
973) -> Result<DeadCodeLivenessSummary, ErrorGuaranteed> {
974 let SeedWorklists { worklist, deferred_seeds, mut unsolved_items } =
975 create_and_seed_worklist(tcx);
976 let mut symbol_visitor = MarkSymbolVisitor {
977 worklist,
978 tcx,
979 maybe_typeck_results: None,
980 scanned: Default::default(),
981 live_symbols: Default::default(),
982 repr_unconditionally_treats_fields_as_live: false,
983 repr_has_repr_simd: false,
984 in_pat: false,
985 ignore_variant_stack: ::alloc::vec::Vec::new()vec![],
986 ignored_derived_traits: Default::default(),
987 propagated_comes_from_allow_expect: ComesFromAllowExpect::No,
988 };
989 mark_live_symbols_and_ignored_derived_traits(&mut symbol_visitor, &mut unsolved_items)?;
990 let pre_deferred_seeding = DeadCodeLivenessSnapshot {
991 live_symbols: symbol_visitor.live_symbols.clone(),
992 ignored_derived_traits: symbol_visitor.ignored_derived_traits.clone(),
993 };
994
995 symbol_visitor.worklist.extend(deferred_seeds);
996 mark_live_symbols_and_ignored_derived_traits(&mut symbol_visitor, &mut unsolved_items)?;
997
998 Ok(DeadCodeLivenessSummary {
999 pre_deferred_seeding,
1000 final_result: DeadCodeLivenessSnapshot {
1001 live_symbols: symbol_visitor.live_symbols,
1002 ignored_derived_traits: symbol_visitor.ignored_derived_traits,
1003 },
1004 })
1005}
1006
1007fn mark_live_symbols_and_ignored_derived_traits(
1008 symbol_visitor: &mut MarkSymbolVisitor<'_>,
1009 unsolved_items: &mut Vec<LocalDefId>,
1010) -> Result<(), ErrorGuaranteed> {
1011 if let ControlFlow::Break(guar) = symbol_visitor.mark_live_symbols() {
1012 return Err(guar);
1013 }
1014
1015 let mut items_to_check: Vec<_> = unsolved_items
1018 .extract_if(.., |&mut local_def_id| {
1019 symbol_visitor.check_impl_or_impl_item_live(local_def_id)
1020 })
1021 .collect();
1022
1023 while !items_to_check.is_empty() {
1024 symbol_visitor.worklist.extend(items_to_check.drain(..).map(|id| WorkItem {
1025 id,
1026 propagated: ComesFromAllowExpect::No,
1027 own: ComesFromAllowExpect::No,
1028 }));
1029 if let ControlFlow::Break(guar) = symbol_visitor.mark_live_symbols() {
1030 return Err(guar);
1031 }
1032
1033 items_to_check.extend(unsolved_items.extract_if(.., |&mut local_def_id| {
1034 symbol_visitor.check_impl_or_impl_item_live(local_def_id)
1035 }));
1036 }
1037
1038 Ok(())
1039}
1040
1041struct DeadItem {
1042 def_id: LocalDefId,
1043 name: Symbol,
1044 level_plus: (lint::Level, Option<StableLintExpectationId>),
1045}
1046
1047struct DeadVisitor<'tcx> {
1048 tcx: TyCtxt<'tcx>,
1049 target_lint: &'static Lint,
1050 live_symbols: &'tcx LocalDefIdSet,
1051 ignored_derived_traits: &'tcx LocalDefIdMap<FxIndexSet<DefId>>,
1052}
1053
1054enum ShouldWarnAboutField {
1055 Yes,
1056 No,
1057}
1058
1059#[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)]
1060enum ReportOn {
1061 TupleField,
1063 NamedField,
1065}
1066
1067impl<'tcx> DeadVisitor<'tcx> {
1068 fn should_warn_about_field(&mut self, field: &ty::FieldDef) -> ShouldWarnAboutField {
1069 if self.live_symbols.contains(&field.did.expect_local()) {
1070 return ShouldWarnAboutField::No;
1071 }
1072 let field_type = self.tcx.type_of(field.did).instantiate_identity().skip_norm_wip();
1073 if field_type.is_phantom_data() {
1074 return ShouldWarnAboutField::No;
1075 }
1076 let is_positional = field.name.as_str().starts_with(|c: char| c.is_ascii_digit());
1077 if is_positional
1078 && self
1079 .tcx
1080 .layout_of(
1081 ty::TypingEnv::non_body_analysis(self.tcx, field.did)
1082 .as_query_input(field_type),
1083 )
1084 .map_or(true, |layout| layout.is_zst())
1085 {
1086 return ShouldWarnAboutField::No;
1087 }
1088 ShouldWarnAboutField::Yes
1089 }
1090
1091 fn def_lint_level_plus(
1092 &self,
1093 id: LocalDefId,
1094 ) -> (lint::Level, Option<StableLintExpectationId>) {
1095 let hir_id = self.tcx.local_def_id_to_hir_id(id);
1096 let level_spec = self.tcx.lint_level_spec_at_node(self.target_lint, hir_id);
1097 (level_spec.level(), level_spec.lint_id())
1098 }
1099
1100 fn dead_code_pub_in_binary_note(&self) -> Option<DeadCodePubInBinaryNote> {
1101 self.target_lint.name.eq(DEAD_CODE_PUB_IN_BINARY.name).then_some(DeadCodePubInBinaryNote)
1102 }
1103
1104 fn lint_at_single_level(
1111 &self,
1112 dead_codes: &[&DeadItem],
1113 participle: &str,
1114 parent_item: Option<LocalDefId>,
1115 report_on: ReportOn,
1116 ) {
1117 let Some(&first_item) = dead_codes.first() else { return };
1118 let tcx = self.tcx;
1119
1120 let first_lint_level_plus = first_item.level_plus;
1121 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));
1122
1123 let names: Vec<_> = dead_codes.iter().map(|item| item.name).collect();
1124 let spans: Vec<_> = dead_codes
1125 .iter()
1126 .map(|item| {
1127 let span = tcx.def_span(item.def_id);
1128 let ident_span = tcx.def_ident_span(item.def_id);
1129 ident_span.map(|s| s.with_ctxt(span.ctxt())).unwrap_or(span)
1131 })
1132 .collect();
1133
1134 let mut descr = tcx.def_descr(first_item.def_id.to_def_id());
1135 if dead_codes.iter().any(|item| tcx.def_descr(item.def_id.to_def_id()) != descr) {
1138 descr = "associated item"
1139 }
1140
1141 let num = dead_codes.len();
1142 let multiple = num > 6;
1143 let name_list = names.into();
1144
1145 let parent_info = parent_item.map(|parent_item| {
1146 let parent_descr = tcx.def_descr(parent_item.to_def_id());
1147 let span = if let DefKind::Impl { .. } = tcx.def_kind(parent_item) {
1148 tcx.def_span(parent_item)
1149 } else {
1150 tcx.def_ident_span(parent_item).unwrap()
1151 };
1152 ParentInfo { num, descr, parent_descr, span }
1153 });
1154
1155 let mut encl_def_id = parent_item.unwrap_or(first_item.def_id);
1156 if let DefKind::Variant = tcx.def_kind(encl_def_id) {
1158 encl_def_id = tcx.local_parent(encl_def_id);
1159 }
1160
1161 let ignored_derived_impls =
1162 self.ignored_derived_traits.get(&encl_def_id).map(|ign_traits| {
1163 let trait_list = ign_traits
1164 .iter()
1165 .map(|trait_id| self.tcx.item_name(*trait_id))
1166 .collect::<Vec<_>>();
1167 let trait_list_len = trait_list.len();
1168 IgnoredDerivedImpls {
1169 name: self.tcx.item_name(encl_def_id.to_def_id()),
1170 trait_list: trait_list.into(),
1171 trait_list_len,
1172 }
1173 });
1174
1175 let diag = match report_on {
1176 ReportOn::TupleField => {
1177 let tuple_fields = if let Some(parent_id) = parent_item
1178 && let node = tcx.hir_node_by_def_id(parent_id)
1179 && let hir::Node::Item(hir::Item {
1180 kind: hir::ItemKind::Struct(_, _, hir::VariantData::Tuple(fields, _, _)),
1181 ..
1182 }) = node
1183 {
1184 *fields
1185 } else {
1186 &[]
1187 };
1188
1189 let trailing_tuple_fields = if tuple_fields.len() >= dead_codes.len() {
1190 LocalDefIdSet::from_iter(
1191 tuple_fields
1192 .iter()
1193 .skip(tuple_fields.len() - dead_codes.len())
1194 .map(|f| f.def_id),
1195 )
1196 } else {
1197 LocalDefIdSet::default()
1198 };
1199
1200 let fields_suggestion =
1201 if dead_codes.iter().all(|dc| trailing_tuple_fields.contains(&dc.def_id)) {
1204 ChangeFields::Remove { num }
1205 } else {
1206 ChangeFields::ChangeToUnitTypeOrRemove { num, spans: spans.clone() }
1207 };
1208
1209 MultipleDeadCodes::UnusedTupleStructFields {
1210 multiple,
1211 num,
1212 descr,
1213 participle,
1214 name_list,
1215 dead_code_pub_in_binary_note: self.dead_code_pub_in_binary_note(),
1216 change_fields_suggestion: fields_suggestion,
1217 parent_info,
1218 ignored_derived_impls,
1219 }
1220 }
1221 ReportOn::NamedField => {
1222 let enum_variants_with_same_name = dead_codes
1223 .iter()
1224 .filter_map(|dead_item| {
1225 if let DefKind::AssocFn | DefKind::AssocConst { .. } =
1226 tcx.def_kind(dead_item.def_id)
1227 && let impl_did = tcx.local_parent(dead_item.def_id)
1228 && let DefKind::Impl { of_trait: false } = tcx.def_kind(impl_did)
1229 && let ty::Adt(maybe_enum, _) =
1230 tcx.type_of(impl_did).instantiate_identity().skip_norm_wip().kind()
1231 && maybe_enum.is_enum()
1232 && let Some(variant) =
1233 maybe_enum.variants().iter().find(|i| i.name == dead_item.name)
1234 {
1235 Some(crate::diagnostics::EnumVariantSameName {
1236 dead_descr: tcx.def_descr(dead_item.def_id.to_def_id()),
1237 dead_name: dead_item.name,
1238 variant_span: tcx.def_span(variant.def_id),
1239 })
1240 } else {
1241 None
1242 }
1243 })
1244 .collect();
1245
1246 MultipleDeadCodes::DeadCodes {
1247 multiple,
1248 num,
1249 descr,
1250 participle,
1251 name_list,
1252 dead_code_pub_in_binary_note: self.dead_code_pub_in_binary_note(),
1253 parent_info,
1254 ignored_derived_impls,
1255 enum_variants_with_same_name,
1256 }
1257 }
1258 };
1259
1260 let hir_id = tcx.local_def_id_to_hir_id(first_item.def_id);
1261 self.tcx.emit_node_span_lint(self.target_lint, hir_id, MultiSpan::from_spans(spans), diag);
1262 }
1263
1264 fn warn_multiple(
1265 &self,
1266 def_id: LocalDefId,
1267 participle: &str,
1268 dead_codes: Vec<DeadItem>,
1269 report_on: ReportOn,
1270 ) {
1271 let mut dead_codes = dead_codes
1272 .iter()
1273 .filter(|v| !v.name.as_str().starts_with('_'))
1274 .collect::<Vec<&DeadItem>>();
1275 if dead_codes.is_empty() {
1276 return;
1277 }
1278 dead_codes.sort_by_key(|v| v.level_plus.0);
1281 for group in dead_codes.chunk_by(|a, b| a.level_plus == b.level_plus) {
1282 self.lint_at_single_level(&group, participle, Some(def_id), report_on);
1283 }
1284 }
1285
1286 fn warn_dead_code(&mut self, id: LocalDefId, participle: &str) {
1287 let item = DeadItem {
1288 def_id: id,
1289 name: self.tcx.item_name(id.to_def_id()),
1290 level_plus: self.def_lint_level_plus(id),
1291 };
1292 self.lint_at_single_level(&[&item], participle, None, ReportOn::NamedField);
1293 }
1294
1295 fn check_definition(&mut self, def_id: LocalDefId) {
1296 if self.is_live_code(def_id) {
1297 return;
1298 }
1299 match self.tcx.def_kind(def_id) {
1300 DefKind::AssocConst { .. }
1301 | DefKind::AssocTy
1302 | DefKind::AssocFn
1303 | DefKind::Fn
1304 | DefKind::Static { .. }
1305 | DefKind::Const { .. }
1306 | DefKind::TyAlias
1307 | DefKind::Enum
1308 | DefKind::Union
1309 | DefKind::ForeignTy
1310 | DefKind::Trait => self.warn_dead_code(def_id, "used"),
1311 DefKind::Struct => self.warn_dead_code(def_id, "constructed"),
1312 DefKind::Variant | DefKind::Field => ::rustc_middle::util::bug::bug_fmt(format_args!("should be handled specially"))bug!("should be handled specially"),
1313 _ => {}
1314 }
1315 }
1316
1317 fn is_live_code(&self, def_id: LocalDefId) -> bool {
1318 let Some(name) = self.tcx.opt_item_name(def_id.to_def_id()) else {
1321 return true;
1322 };
1323
1324 self.live_symbols.contains(&def_id) || name.as_str().starts_with('_')
1325 }
1326}
1327
1328fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalModDefId) {
1329 let Ok(DeadCodeLivenessSummary { pre_deferred_seeding, final_result }) =
1330 tcx.live_symbols_and_ignored_derived_traits(()).as_ref()
1331 else {
1332 return;
1333 };
1334
1335 let module_items = tcx.hir_module_items(module);
1336
1337 if tcx.crate_types().contains(&CrateType::Executable) {
1338 let is_unused_pub = |def_id: LocalDefId| {
1339 tcx.effective_visibilities(()).is_public_at_level(def_id, Level::Reachable)
1340 && !pre_deferred_seeding.live_symbols.contains(&def_id)
1341 };
1342
1343 lint_dead_codes(
1344 tcx,
1345 DEAD_CODE_PUB_IN_BINARY,
1346 module,
1347 &pre_deferred_seeding.live_symbols,
1348 &pre_deferred_seeding.ignored_derived_traits,
1349 module_items.free_items().filter(|free_item| is_unused_pub(free_item.owner_id.def_id)),
1350 module_items
1351 .foreign_items()
1352 .filter(|foreign_item| is_unused_pub(foreign_item.owner_id.def_id)),
1353 );
1354 }
1355
1356 lint_dead_codes(
1357 tcx,
1358 DEAD_CODE,
1359 module,
1360 &final_result.live_symbols,
1361 &final_result.ignored_derived_traits,
1362 module_items.free_items(),
1363 module_items.foreign_items(),
1364 );
1365}
1366
1367fn lint_dead_codes<'tcx>(
1368 tcx: TyCtxt<'tcx>,
1369 target_lint: &'static Lint,
1370 module: LocalModDefId,
1371 live_symbols: &'tcx LocalDefIdSet,
1372 ignored_derived_traits: &'tcx LocalDefIdMap<FxIndexSet<DefId>>,
1373 free_items: impl Iterator<Item = ItemId>,
1374 foreign_items: impl Iterator<Item = ForeignItemId>,
1375) {
1376 let mut visitor = DeadVisitor { tcx, target_lint, live_symbols, ignored_derived_traits };
1377 for item in free_items {
1378 let def_kind = tcx.def_kind(item.owner_id);
1379
1380 let mut dead_codes = Vec::new();
1381 if def_kind == (DefKind::Impl { of_trait: false })
1387 || (def_kind == DefKind::Trait && live_symbols.contains(&item.owner_id.def_id))
1388 {
1389 for &def_id in tcx.associated_item_def_ids(item.owner_id.def_id) {
1390 if let Some(local_def_id) = def_id.as_local()
1391 && !visitor.is_live_code(local_def_id)
1392 {
1393 let name = tcx.item_name(def_id);
1394 let level_plus = visitor.def_lint_level_plus(local_def_id);
1395 dead_codes.push(DeadItem { def_id: local_def_id, name, level_plus });
1396 }
1397 }
1398 }
1399 if !dead_codes.is_empty() {
1400 visitor.warn_multiple(item.owner_id.def_id, "used", dead_codes, ReportOn::NamedField);
1401 }
1402
1403 if !live_symbols.contains(&item.owner_id.def_id) {
1404 let parent = tcx.local_parent(item.owner_id.def_id);
1405 if parent != module.to_local_def_id() && !live_symbols.contains(&parent) {
1406 continue;
1408 }
1409 visitor.check_definition(item.owner_id.def_id);
1410 continue;
1411 }
1412
1413 if let DefKind::Struct | DefKind::Union | DefKind::Enum = def_kind {
1414 let adt = tcx.adt_def(item.owner_id);
1415 let mut dead_variants = Vec::new();
1416
1417 for variant in adt.variants() {
1418 let def_id = variant.def_id.expect_local();
1419 if !live_symbols.contains(&def_id) {
1420 let level_plus = visitor.def_lint_level_plus(def_id);
1422 dead_variants.push(DeadItem { def_id, name: variant.name, level_plus });
1423 continue;
1424 }
1425
1426 let is_positional = variant.fields.raw.first().is_some_and(|field| {
1427 field.name.as_str().starts_with(|c: char| c.is_ascii_digit())
1428 });
1429 let report_on =
1430 if is_positional { ReportOn::TupleField } else { ReportOn::NamedField };
1431 let dead_fields = variant
1432 .fields
1433 .iter()
1434 .filter_map(|field| {
1435 let def_id = field.did.expect_local();
1436 if let ShouldWarnAboutField::Yes = visitor.should_warn_about_field(field) {
1437 let level_plus = visitor.def_lint_level_plus(def_id);
1438 Some(DeadItem { def_id, name: field.name, level_plus })
1439 } else {
1440 None
1441 }
1442 })
1443 .collect();
1444 visitor.warn_multiple(def_id, "read", dead_fields, report_on);
1445 }
1446
1447 visitor.warn_multiple(
1448 item.owner_id.def_id,
1449 "constructed",
1450 dead_variants,
1451 ReportOn::NamedField,
1452 );
1453 }
1454 }
1455
1456 for foreign_item in foreign_items {
1457 visitor.check_definition(foreign_item.owner_id.def_id);
1458 }
1459}
1460
1461pub(crate) fn provide(providers: &mut Providers) {
1462 *providers =
1463 Providers { live_symbols_and_ignored_derived_traits, check_mod_deathness, ..*providers };
1464}