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