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