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