1use std::mem;
7
8use hir::ItemKind;
9use hir::def_id::{LocalDefIdMap, LocalDefIdSet};
10use rustc_abi::FieldIdx;
11use rustc_data_structures::fx::FxIndexSet;
12use rustc_data_structures::unord::UnordSet;
13use rustc_errors::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, ImplItem, ImplItemKind, Node, PatKind, QPath, TyKind};
18use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
19use rustc_middle::middle::privacy::Level;
20use rustc_middle::query::Providers;
21use rustc_middle::ty::{self, AssocTag, TyCtxt};
22use rustc_middle::{bug, span_bug};
23use rustc_session::lint::builtin::DEAD_CODE;
24use rustc_session::lint::{self, LintExpectationId};
25use rustc_span::{Symbol, kw, sym};
26
27use crate::errors::{
28 ChangeFields, IgnoredDerivedImpls, MultipleDeadCodes, ParentInfo, UselessAssignment,
29};
30
31fn should_explore(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
36 matches!(
37 tcx.hir_node_by_def_id(def_id),
38 Node::Item(..)
39 | Node::ImplItem(..)
40 | Node::ForeignItem(..)
41 | Node::TraitItem(..)
42 | Node::Variant(..)
43 | Node::AnonConst(..)
44 | Node::OpaqueTy(..)
45 )
46}
47
48fn local_adt_def_of_ty<'tcx>(ty: &hir::Ty<'tcx>) -> Option<LocalDefId> {
50 match ty.kind {
51 TyKind::Path(QPath::Resolved(_, path)) => {
52 if let Res::Def(def_kind, def_id) = path.res
53 && let Some(local_def_id) = def_id.as_local()
54 && matches!(def_kind, DefKind::Struct | DefKind::Enum | DefKind::Union)
55 {
56 Some(local_def_id)
57 } else {
58 None
59 }
60 }
61 _ => None,
62 }
63}
64
65#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
68enum ComesFromAllowExpect {
69 Yes,
70 No,
71}
72
73struct MarkSymbolVisitor<'tcx> {
74 worklist: Vec<(LocalDefId, ComesFromAllowExpect)>,
75 tcx: TyCtxt<'tcx>,
76 maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
77 live_symbols: LocalDefIdSet,
78 repr_unconditionally_treats_fields_as_live: bool,
79 repr_has_repr_simd: bool,
80 in_pat: bool,
81 ignore_variant_stack: Vec<DefId>,
82 struct_constructors: LocalDefIdMap<LocalDefId>,
84 ignored_derived_traits: LocalDefIdMap<FxIndexSet<(DefId, DefId)>>,
88}
89
90impl<'tcx> MarkSymbolVisitor<'tcx> {
91 #[track_caller]
95 fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
96 self.maybe_typeck_results
97 .expect("`MarkSymbolVisitor::typeck_results` called outside of body")
98 }
99
100 fn check_def_id(&mut self, def_id: DefId) {
101 if let Some(def_id) = def_id.as_local() {
102 if should_explore(self.tcx, def_id) || self.struct_constructors.contains_key(&def_id) {
103 self.worklist.push((def_id, ComesFromAllowExpect::No));
104 }
105 self.live_symbols.insert(def_id);
106 }
107 }
108
109 fn insert_def_id(&mut self, def_id: DefId) {
110 if let Some(def_id) = def_id.as_local() {
111 debug_assert!(!should_explore(self.tcx, def_id));
112 self.live_symbols.insert(def_id);
113 }
114 }
115
116 fn handle_res(&mut self, res: Res) {
117 match res {
118 Res::Def(
119 DefKind::Const | DefKind::AssocConst | DefKind::AssocTy | DefKind::TyAlias,
120 def_id,
121 ) => {
122 self.check_def_id(def_id);
123 }
124 _ if self.in_pat => {}
125 Res::PrimTy(..) | Res::SelfCtor(..) | Res::Local(..) => {}
126 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), ctor_def_id) => {
127 let variant_id = self.tcx.parent(ctor_def_id);
128 let enum_id = self.tcx.parent(variant_id);
129 self.check_def_id(enum_id);
130 if !self.ignore_variant_stack.contains(&ctor_def_id) {
131 self.check_def_id(variant_id);
132 }
133 }
134 Res::Def(DefKind::Variant, variant_id) => {
135 let enum_id = self.tcx.parent(variant_id);
136 self.check_def_id(enum_id);
137 if !self.ignore_variant_stack.contains(&variant_id) {
138 self.check_def_id(variant_id);
139 }
140 }
141 Res::Def(_, def_id) => self.check_def_id(def_id),
142 Res::SelfTyParam { trait_: t } => self.check_def_id(t),
143 Res::SelfTyAlias { alias_to: i, .. } => self.check_def_id(i),
144 Res::ToolMod | Res::NonMacroAttr(..) | Res::Err => {}
145 }
146 }
147
148 fn lookup_and_handle_method(&mut self, id: hir::HirId) {
149 if let Some(def_id) = self.typeck_results().type_dependent_def_id(id) {
150 self.check_def_id(def_id);
151 } else {
152 assert!(
153 self.typeck_results().tainted_by_errors.is_some(),
154 "no type-dependent def for method"
155 );
156 }
157 }
158
159 fn handle_field_access(&mut self, lhs: &hir::Expr<'_>, hir_id: hir::HirId) {
160 match self.typeck_results().expr_ty_adjusted(lhs).kind() {
161 ty::Adt(def, _) => {
162 let index = self.typeck_results().field_index(hir_id);
163 self.insert_def_id(def.non_enum_variant().fields[index].did);
164 }
165 ty::Tuple(..) => {}
166 ty::Error(_) => {}
167 kind => span_bug!(lhs.span, "named field access on non-ADT: {kind:?}"),
168 }
169 }
170
171 #[allow(dead_code)] fn handle_assign(&mut self, expr: &'tcx hir::Expr<'tcx>) {
173 if self
174 .typeck_results()
175 .expr_adjustments(expr)
176 .iter()
177 .any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(_)))
178 {
179 self.visit_expr(expr);
180 } else if let hir::ExprKind::Field(base, ..) = expr.kind {
181 self.handle_assign(base);
183 } else {
184 self.visit_expr(expr);
185 }
186 }
187
188 #[allow(dead_code)] fn check_for_self_assign(&mut self, assign: &'tcx hir::Expr<'tcx>) {
190 fn check_for_self_assign_helper<'tcx>(
191 typeck_results: &'tcx ty::TypeckResults<'tcx>,
192 lhs: &'tcx hir::Expr<'tcx>,
193 rhs: &'tcx hir::Expr<'tcx>,
194 ) -> bool {
195 match (&lhs.kind, &rhs.kind) {
196 (hir::ExprKind::Path(qpath_l), hir::ExprKind::Path(qpath_r)) => {
197 if let (Res::Local(id_l), Res::Local(id_r)) = (
198 typeck_results.qpath_res(qpath_l, lhs.hir_id),
199 typeck_results.qpath_res(qpath_r, rhs.hir_id),
200 ) {
201 if id_l == id_r {
202 return true;
203 }
204 }
205 return false;
206 }
207 (hir::ExprKind::Field(lhs_l, ident_l), hir::ExprKind::Field(lhs_r, ident_r)) => {
208 if ident_l == ident_r {
209 return check_for_self_assign_helper(typeck_results, lhs_l, lhs_r);
210 }
211 return false;
212 }
213 _ => {
214 return false;
215 }
216 }
217 }
218
219 if let hir::ExprKind::Assign(lhs, rhs, _) = assign.kind
220 && check_for_self_assign_helper(self.typeck_results(), lhs, rhs)
221 && !assign.span.from_expansion()
222 {
223 let is_field_assign = matches!(lhs.kind, hir::ExprKind::Field(..));
224 self.tcx.emit_node_span_lint(
225 lint::builtin::DEAD_CODE,
226 assign.hir_id,
227 assign.span,
228 UselessAssignment { is_field_assign, ty: self.typeck_results().expr_ty(lhs) },
229 )
230 }
231 }
232
233 fn handle_field_pattern_match(
234 &mut self,
235 lhs: &hir::Pat<'_>,
236 res: Res,
237 pats: &[hir::PatField<'_>],
238 ) {
239 let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
240 ty::Adt(adt, _) => {
241 self.check_def_id(adt.did());
246 adt.variant_of_res(res)
247 }
248 _ => span_bug!(lhs.span, "non-ADT in struct pattern"),
249 };
250 for pat in pats {
251 if let PatKind::Wild = pat.pat.kind {
252 continue;
253 }
254 let index = self.typeck_results().field_index(pat.hir_id);
255 self.insert_def_id(variant.fields[index].did);
256 }
257 }
258
259 fn handle_tuple_field_pattern_match(
260 &mut self,
261 lhs: &hir::Pat<'_>,
262 res: Res,
263 pats: &[hir::Pat<'_>],
264 dotdot: hir::DotDotPos,
265 ) {
266 let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
267 ty::Adt(adt, _) => {
268 self.check_def_id(adt.did());
270 adt.variant_of_res(res)
271 }
272 _ => {
273 self.tcx.dcx().span_delayed_bug(lhs.span, "non-ADT in tuple struct pattern");
274 return;
275 }
276 };
277 let dotdot = dotdot.as_opt_usize().unwrap_or(pats.len());
278 let first_n = pats.iter().enumerate().take(dotdot);
279 let missing = variant.fields.len() - pats.len();
280 let last_n = pats.iter().enumerate().skip(dotdot).map(|(idx, pat)| (idx + missing, pat));
281 for (idx, pat) in first_n.chain(last_n) {
282 if let PatKind::Wild = pat.kind {
283 continue;
284 }
285 self.insert_def_id(variant.fields[FieldIdx::from_usize(idx)].did);
286 }
287 }
288
289 fn handle_offset_of(&mut self, expr: &'tcx hir::Expr<'tcx>) {
290 let data = self.typeck_results().offset_of_data();
291 let &(container, ref indices) =
292 data.get(expr.hir_id).expect("no offset_of_data for offset_of");
293
294 let body_did = self.typeck_results().hir_owner.to_def_id();
295 let typing_env = ty::TypingEnv::non_body_analysis(self.tcx, body_did);
296
297 let mut current_ty = container;
298
299 for &(variant, field) in indices {
300 match current_ty.kind() {
301 ty::Adt(def, args) => {
302 let field = &def.variant(variant).fields[field];
303
304 self.insert_def_id(field.did);
305 let field_ty = field.ty(self.tcx, args);
306
307 current_ty = self.tcx.normalize_erasing_regions(typing_env, field_ty);
308 }
309 ty::Tuple(tys) => {
312 current_ty =
313 self.tcx.normalize_erasing_regions(typing_env, tys[field.as_usize()]);
314 }
315 _ => span_bug!(expr.span, "named field access on non-ADT"),
316 }
317 }
318 }
319
320 fn mark_live_symbols(&mut self) {
321 let mut scanned = UnordSet::default();
322 while let Some(work) = self.worklist.pop() {
323 if !scanned.insert(work) {
324 continue;
325 }
326
327 let (id, comes_from_allow_expect) = work;
328
329 if self.tcx.is_impl_trait_in_trait(id.to_def_id()) {
331 self.live_symbols.insert(id);
332 continue;
333 }
334
335 let id = self.struct_constructors.get(&id).copied().unwrap_or(id);
338
339 if comes_from_allow_expect != ComesFromAllowExpect::Yes {
361 self.live_symbols.insert(id);
362 }
363 self.visit_node(self.tcx.hir_node_by_def_id(id));
364 }
365 }
366
367 fn should_ignore_item(&mut self, def_id: DefId) -> bool {
371 if let Some(impl_of) = self.tcx.impl_of_method(def_id) {
372 if !self.tcx.is_automatically_derived(impl_of) {
373 return false;
374 }
375
376 if let Some(trait_of) = self.tcx.trait_id_of_impl(impl_of)
377 && self.tcx.has_attr(trait_of, sym::rustc_trivial_field_reads)
378 {
379 let trait_ref = self.tcx.impl_trait_ref(impl_of).unwrap().instantiate_identity();
380 if let ty::Adt(adt_def, _) = trait_ref.self_ty().kind()
381 && let Some(adt_def_id) = adt_def.did().as_local()
382 {
383 self.ignored_derived_traits
384 .entry(adt_def_id)
385 .or_default()
386 .insert((trait_of, impl_of));
387 }
388 return true;
389 }
390 }
391
392 false
393 }
394
395 fn visit_node(&mut self, node: Node<'tcx>) {
396 if let Node::ImplItem(hir::ImplItem { owner_id, .. }) = node
397 && self.should_ignore_item(owner_id.to_def_id())
398 {
399 return;
400 }
401
402 let unconditionally_treated_fields_as_live =
403 self.repr_unconditionally_treats_fields_as_live;
404 let had_repr_simd = self.repr_has_repr_simd;
405 self.repr_unconditionally_treats_fields_as_live = false;
406 self.repr_has_repr_simd = false;
407 match node {
408 Node::Item(item) => match item.kind {
409 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
410 let def = self.tcx.adt_def(item.owner_id);
411 self.repr_unconditionally_treats_fields_as_live =
412 def.repr().c() || def.repr().transparent();
413 self.repr_has_repr_simd = def.repr().simd();
414
415 intravisit::walk_item(self, item)
416 }
417 hir::ItemKind::ForeignMod { .. } => {}
418 hir::ItemKind::Trait(.., trait_item_refs) => {
419 for trait_item in trait_item_refs {
421 if matches!(self.tcx.def_kind(trait_item.owner_id), DefKind::AssocTy) {
422 self.check_def_id(trait_item.owner_id.to_def_id());
423 }
424 }
425 intravisit::walk_item(self, item)
426 }
427 _ => intravisit::walk_item(self, item),
428 },
429 Node::TraitItem(trait_item) => {
430 let trait_item_id = trait_item.owner_id.to_def_id();
432 if let Some(trait_id) = self.tcx.trait_of_item(trait_item_id) {
433 self.check_def_id(trait_id);
434 }
435 intravisit::walk_trait_item(self, trait_item);
436 }
437 Node::ImplItem(impl_item) => {
438 let item = self.tcx.local_parent(impl_item.owner_id.def_id);
439 if self.tcx.impl_trait_ref(item).is_none() {
440 let self_ty = self.tcx.type_of(item).instantiate_identity();
445 match *self_ty.kind() {
446 ty::Adt(def, _) => self.check_def_id(def.did()),
447 ty::Foreign(did) => self.check_def_id(did),
448 ty::Dynamic(data, ..) => {
449 if let Some(def_id) = data.principal_def_id() {
450 self.check_def_id(def_id)
451 }
452 }
453 _ => {}
454 }
455 }
456 intravisit::walk_impl_item(self, impl_item);
457 }
458 Node::ForeignItem(foreign_item) => {
459 intravisit::walk_foreign_item(self, foreign_item);
460 }
461 Node::OpaqueTy(opaq) => intravisit::walk_opaque_ty(self, opaq),
462 _ => {}
463 }
464 self.repr_has_repr_simd = had_repr_simd;
465 self.repr_unconditionally_treats_fields_as_live = unconditionally_treated_fields_as_live;
466 }
467
468 fn mark_as_used_if_union(&mut self, adt: ty::AdtDef<'tcx>, fields: &[hir::ExprField<'_>]) {
469 if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did().is_local() {
470 for field in fields {
471 let index = self.typeck_results().field_index(field.hir_id);
472 self.insert_def_id(adt.non_enum_variant().fields[index].did);
473 }
474 }
475 }
476
477 fn check_impl_or_impl_item_live(
482 &mut self,
483 impl_id: hir::ItemId,
484 local_def_id: LocalDefId,
485 ) -> bool {
486 let trait_def_id = match self.tcx.def_kind(local_def_id) {
487 DefKind::AssocConst | DefKind::AssocTy | DefKind::AssocFn => self
489 .tcx
490 .associated_item(local_def_id)
491 .trait_item_def_id
492 .and_then(|def_id| def_id.as_local()),
493 DefKind::Impl { of_trait: true } => self
495 .tcx
496 .impl_trait_ref(impl_id.owner_id.def_id)
497 .and_then(|trait_ref| trait_ref.skip_binder().def_id.as_local()),
498 _ => None,
499 };
500
501 if let Some(trait_def_id) = trait_def_id
502 && !self.live_symbols.contains(&trait_def_id)
503 {
504 return false;
505 }
506
507 if let Some(local_def_id) =
509 local_adt_def_of_ty(self.tcx.hir_item(impl_id).expect_impl().self_ty)
510 && !self.live_symbols.contains(&local_def_id)
511 {
512 return false;
513 }
514
515 true
516 }
517}
518
519impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
520 fn visit_nested_body(&mut self, body: hir::BodyId) {
521 let old_maybe_typeck_results =
522 self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
523 let body = self.tcx.hir_body(body);
524 self.visit_body(body);
525 self.maybe_typeck_results = old_maybe_typeck_results;
526 }
527
528 fn visit_variant_data(&mut self, def: &'tcx hir::VariantData<'tcx>) {
529 let tcx = self.tcx;
530 let unconditionally_treat_fields_as_live = self.repr_unconditionally_treats_fields_as_live;
531 let has_repr_simd = self.repr_has_repr_simd;
532 let effective_visibilities = &tcx.effective_visibilities(());
533 let live_fields = def.fields().iter().filter_map(|f| {
534 let def_id = f.def_id;
535 if unconditionally_treat_fields_as_live || (f.is_positional() && has_repr_simd) {
536 return Some(def_id);
537 }
538 if !effective_visibilities.is_reachable(f.hir_id.owner.def_id) {
539 return None;
540 }
541 if effective_visibilities.is_reachable(def_id) { Some(def_id) } else { None }
542 });
543 self.live_symbols.extend(live_fields);
544
545 intravisit::walk_struct_def(self, def);
546 }
547
548 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
549 match expr.kind {
550 hir::ExprKind::Path(ref qpath @ QPath::TypeRelative(..)) => {
551 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
552 self.handle_res(res);
553 }
554 hir::ExprKind::MethodCall(..) => {
555 self.lookup_and_handle_method(expr.hir_id);
556 }
557 hir::ExprKind::Field(ref lhs, ..) => {
558 if self.typeck_results().opt_field_index(expr.hir_id).is_some() {
559 self.handle_field_access(lhs, expr.hir_id);
560 } else {
561 self.tcx.dcx().span_delayed_bug(expr.span, "couldn't resolve index for field");
562 }
563 }
564 hir::ExprKind::Struct(qpath, fields, _) => {
565 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
566 self.handle_res(res);
567 if let ty::Adt(adt, _) = self.typeck_results().expr_ty(expr).kind() {
568 self.mark_as_used_if_union(*adt, fields);
569 }
570 }
571 hir::ExprKind::Closure(cls) => {
572 self.insert_def_id(cls.def_id.to_def_id());
573 }
574 hir::ExprKind::OffsetOf(..) => {
575 self.handle_offset_of(expr);
576 }
577 _ => (),
578 }
579
580 intravisit::walk_expr(self, expr);
581 }
582
583 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
584 let len = self.ignore_variant_stack.len();
588 self.ignore_variant_stack.extend(arm.pat.necessary_variants());
589 intravisit::walk_arm(self, arm);
590 self.ignore_variant_stack.truncate(len);
591 }
592
593 fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
594 self.in_pat = true;
595 match pat.kind {
596 PatKind::Struct(ref path, fields, _) => {
597 let res = self.typeck_results().qpath_res(path, pat.hir_id);
598 self.handle_field_pattern_match(pat, res, fields);
599 }
600 PatKind::TupleStruct(ref qpath, fields, dotdot) => {
601 let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
602 self.handle_tuple_field_pattern_match(pat, res, fields, dotdot);
603 }
604 _ => (),
605 }
606
607 intravisit::walk_pat(self, pat);
608 self.in_pat = false;
609 }
610
611 fn visit_pat_expr(&mut self, expr: &'tcx rustc_hir::PatExpr<'tcx>) {
612 match &expr.kind {
613 rustc_hir::PatExprKind::Path(qpath) => {
614 if let ty::Adt(adt, _) = self.typeck_results().node_type(expr.hir_id).kind() {
616 self.check_def_id(adt.did());
617 }
618
619 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
620 self.handle_res(res);
621 }
622 _ => {}
623 }
624 intravisit::walk_pat_expr(self, expr);
625 }
626
627 fn visit_path(&mut self, path: &hir::Path<'tcx>, _: hir::HirId) {
628 self.handle_res(path.res);
629 intravisit::walk_path(self, path);
630 }
631
632 fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
633 let in_pat = mem::replace(&mut self.in_pat, false);
636
637 self.live_symbols.insert(c.def_id);
638 intravisit::walk_anon_const(self, c);
639
640 self.in_pat = in_pat;
641 }
642
643 fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) {
644 let in_pat = mem::replace(&mut self.in_pat, false);
647
648 self.live_symbols.insert(c.def_id);
649 intravisit::walk_inline_const(self, c);
650
651 self.in_pat = in_pat;
652 }
653
654 fn visit_trait_ref(&mut self, t: &'tcx hir::TraitRef<'tcx>) {
655 if let Some(trait_def_id) = t.path.res.opt_def_id()
656 && let Some(segment) = t.path.segments.last()
657 && let Some(args) = segment.args
658 {
659 for constraint in args.constraints {
660 if let Some(local_def_id) = self
661 .tcx
662 .associated_items(trait_def_id)
663 .find_by_ident_and_kind(
664 self.tcx,
665 constraint.ident,
666 AssocTag::Const,
667 trait_def_id,
668 )
669 .and_then(|item| item.def_id.as_local())
670 {
671 self.worklist.push((local_def_id, ComesFromAllowExpect::No));
672 }
673 }
674 }
675
676 intravisit::walk_trait_ref(self, t);
677 }
678}
679
680fn has_allow_dead_code_or_lang_attr(
681 tcx: TyCtxt<'_>,
682 def_id: LocalDefId,
683) -> Option<ComesFromAllowExpect> {
684 fn has_lang_attr(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
685 tcx.has_attr(def_id, sym::lang)
686 || tcx.has_attr(def_id, sym::panic_handler)
688 }
689
690 fn has_allow_expect_dead_code(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
691 let hir_id = tcx.local_def_id_to_hir_id(def_id);
692 let lint_level = tcx.lint_level_at_node(lint::builtin::DEAD_CODE, hir_id).level;
693 matches!(lint_level, lint::Allow | lint::Expect)
694 }
695
696 fn has_used_like_attr(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
697 tcx.def_kind(def_id).has_codegen_attrs() && {
698 let cg_attrs = tcx.codegen_fn_attrs(def_id);
699
700 cg_attrs.contains_extern_indicator()
703 || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)
704 || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)
705 }
706 }
707
708 if has_allow_expect_dead_code(tcx, def_id) {
709 Some(ComesFromAllowExpect::Yes)
710 } else if has_used_like_attr(tcx, def_id) || has_lang_attr(tcx, def_id) {
711 Some(ComesFromAllowExpect::No)
712 } else {
713 None
714 }
715}
716
717fn check_item<'tcx>(
731 tcx: TyCtxt<'tcx>,
732 worklist: &mut Vec<(LocalDefId, ComesFromAllowExpect)>,
733 struct_constructors: &mut LocalDefIdMap<LocalDefId>,
734 unsolved_items: &mut Vec<(hir::ItemId, LocalDefId)>,
735 id: hir::ItemId,
736) {
737 let allow_dead_code = has_allow_dead_code_or_lang_attr(tcx, id.owner_id.def_id);
738 if let Some(comes_from_allow) = allow_dead_code {
739 worklist.push((id.owner_id.def_id, comes_from_allow));
740 }
741
742 match tcx.def_kind(id.owner_id) {
743 DefKind::Enum => {
744 let item = tcx.hir_item(id);
745 if let hir::ItemKind::Enum(_, _, ref enum_def) = item.kind {
746 if let Some(comes_from_allow) = allow_dead_code {
747 worklist.extend(
748 enum_def.variants.iter().map(|variant| (variant.def_id, comes_from_allow)),
749 );
750 }
751
752 for variant in enum_def.variants {
753 if let Some(ctor_def_id) = variant.data.ctor_def_id() {
754 struct_constructors.insert(ctor_def_id, variant.def_id);
755 }
756 }
757 }
758 }
759 DefKind::Impl { of_trait } => {
760 if let Some(comes_from_allow) =
761 has_allow_dead_code_or_lang_attr(tcx, id.owner_id.def_id)
762 {
763 worklist.push((id.owner_id.def_id, comes_from_allow));
764 } else if of_trait {
765 unsolved_items.push((id, id.owner_id.def_id));
766 }
767
768 for def_id in tcx.associated_item_def_ids(id.owner_id) {
769 let local_def_id = def_id.expect_local();
770
771 if let Some(comes_from_allow) = has_allow_dead_code_or_lang_attr(tcx, local_def_id)
772 {
773 worklist.push((local_def_id, comes_from_allow));
774 } else if of_trait {
775 unsolved_items.push((id, local_def_id));
781 }
782 }
783 }
784 DefKind::Struct => {
785 let item = tcx.hir_item(id);
786 if let hir::ItemKind::Struct(_, _, ref variant_data) = item.kind
787 && let Some(ctor_def_id) = variant_data.ctor_def_id()
788 {
789 struct_constructors.insert(ctor_def_id, item.owner_id.def_id);
790 }
791 }
792 DefKind::GlobalAsm => {
793 worklist.push((id.owner_id.def_id, ComesFromAllowExpect::No));
795 }
796 DefKind::Const => {
797 let item = tcx.hir_item(id);
798 if let hir::ItemKind::Const(ident, ..) = item.kind
799 && ident.name == kw::Underscore
800 {
801 worklist.push((id.owner_id.def_id, ComesFromAllowExpect::No));
805 }
806 }
807 _ => {}
808 }
809}
810
811fn check_trait_item(
812 tcx: TyCtxt<'_>,
813 worklist: &mut Vec<(LocalDefId, ComesFromAllowExpect)>,
814 id: hir::TraitItemId,
815) {
816 use hir::TraitItemKind::{Const, Fn, Type};
817
818 let trait_item = tcx.hir_trait_item(id);
819 if matches!(trait_item.kind, Const(_, Some(_)) | Type(_, Some(_)) | Fn(..))
820 && let Some(comes_from_allow) =
821 has_allow_dead_code_or_lang_attr(tcx, trait_item.owner_id.def_id)
822 {
823 worklist.push((trait_item.owner_id.def_id, comes_from_allow));
824 }
825}
826
827fn check_foreign_item(
828 tcx: TyCtxt<'_>,
829 worklist: &mut Vec<(LocalDefId, ComesFromAllowExpect)>,
830 id: hir::ForeignItemId,
831) {
832 if matches!(tcx.def_kind(id.owner_id), DefKind::Static { .. } | DefKind::Fn)
833 && let Some(comes_from_allow) = has_allow_dead_code_or_lang_attr(tcx, id.owner_id.def_id)
834 {
835 worklist.push((id.owner_id.def_id, comes_from_allow));
836 }
837}
838
839fn create_and_seed_worklist(
840 tcx: TyCtxt<'_>,
841) -> (
842 Vec<(LocalDefId, ComesFromAllowExpect)>,
843 LocalDefIdMap<LocalDefId>,
844 Vec<(hir::ItemId, LocalDefId)>,
845) {
846 let effective_visibilities = &tcx.effective_visibilities(());
847 let mut unsolved_impl_item = Vec::new();
849 let mut struct_constructors = Default::default();
850 let mut worklist = effective_visibilities
851 .iter()
852 .filter_map(|(&id, effective_vis)| {
853 effective_vis
854 .is_public_at_level(Level::Reachable)
855 .then_some(id)
856 .map(|id| (id, ComesFromAllowExpect::No))
857 })
858 .chain(
860 tcx.entry_fn(())
861 .and_then(|(def_id, _)| def_id.as_local().map(|id| (id, ComesFromAllowExpect::No))),
862 )
863 .collect::<Vec<_>>();
864
865 let crate_items = tcx.hir_crate_items(());
866 for id in crate_items.free_items() {
867 check_item(tcx, &mut worklist, &mut struct_constructors, &mut unsolved_impl_item, id);
868 }
869
870 for id in crate_items.trait_items() {
871 check_trait_item(tcx, &mut worklist, id);
872 }
873
874 for id in crate_items.foreign_items() {
875 check_foreign_item(tcx, &mut worklist, id);
876 }
877
878 (worklist, struct_constructors, unsolved_impl_item)
879}
880
881fn live_symbols_and_ignored_derived_traits(
882 tcx: TyCtxt<'_>,
883 (): (),
884) -> (LocalDefIdSet, LocalDefIdMap<FxIndexSet<(DefId, DefId)>>) {
885 let (worklist, struct_constructors, mut unsolved_items) = create_and_seed_worklist(tcx);
886 let mut symbol_visitor = MarkSymbolVisitor {
887 worklist,
888 tcx,
889 maybe_typeck_results: None,
890 live_symbols: Default::default(),
891 repr_unconditionally_treats_fields_as_live: false,
892 repr_has_repr_simd: false,
893 in_pat: false,
894 ignore_variant_stack: vec![],
895 struct_constructors,
896 ignored_derived_traits: Default::default(),
897 };
898 symbol_visitor.mark_live_symbols();
899 let mut items_to_check;
900 (items_to_check, unsolved_items) =
901 unsolved_items.into_iter().partition(|&(impl_id, local_def_id)| {
902 symbol_visitor.check_impl_or_impl_item_live(impl_id, local_def_id)
903 });
904
905 while !items_to_check.is_empty() {
906 symbol_visitor.worklist =
907 items_to_check.into_iter().map(|(_, id)| (id, ComesFromAllowExpect::No)).collect();
908 symbol_visitor.mark_live_symbols();
909
910 (items_to_check, unsolved_items) =
911 unsolved_items.into_iter().partition(|&(impl_id, local_def_id)| {
912 symbol_visitor.check_impl_or_impl_item_live(impl_id, local_def_id)
913 });
914 }
915
916 (symbol_visitor.live_symbols, symbol_visitor.ignored_derived_traits)
917}
918
919struct DeadItem {
920 def_id: LocalDefId,
921 name: Symbol,
922 level: (lint::Level, Option<LintExpectationId>),
923}
924
925struct DeadVisitor<'tcx> {
926 tcx: TyCtxt<'tcx>,
927 live_symbols: &'tcx LocalDefIdSet,
928 ignored_derived_traits: &'tcx LocalDefIdMap<FxIndexSet<(DefId, DefId)>>,
929}
930
931enum ShouldWarnAboutField {
932 Yes,
933 No,
934}
935
936#[derive(Debug, Copy, Clone, PartialEq, Eq)]
937enum ReportOn {
938 TupleField,
940 NamedField,
942}
943
944impl<'tcx> DeadVisitor<'tcx> {
945 fn should_warn_about_field(&mut self, field: &ty::FieldDef) -> ShouldWarnAboutField {
946 if self.live_symbols.contains(&field.did.expect_local()) {
947 return ShouldWarnAboutField::No;
948 }
949 let field_type = self.tcx.type_of(field.did).instantiate_identity();
950 if field_type.is_phantom_data() {
951 return ShouldWarnAboutField::No;
952 }
953 let is_positional = field.name.as_str().starts_with(|c: char| c.is_ascii_digit());
954 if is_positional
955 && self
956 .tcx
957 .layout_of(
958 ty::TypingEnv::non_body_analysis(self.tcx, field.did)
959 .as_query_input(field_type),
960 )
961 .map_or(true, |layout| layout.is_zst())
962 {
963 return ShouldWarnAboutField::No;
964 }
965 ShouldWarnAboutField::Yes
966 }
967
968 fn def_lint_level(&self, id: LocalDefId) -> (lint::Level, Option<LintExpectationId>) {
969 let hir_id = self.tcx.local_def_id_to_hir_id(id);
970 let level = self.tcx.lint_level_at_node(DEAD_CODE, hir_id);
971 (level.level, level.lint_id)
972 }
973
974 fn lint_at_single_level(
981 &self,
982 dead_codes: &[&DeadItem],
983 participle: &str,
984 parent_item: Option<LocalDefId>,
985 report_on: ReportOn,
986 ) {
987 fn get_parent_if_enum_variant<'tcx>(
988 tcx: TyCtxt<'tcx>,
989 may_variant: LocalDefId,
990 ) -> LocalDefId {
991 if let Node::Variant(_) = tcx.hir_node_by_def_id(may_variant)
992 && let Some(enum_did) = tcx.opt_parent(may_variant.to_def_id())
993 && let Some(enum_local_id) = enum_did.as_local()
994 && let Node::Item(item) = tcx.hir_node_by_def_id(enum_local_id)
995 && let ItemKind::Enum(..) = item.kind
996 {
997 enum_local_id
998 } else {
999 may_variant
1000 }
1001 }
1002
1003 let Some(&first_item) = dead_codes.first() else {
1004 return;
1005 };
1006 let tcx = self.tcx;
1007
1008 let first_lint_level = first_item.level;
1009 assert!(dead_codes.iter().skip(1).all(|item| item.level == first_lint_level));
1010
1011 let names: Vec<_> = dead_codes.iter().map(|item| item.name).collect();
1012 let spans: Vec<_> = dead_codes
1013 .iter()
1014 .map(|item| match tcx.def_ident_span(item.def_id) {
1015 Some(s) => s.with_ctxt(tcx.def_span(item.def_id).ctxt()),
1016 None => tcx.def_span(item.def_id),
1017 })
1018 .collect();
1019
1020 let descr = tcx.def_descr(first_item.def_id.to_def_id());
1021 let descr = if dead_codes.iter().any(|item| tcx.def_descr(item.def_id.to_def_id()) != descr)
1024 {
1025 "associated item"
1026 } else {
1027 descr
1028 };
1029 let num = dead_codes.len();
1030 let multiple = num > 6;
1031 let name_list = names.into();
1032
1033 let parent_info = if let Some(parent_item) = parent_item {
1034 let parent_descr = tcx.def_descr(parent_item.to_def_id());
1035 let span = if let DefKind::Impl { .. } = tcx.def_kind(parent_item) {
1036 tcx.def_span(parent_item)
1037 } else {
1038 tcx.def_ident_span(parent_item).unwrap()
1039 };
1040 Some(ParentInfo { num, descr, parent_descr, span })
1041 } else {
1042 None
1043 };
1044
1045 let encl_def_id = parent_item.unwrap_or(first_item.def_id);
1046 let encl_def_id = get_parent_if_enum_variant(tcx, encl_def_id);
1048
1049 let ignored_derived_impls =
1050 if let Some(ign_traits) = self.ignored_derived_traits.get(&encl_def_id) {
1051 let trait_list = ign_traits
1052 .iter()
1053 .map(|(trait_id, _)| self.tcx.item_name(*trait_id))
1054 .collect::<Vec<_>>();
1055 let trait_list_len = trait_list.len();
1056 Some(IgnoredDerivedImpls {
1057 name: self.tcx.item_name(encl_def_id.to_def_id()),
1058 trait_list: trait_list.into(),
1059 trait_list_len,
1060 })
1061 } else {
1062 None
1063 };
1064
1065 let enum_variants_with_same_name = dead_codes
1066 .iter()
1067 .filter_map(|dead_item| {
1068 if let Node::ImplItem(ImplItem {
1069 kind: ImplItemKind::Fn(..) | ImplItemKind::Const(..),
1070 ..
1071 }) = tcx.hir_node_by_def_id(dead_item.def_id)
1072 && let Some(impl_did) = tcx.opt_parent(dead_item.def_id.to_def_id())
1073 && let DefKind::Impl { of_trait: false } = tcx.def_kind(impl_did)
1074 && let ty::Adt(maybe_enum, _) = tcx.type_of(impl_did).skip_binder().kind()
1075 && maybe_enum.is_enum()
1076 && let Some(variant) =
1077 maybe_enum.variants().iter().find(|i| i.name == dead_item.name)
1078 {
1079 Some(crate::errors::EnumVariantSameName {
1080 dead_descr: tcx.def_descr(dead_item.def_id.to_def_id()),
1081 dead_name: dead_item.name,
1082 variant_span: tcx.def_span(variant.def_id),
1083 })
1084 } else {
1085 None
1086 }
1087 })
1088 .collect();
1089
1090 let diag = match report_on {
1091 ReportOn::TupleField => {
1092 let tuple_fields = if let Some(parent_id) = parent_item
1093 && let node = tcx.hir_node_by_def_id(parent_id)
1094 && let hir::Node::Item(hir::Item {
1095 kind: hir::ItemKind::Struct(_, _, hir::VariantData::Tuple(fields, _, _)),
1096 ..
1097 }) = node
1098 {
1099 *fields
1100 } else {
1101 &[]
1102 };
1103
1104 let trailing_tuple_fields = if tuple_fields.len() >= dead_codes.len() {
1105 LocalDefIdSet::from_iter(
1106 tuple_fields
1107 .iter()
1108 .skip(tuple_fields.len() - dead_codes.len())
1109 .map(|f| f.def_id),
1110 )
1111 } else {
1112 LocalDefIdSet::default()
1113 };
1114
1115 let fields_suggestion =
1116 if dead_codes.iter().all(|dc| trailing_tuple_fields.contains(&dc.def_id)) {
1119 ChangeFields::Remove { num }
1120 } else {
1121 ChangeFields::ChangeToUnitTypeOrRemove { num, spans: spans.clone() }
1122 };
1123
1124 MultipleDeadCodes::UnusedTupleStructFields {
1125 multiple,
1126 num,
1127 descr,
1128 participle,
1129 name_list,
1130 change_fields_suggestion: fields_suggestion,
1131 parent_info,
1132 ignored_derived_impls,
1133 }
1134 }
1135 ReportOn::NamedField => MultipleDeadCodes::DeadCodes {
1136 multiple,
1137 num,
1138 descr,
1139 participle,
1140 name_list,
1141 parent_info,
1142 ignored_derived_impls,
1143 enum_variants_with_same_name,
1144 },
1145 };
1146
1147 let hir_id = tcx.local_def_id_to_hir_id(first_item.def_id);
1148 self.tcx.emit_node_span_lint(DEAD_CODE, hir_id, MultiSpan::from_spans(spans), diag);
1149 }
1150
1151 fn warn_multiple(
1152 &self,
1153 def_id: LocalDefId,
1154 participle: &str,
1155 dead_codes: Vec<DeadItem>,
1156 report_on: ReportOn,
1157 ) {
1158 let mut dead_codes = dead_codes
1159 .iter()
1160 .filter(|v| !v.name.as_str().starts_with('_'))
1161 .collect::<Vec<&DeadItem>>();
1162 if dead_codes.is_empty() {
1163 return;
1164 }
1165 dead_codes.sort_by_key(|v| v.level.0);
1167 for group in dead_codes.chunk_by(|a, b| a.level == b.level) {
1168 self.lint_at_single_level(&group, participle, Some(def_id), report_on);
1169 }
1170 }
1171
1172 fn warn_dead_code(&mut self, id: LocalDefId, participle: &str) {
1173 let item = DeadItem {
1174 def_id: id,
1175 name: self.tcx.item_name(id.to_def_id()),
1176 level: self.def_lint_level(id),
1177 };
1178 self.lint_at_single_level(&[&item], participle, None, ReportOn::NamedField);
1179 }
1180
1181 fn check_definition(&mut self, def_id: LocalDefId) {
1182 if self.is_live_code(def_id) {
1183 return;
1184 }
1185 match self.tcx.def_kind(def_id) {
1186 DefKind::AssocConst
1187 | DefKind::AssocTy
1188 | DefKind::AssocFn
1189 | DefKind::Fn
1190 | DefKind::Static { .. }
1191 | DefKind::Const
1192 | DefKind::TyAlias
1193 | DefKind::Enum
1194 | DefKind::Union
1195 | DefKind::ForeignTy
1196 | DefKind::Trait => self.warn_dead_code(def_id, "used"),
1197 DefKind::Struct => self.warn_dead_code(def_id, "constructed"),
1198 DefKind::Variant | DefKind::Field => bug!("should be handled specially"),
1199 _ => {}
1200 }
1201 }
1202
1203 fn is_live_code(&self, def_id: LocalDefId) -> bool {
1204 let Some(name) = self.tcx.opt_item_name(def_id.to_def_id()) else {
1207 return true;
1208 };
1209
1210 self.live_symbols.contains(&def_id) || name.as_str().starts_with('_')
1211 }
1212}
1213
1214fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalModDefId) {
1215 let (live_symbols, ignored_derived_traits) = tcx.live_symbols_and_ignored_derived_traits(());
1216 let mut visitor = DeadVisitor { tcx, live_symbols, ignored_derived_traits };
1217
1218 let module_items = tcx.hir_module_items(module);
1219
1220 for item in module_items.free_items() {
1221 let def_kind = tcx.def_kind(item.owner_id);
1222
1223 let mut dead_codes = Vec::new();
1224 if matches!(def_kind, DefKind::Impl { of_trait: false })
1230 || (def_kind == DefKind::Trait && live_symbols.contains(&item.owner_id.def_id))
1231 {
1232 for &def_id in tcx.associated_item_def_ids(item.owner_id.def_id) {
1233 if let Some(local_def_id) = def_id.as_local()
1234 && !visitor.is_live_code(local_def_id)
1235 {
1236 let name = tcx.item_name(def_id);
1237 let level = visitor.def_lint_level(local_def_id);
1238 dead_codes.push(DeadItem { def_id: local_def_id, name, level });
1239 }
1240 }
1241 }
1242 if !dead_codes.is_empty() {
1243 visitor.warn_multiple(item.owner_id.def_id, "used", dead_codes, ReportOn::NamedField);
1244 }
1245
1246 if !live_symbols.contains(&item.owner_id.def_id) {
1247 let parent = tcx.local_parent(item.owner_id.def_id);
1248 if parent != module.to_local_def_id() && !live_symbols.contains(&parent) {
1249 continue;
1251 }
1252 visitor.check_definition(item.owner_id.def_id);
1253 continue;
1254 }
1255
1256 if let DefKind::Struct | DefKind::Union | DefKind::Enum = def_kind {
1257 let adt = tcx.adt_def(item.owner_id);
1258 let mut dead_variants = Vec::new();
1259
1260 for variant in adt.variants() {
1261 let def_id = variant.def_id.expect_local();
1262 if !live_symbols.contains(&def_id) {
1263 let level = visitor.def_lint_level(def_id);
1265 dead_variants.push(DeadItem { def_id, name: variant.name, level });
1266 continue;
1267 }
1268
1269 let is_positional = variant.fields.raw.first().is_some_and(|field| {
1270 field.name.as_str().starts_with(|c: char| c.is_ascii_digit())
1271 });
1272 let report_on =
1273 if is_positional { ReportOn::TupleField } else { ReportOn::NamedField };
1274 let dead_fields = variant
1275 .fields
1276 .iter()
1277 .filter_map(|field| {
1278 let def_id = field.did.expect_local();
1279 if let ShouldWarnAboutField::Yes = visitor.should_warn_about_field(field) {
1280 let level = visitor.def_lint_level(def_id);
1281 Some(DeadItem { def_id, name: field.name, level })
1282 } else {
1283 None
1284 }
1285 })
1286 .collect();
1287 visitor.warn_multiple(def_id, "read", dead_fields, report_on);
1288 }
1289
1290 visitor.warn_multiple(
1291 item.owner_id.def_id,
1292 "constructed",
1293 dead_variants,
1294 ReportOn::NamedField,
1295 );
1296 }
1297 }
1298
1299 for foreign_item in module_items.foreign_items() {
1300 visitor.check_definition(foreign_item.owner_id.def_id);
1301 }
1302}
1303
1304pub(crate) fn provide(providers: &mut Providers) {
1305 *providers =
1306 Providers { live_symbols_and_ignored_derived_traits, check_mod_deathness, ..*providers };
1307}