1 // This implements the dead-code warning pass. It follows middle::reachable
2 // closely. The idea is that all reachable symbols are live, codes called
3 // from live codes are live, and everything else is dead.
5 use itertools::Itertools;
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7 use rustc_errors::{pluralize, Applicability, MultiSpan};
9 use rustc_hir::def::{CtorOf, DefKind, Res};
10 use rustc_hir::def_id::{DefId, LocalDefId};
11 use rustc_hir::intravisit::{self, Visitor};
12 use rustc_hir::{Node, PatKind, TyKind};
13 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
14 use rustc_middle::middle::privacy;
15 use rustc_middle::ty::query::Providers;
16 use rustc_middle::ty::{self, DefIdTree, TyCtxt};
17 use rustc_session::lint;
18 use rustc_span::symbol::{sym, Symbol};
21 // Any local node that may call something in its body block should be
22 // explored. For example, if it's a live Node::Item that is a
23 // function, then we should explore its block to check for codes that
24 // may need to be marked as live.
25 fn should_explore(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
27 tcx.hir().find_by_def_id(def_id),
31 | Node::ForeignItem(..)
39 struct MarkSymbolVisitor<'tcx> {
40 worklist: Vec<LocalDefId>,
42 maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
43 live_symbols: FxHashSet<LocalDefId>,
44 repr_has_repr_c: bool,
45 repr_has_repr_simd: bool,
47 ignore_variant_stack: Vec<DefId>,
48 // maps from tuple struct constructors to tuple struct items
49 struct_constructors: FxHashMap<LocalDefId, LocalDefId>,
50 // maps from ADTs to ignored derived traits (e.g. Debug and Clone)
51 // and the span of their respective impl (i.e., part of the derive
53 ignored_derived_traits: FxHashMap<LocalDefId, Vec<(DefId, DefId)>>,
56 impl<'tcx> MarkSymbolVisitor<'tcx> {
57 /// Gets the type-checking results for the current body.
58 /// As this will ICE if called outside bodies, only call when working with
59 /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
61 fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
62 self.maybe_typeck_results
63 .expect("`MarkSymbolVisitor::typeck_results` called outside of body")
66 fn check_def_id(&mut self, def_id: DefId) {
67 if let Some(def_id) = def_id.as_local() {
68 if should_explore(self.tcx, def_id) || self.struct_constructors.contains_key(&def_id) {
69 self.worklist.push(def_id);
71 self.live_symbols.insert(def_id);
75 fn insert_def_id(&mut self, def_id: DefId) {
76 if let Some(def_id) = def_id.as_local() {
77 debug_assert!(!should_explore(self.tcx, def_id));
78 self.live_symbols.insert(def_id);
82 fn handle_res(&mut self, res: Res) {
84 Res::Def(DefKind::Const | DefKind::AssocConst | DefKind::TyAlias, def_id) => {
85 self.check_def_id(def_id);
87 _ if self.in_pat => {}
88 Res::PrimTy(..) | Res::SelfCtor(..) | Res::Local(..) => {}
89 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), ctor_def_id) => {
90 let variant_id = self.tcx.parent(ctor_def_id);
91 let enum_id = self.tcx.parent(variant_id);
92 self.check_def_id(enum_id);
93 if !self.ignore_variant_stack.contains(&ctor_def_id) {
94 self.check_def_id(variant_id);
97 Res::Def(DefKind::Variant, variant_id) => {
98 let enum_id = self.tcx.parent(variant_id);
99 self.check_def_id(enum_id);
100 if !self.ignore_variant_stack.contains(&variant_id) {
101 self.check_def_id(variant_id);
104 Res::Def(_, def_id) => self.check_def_id(def_id),
105 Res::SelfTy { trait_: t, alias_to: i } => {
107 self.check_def_id(t);
109 if let Some((i, _)) = i {
110 self.check_def_id(i);
113 Res::ToolMod | Res::NonMacroAttr(..) | Res::Err => {}
117 fn lookup_and_handle_method(&mut self, id: hir::HirId) {
118 if let Some(def_id) = self.typeck_results().type_dependent_def_id(id) {
119 self.check_def_id(def_id);
121 bug!("no type-dependent def for method");
125 fn handle_field_access(&mut self, lhs: &hir::Expr<'_>, hir_id: hir::HirId) {
126 match self.typeck_results().expr_ty_adjusted(lhs).kind() {
128 let index = self.tcx.field_index(hir_id, self.typeck_results());
129 self.insert_def_id(def.non_enum_variant().fields[index].did);
132 _ => span_bug!(lhs.span, "named field access on non-ADT"),
136 #[allow(dead_code)] // FIXME(81658): should be used + lint reinstated after #83171 relands.
137 fn handle_assign(&mut self, expr: &'tcx hir::Expr<'tcx>) {
140 .expr_adjustments(expr)
142 .any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(_)))
144 self.visit_expr(expr);
145 } else if let hir::ExprKind::Field(base, ..) = expr.kind {
146 // Ignore write to field
147 self.handle_assign(base);
149 self.visit_expr(expr);
153 #[allow(dead_code)] // FIXME(81658): should be used + lint reinstated after #83171 relands.
154 fn check_for_self_assign(&mut self, assign: &'tcx hir::Expr<'tcx>) {
155 fn check_for_self_assign_helper<'tcx>(
156 typeck_results: &'tcx ty::TypeckResults<'tcx>,
157 lhs: &'tcx hir::Expr<'tcx>,
158 rhs: &'tcx hir::Expr<'tcx>,
160 match (&lhs.kind, &rhs.kind) {
161 (hir::ExprKind::Path(ref qpath_l), hir::ExprKind::Path(ref qpath_r)) => {
162 if let (Res::Local(id_l), Res::Local(id_r)) = (
163 typeck_results.qpath_res(qpath_l, lhs.hir_id),
164 typeck_results.qpath_res(qpath_r, rhs.hir_id),
172 (hir::ExprKind::Field(lhs_l, ident_l), hir::ExprKind::Field(lhs_r, ident_r)) => {
173 if ident_l == ident_r {
174 return check_for_self_assign_helper(typeck_results, lhs_l, lhs_r);
184 if let hir::ExprKind::Assign(lhs, rhs, _) = assign.kind
185 && check_for_self_assign_helper(self.typeck_results(), lhs, rhs)
186 && !assign.span.from_expansion()
188 let is_field_assign = matches!(lhs.kind, hir::ExprKind::Field(..));
189 self.tcx.struct_span_lint_hir(
190 lint::builtin::DEAD_CODE,
195 "useless assignment of {} of type `{}` to itself",
196 if is_field_assign { "field" } else { "variable" },
197 self.typeck_results().expr_ty(lhs),
205 fn handle_field_pattern_match(
209 pats: &[hir::PatField<'_>],
211 let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
212 ty::Adt(adt, _) => adt.variant_of_res(res),
213 _ => span_bug!(lhs.span, "non-ADT in struct pattern"),
216 if let PatKind::Wild = pat.pat.kind {
219 let index = self.tcx.field_index(pat.hir_id, self.typeck_results());
220 self.insert_def_id(variant.fields[index].did);
224 fn handle_tuple_field_pattern_match(
228 pats: &[hir::Pat<'_>],
229 dotdot: hir::DotDotPos,
231 let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
232 ty::Adt(adt, _) => adt.variant_of_res(res),
233 _ => span_bug!(lhs.span, "non-ADT in tuple struct pattern"),
235 let dotdot = dotdot.as_opt_usize().unwrap_or(pats.len());
236 let first_n = pats.iter().enumerate().take(dotdot);
237 let missing = variant.fields.len() - pats.len();
238 let last_n = pats.iter().enumerate().skip(dotdot).map(|(idx, pat)| (idx + missing, pat));
239 for (idx, pat) in first_n.chain(last_n) {
240 if let PatKind::Wild = pat.kind {
243 self.insert_def_id(variant.fields[idx].did);
247 fn mark_live_symbols(&mut self) {
248 let mut scanned = FxHashSet::default();
249 while let Some(id) = self.worklist.pop() {
250 if !scanned.insert(id) {
254 // in the case of tuple struct constructors we want to check the item, not the generated
255 // tuple struct constructor function
256 let id = self.struct_constructors.get(&id).copied().unwrap_or(id);
258 if let Some(node) = self.tcx.hir().find_by_def_id(id) {
259 self.live_symbols.insert(id);
260 self.visit_node(node);
265 /// Automatically generated items marked with `rustc_trivial_field_reads`
266 /// will be ignored for the purposes of dead code analysis (see PR #85200
268 fn should_ignore_item(&mut self, def_id: DefId) -> bool {
269 if let Some(impl_of) = self.tcx.impl_of_method(def_id) {
270 if !self.tcx.has_attr(impl_of, sym::automatically_derived) {
274 if let Some(trait_of) = self.tcx.trait_id_of_impl(impl_of)
275 && self.tcx.has_attr(trait_of, sym::rustc_trivial_field_reads)
277 let trait_ref = self.tcx.impl_trait_ref(impl_of).unwrap();
278 if let ty::Adt(adt_def, _) = trait_ref.self_ty().kind()
279 && let Some(adt_def_id) = adt_def.did().as_local()
281 self.ignored_derived_traits
284 .push((trait_of, impl_of));
293 fn visit_node(&mut self, node: Node<'tcx>) {
294 if let Node::ImplItem(hir::ImplItem { def_id, .. }) = node
295 && self.should_ignore_item(def_id.to_def_id())
300 let had_repr_c = self.repr_has_repr_c;
301 let had_repr_simd = self.repr_has_repr_simd;
302 self.repr_has_repr_c = false;
303 self.repr_has_repr_simd = false;
305 Node::Item(item) => match item.kind {
306 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
307 let def = self.tcx.adt_def(item.def_id);
308 self.repr_has_repr_c = def.repr().c();
309 self.repr_has_repr_simd = def.repr().simd();
311 intravisit::walk_item(self, &item)
313 hir::ItemKind::ForeignMod { .. } => {}
314 _ => intravisit::walk_item(self, &item),
316 Node::TraitItem(trait_item) => {
317 intravisit::walk_trait_item(self, trait_item);
319 Node::ImplItem(impl_item) => {
320 let item = self.tcx.local_parent(impl_item.def_id);
321 if self.tcx.impl_trait_ref(item).is_none() {
322 //// If it's a type whose items are live, then it's live, too.
323 //// This is done to handle the case where, for example, the static
324 //// method of a private type is used, but the type itself is never
325 //// called directly.
326 let self_ty = self.tcx.type_of(item);
327 match *self_ty.kind() {
328 ty::Adt(def, _) => self.check_def_id(def.did()),
329 ty::Foreign(did) => self.check_def_id(did),
330 ty::Dynamic(data, ..) => {
331 if let Some(def_id) = data.principal_def_id() {
332 self.check_def_id(def_id)
338 intravisit::walk_impl_item(self, impl_item);
340 Node::ForeignItem(foreign_item) => {
341 intravisit::walk_foreign_item(self, &foreign_item);
345 self.repr_has_repr_simd = had_repr_simd;
346 self.repr_has_repr_c = had_repr_c;
349 fn mark_as_used_if_union(&mut self, adt: ty::AdtDef<'tcx>, fields: &[hir::ExprField<'_>]) {
350 if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did().is_local() {
351 for field in fields {
352 let index = self.tcx.field_index(field.hir_id, self.typeck_results());
353 self.insert_def_id(adt.non_enum_variant().fields[index].did);
359 impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
360 fn visit_nested_body(&mut self, body: hir::BodyId) {
361 let old_maybe_typeck_results =
362 self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
363 let body = self.tcx.hir().body(body);
364 self.visit_body(body);
365 self.maybe_typeck_results = old_maybe_typeck_results;
368 fn visit_variant_data(&mut self, def: &'tcx hir::VariantData<'tcx>) {
370 let has_repr_c = self.repr_has_repr_c;
371 let has_repr_simd = self.repr_has_repr_simd;
372 let live_fields = def.fields().iter().filter_map(|f| {
373 let def_id = tcx.hir().local_def_id(f.hir_id);
374 if has_repr_c || (f.is_positional() && has_repr_simd) {
377 if !tcx.visibility(f.hir_id.owner).is_public() {
380 if tcx.visibility(def_id).is_public() { Some(def_id) } else { None }
382 self.live_symbols.extend(live_fields);
384 intravisit::walk_struct_def(self, def);
387 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
389 hir::ExprKind::Path(ref qpath @ hir::QPath::TypeRelative(..)) => {
390 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
391 self.handle_res(res);
393 hir::ExprKind::MethodCall(..) => {
394 self.lookup_and_handle_method(expr.hir_id);
396 hir::ExprKind::Field(ref lhs, ..) => {
397 self.handle_field_access(&lhs, expr.hir_id);
399 hir::ExprKind::Struct(ref qpath, ref fields, _) => {
400 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
401 self.handle_res(res);
402 if let ty::Adt(adt, _) = self.typeck_results().expr_ty(expr).kind() {
403 self.mark_as_used_if_union(*adt, fields);
409 intravisit::walk_expr(self, expr);
412 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
413 // Inside the body, ignore constructions of variants
414 // necessary for the pattern to match. Those construction sites
415 // can't be reached unless the variant is constructed elsewhere.
416 let len = self.ignore_variant_stack.len();
417 self.ignore_variant_stack.extend(arm.pat.necessary_variants());
418 intravisit::walk_arm(self, arm);
419 self.ignore_variant_stack.truncate(len);
422 fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
425 PatKind::Struct(ref path, ref fields, _) => {
426 let res = self.typeck_results().qpath_res(path, pat.hir_id);
427 self.handle_field_pattern_match(pat, res, fields);
429 PatKind::Path(ref qpath) => {
430 let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
431 self.handle_res(res);
433 PatKind::TupleStruct(ref qpath, ref fields, dotdot) => {
434 let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
435 self.handle_tuple_field_pattern_match(pat, res, fields, dotdot);
440 intravisit::walk_pat(self, pat);
444 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
445 self.handle_res(path.res);
446 intravisit::walk_path(self, path);
449 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
450 if let TyKind::OpaqueDef(item_id, _, _) = ty.kind {
451 let item = self.tcx.hir().item(item_id);
452 intravisit::walk_item(self, item);
454 intravisit::walk_ty(self, ty);
457 fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
458 // When inline const blocks are used in pattern position, paths
459 // referenced by it should be considered as used.
460 let in_pat = mem::replace(&mut self.in_pat, false);
462 self.live_symbols.insert(self.tcx.hir().local_def_id(c.hir_id));
463 intravisit::walk_anon_const(self, c);
465 self.in_pat = in_pat;
469 fn has_allow_dead_code_or_lang_attr_helper(
472 lint: &'static lint::Lint,
474 let attrs = tcx.hir().attrs(id);
475 if tcx.sess.contains_name(attrs, sym::lang) {
479 // Stable attribute for #[lang = "panic_impl"]
480 if tcx.sess.contains_name(attrs, sym::panic_handler) {
484 // (To be) stable attribute for #[lang = "oom"]
485 if tcx.sess.contains_name(attrs, sym::alloc_error_handler) {
489 let def_id = tcx.hir().local_def_id(id);
490 if tcx.def_kind(def_id).has_codegen_attrs() {
491 let cg_attrs = tcx.codegen_fn_attrs(def_id);
493 // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
494 // forcefully, e.g., for placing it in a specific section.
495 if cg_attrs.contains_extern_indicator()
496 || cg_attrs.flags.contains(CodegenFnAttrFlags::USED)
497 || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)
503 tcx.lint_level_at_node(lint, id).0 == lint::Allow
506 fn has_allow_dead_code_or_lang_attr(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {
507 has_allow_dead_code_or_lang_attr_helper(tcx, id, lint::builtin::DEAD_CODE)
510 // These check_* functions seeds items that
511 // 1) We want to explicitly consider as live:
512 // * Item annotated with #[allow(dead_code)]
513 // - This is done so that if we want to suppress warnings for a
514 // group of dead functions, we only have to annotate the "root".
515 // For example, if both `f` and `g` are dead and `f` calls `g`,
516 // then annotating `f` with `#[allow(dead_code)]` will suppress
517 // warning for both `f` and `g`.
518 // * Item annotated with #[lang=".."]
519 // - This is because lang items are always callable from elsewhere.
521 // 2) We are not sure to be live or not
522 // * Implementations of traits and trait methods
525 worklist: &mut Vec<LocalDefId>,
526 struct_constructors: &mut FxHashMap<LocalDefId, LocalDefId>,
529 let allow_dead_code = has_allow_dead_code_or_lang_attr(tcx, id.hir_id());
531 worklist.push(id.def_id);
534 match tcx.def_kind(id.def_id) {
536 let item = tcx.hir().item(id);
537 if let hir::ItemKind::Enum(ref enum_def, _) = item.kind {
541 enum_def.variants.iter().map(|variant| hir.local_def_id(variant.id)),
545 for variant in enum_def.variants {
546 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
548 .insert(hir.local_def_id(ctor_hir_id), hir.local_def_id(variant.id));
554 let of_trait = tcx.impl_trait_ref(id.def_id);
556 if of_trait.is_some() {
557 worklist.push(id.def_id);
560 // get DefIds from another query
561 let local_def_ids = tcx
562 .associated_item_def_ids(id.def_id)
564 .filter_map(|def_id| def_id.as_local());
566 // And we access the Map here to get HirId from LocalDefId
567 for id in local_def_ids {
568 if of_trait.is_some()
569 || has_allow_dead_code_or_lang_attr(tcx, tcx.hir().local_def_id_to_hir_id(id))
576 let item = tcx.hir().item(id);
577 if let hir::ItemKind::Struct(ref variant_data, _) = item.kind
578 && let Some(ctor_hir_id) = variant_data.ctor_hir_id()
580 struct_constructors.insert(tcx.hir().local_def_id(ctor_hir_id), item.def_id);
583 DefKind::GlobalAsm => {
584 // global_asm! is always live.
585 worklist.push(id.def_id);
591 fn check_trait_item<'tcx>(tcx: TyCtxt<'tcx>, worklist: &mut Vec<LocalDefId>, id: hir::TraitItemId) {
592 use hir::TraitItemKind::{Const, Fn};
593 if matches!(tcx.def_kind(id.def_id), DefKind::AssocConst | DefKind::AssocFn) {
594 let trait_item = tcx.hir().trait_item(id);
595 if matches!(trait_item.kind, Const(_, Some(_)) | Fn(_, hir::TraitFn::Provided(_)))
596 && has_allow_dead_code_or_lang_attr(tcx, trait_item.hir_id())
598 worklist.push(trait_item.def_id);
603 fn check_foreign_item<'tcx>(
605 worklist: &mut Vec<LocalDefId>,
606 id: hir::ForeignItemId,
608 if matches!(tcx.def_kind(id.def_id), DefKind::Static(_) | DefKind::Fn)
609 && has_allow_dead_code_or_lang_attr(tcx, id.hir_id())
611 worklist.push(id.def_id);
615 fn create_and_seed_worklist<'tcx>(
617 ) -> (Vec<LocalDefId>, FxHashMap<LocalDefId, LocalDefId>) {
618 let access_levels = &tcx.privacy_access_levels(());
619 // see `MarkSymbolVisitor::struct_constructors`
620 let mut struct_constructors = Default::default();
621 let mut worklist = access_levels
626 if level >= privacy::AccessLevel::Reachable { Some(id) } else { None }
630 .chain(tcx.entry_fn(()).and_then(|(def_id, _)| def_id.as_local()))
631 .collect::<Vec<_>>();
633 let crate_items = tcx.hir_crate_items(());
634 for id in crate_items.items() {
635 check_item(tcx, &mut worklist, &mut struct_constructors, id);
638 for id in crate_items.trait_items() {
639 check_trait_item(tcx, &mut worklist, id);
642 for id in crate_items.foreign_items() {
643 check_foreign_item(tcx, &mut worklist, id);
646 (worklist, struct_constructors)
649 fn live_symbols_and_ignored_derived_traits<'tcx>(
652 ) -> (FxHashSet<LocalDefId>, FxHashMap<LocalDefId, Vec<(DefId, DefId)>>) {
653 let (worklist, struct_constructors) = create_and_seed_worklist(tcx);
654 let mut symbol_visitor = MarkSymbolVisitor {
657 maybe_typeck_results: None,
658 live_symbols: Default::default(),
659 repr_has_repr_c: false,
660 repr_has_repr_simd: false,
662 ignore_variant_stack: vec![],
664 ignored_derived_traits: FxHashMap::default(),
666 symbol_visitor.mark_live_symbols();
667 (symbol_visitor.live_symbols, symbol_visitor.ignored_derived_traits)
676 struct DeadVisitor<'tcx> {
678 live_symbols: &'tcx FxHashSet<LocalDefId>,
679 ignored_derived_traits: &'tcx FxHashMap<LocalDefId, Vec<(DefId, DefId)>>,
682 enum ShouldWarnAboutField {
683 Yes(bool), // positional?
687 impl<'tcx> DeadVisitor<'tcx> {
688 fn should_warn_about_field(&mut self, field: &ty::FieldDef) -> ShouldWarnAboutField {
689 if self.live_symbols.contains(&field.did.expect_local()) {
690 return ShouldWarnAboutField::No;
692 let field_type = self.tcx.type_of(field.did);
693 if field_type.is_phantom_data() {
694 return ShouldWarnAboutField::No;
696 let is_positional = field.name.as_str().starts_with(|c: char| c.is_ascii_digit());
700 .layout_of(self.tcx.param_env(field.did).and(field_type))
701 .map_or(true, |layout| layout.is_zst())
703 return ShouldWarnAboutField::No;
705 ShouldWarnAboutField::Yes(is_positional)
708 fn warn_multiple_dead_codes(
710 dead_codes: &[LocalDefId],
712 parent_item: Option<LocalDefId>,
715 if let Some(&first_id) = dead_codes.first() {
717 let names: Vec<_> = dead_codes
719 .map(|&def_id| tcx.item_name(def_id.to_def_id()).to_string())
721 let spans: Vec<_> = dead_codes
723 .map(|&def_id| match tcx.def_ident_span(def_id) {
724 Some(s) => s.with_ctxt(tcx.def_span(def_id).ctxt()),
725 None => tcx.def_span(def_id),
729 tcx.struct_span_lint_hir(
731 lint::builtin::UNUSED_TUPLE_STRUCT_FIELDS
733 lint::builtin::DEAD_CODE
735 tcx.hir().local_def_id_to_hir_id(first_id),
736 MultiSpan::from_spans(spans.clone()),
738 let descr = tcx.def_kind(first_id).descr(first_id.to_def_id());
739 let span_len = dead_codes.len();
740 let names = match &names[..] {
741 _ if span_len > 6 => String::new(),
742 [name] => format!("`{name}` "),
743 [names @ .., last] => {
746 names.iter().map(|name| format!("`{name}`")).join(", ")
749 [] => unreachable!(),
751 let mut err = lint.build(&format!(
752 "{these}{descr}{s} {names}{are} never {participle}",
753 these = if span_len > 6 { "multiple " } else { "" },
754 s = pluralize!(span_len),
755 are = pluralize!("is", span_len),
759 err.multipart_suggestion(
761 "consider changing the field{s} to be of unit type to \
762 suppress this warning while preserving the field \
763 numbering, or remove the field{s}",
764 s = pluralize!(span_len)
766 spans.iter().map(|sp| (*sp, "()".to_string())).collect(),
767 // "HasPlaceholders" because applying this fix by itself isn't
768 // enough: All constructor calls have to be adjusted as well
769 Applicability::HasPlaceholders,
773 if let Some(parent_item) = parent_item {
774 let parent_descr = tcx.def_kind(parent_item).descr(parent_item.to_def_id());
776 tcx.def_ident_span(parent_item).unwrap(),
777 format!("{descr}{s} in this {parent_descr}", s = pluralize!(span_len)),
781 let encl_def_id = parent_item.unwrap_or(first_id);
782 if let Some(ign_traits) = self.ignored_derived_traits.get(&encl_def_id) {
783 let traits_str = ign_traits
785 .map(|(trait_id, _)| format!("`{}`", self.tcx.item_name(*trait_id)))
788 let plural_s = pluralize!(ign_traits.len());
789 let article = if ign_traits.len() > 1 { "" } else { "a " };
790 let is_are = if ign_traits.len() > 1 { "these are" } else { "this is" };
792 "`{}` has {}derived impl{} for the trait{} {}, but {} \
793 intentionally ignored during dead code analysis",
794 self.tcx.item_name(encl_def_id.to_def_id()),
809 fn warn_dead_fields_and_variants(
813 dead_codes: Vec<DeadVariant>,
816 let mut dead_codes = dead_codes
818 .filter(|v| !v.name.as_str().starts_with('_'))
820 .collect::<Vec<&DeadVariant>>();
821 if dead_codes.is_empty() {
824 dead_codes.sort_by_key(|v| v.level);
825 for (_, group) in &dead_codes.into_iter().group_by(|v| v.level) {
826 self.warn_multiple_dead_codes(
827 &group.map(|v| v.def_id).collect::<Vec<_>>(),
835 fn warn_dead_code(&mut self, id: LocalDefId, participle: &str) {
836 self.warn_multiple_dead_codes(&[id], participle, None, false);
839 fn check_definition(&mut self, def_id: LocalDefId) {
840 if self.live_symbols.contains(&def_id) {
843 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
844 if has_allow_dead_code_or_lang_attr(self.tcx, hir_id) {
847 let Some(name) = self.tcx.opt_item_name(def_id.to_def_id()) else {
850 if name.as_str().starts_with('_') {
853 match self.tcx.def_kind(def_id) {
862 | DefKind::ForeignTy => self.warn_dead_code(def_id, "used"),
863 DefKind::Struct => self.warn_dead_code(def_id, "constructed"),
864 DefKind::Variant | DefKind::Field => bug!("should be handled specially"),
870 fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalDefId) {
871 let (live_symbols, ignored_derived_traits) = tcx.live_symbols_and_ignored_derived_traits(());
872 let mut visitor = DeadVisitor { tcx, live_symbols, ignored_derived_traits };
874 let module_items = tcx.hir_module_items(module);
876 for item in module_items.items() {
877 if !live_symbols.contains(&item.def_id) {
878 let parent = tcx.local_parent(item.def_id);
879 if parent != module && !live_symbols.contains(&parent) {
880 // We already have diagnosed something.
883 visitor.check_definition(item.def_id);
887 let def_kind = tcx.def_kind(item.def_id);
888 if let DefKind::Struct | DefKind::Union | DefKind::Enum = def_kind {
889 let adt = tcx.adt_def(item.def_id);
890 let mut dead_variants = Vec::new();
892 for variant in adt.variants() {
893 let def_id = variant.def_id.expect_local();
894 if !live_symbols.contains(&def_id) {
895 // Record to group diagnostics.
896 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
897 let level = tcx.lint_level_at_node(lint::builtin::DEAD_CODE, hir_id).0;
898 dead_variants.push(DeadVariant { def_id, name: variant.name, level });
902 let mut is_positional = false;
903 let dead_fields = variant
906 .filter_map(|field| {
907 let def_id = field.did.expect_local();
908 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
909 if let ShouldWarnAboutField::Yes(is_pos) =
910 visitor.should_warn_about_field(&field)
915 is_positional = true;
916 lint::builtin::UNUSED_TUPLE_STRUCT_FIELDS
918 lint::builtin::DEAD_CODE
923 Some(DeadVariant { def_id, name: field.name, level })
929 visitor.warn_dead_fields_and_variants(def_id, "read", dead_fields, is_positional)
932 visitor.warn_dead_fields_and_variants(item.def_id, "constructed", dead_variants, false);
936 for impl_item in module_items.impl_items() {
937 visitor.check_definition(impl_item.def_id);
940 for foreign_item in module_items.foreign_items() {
941 visitor.check_definition(foreign_item.def_id);
944 // We do not warn trait items.
947 pub(crate) fn provide(providers: &mut Providers) {
949 Providers { live_symbols_and_ignored_derived_traits, check_mod_deathness, ..*providers };