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