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: Option<usize>,
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 first_n = pats.iter().enumerate().take(dotdot.unwrap_or(pats.len()));
236 let missing = variant.fields.len() - pats.len();
240 .skip(dotdot.unwrap_or(pats.len()))
241 .map(|(idx, pat)| (idx + missing, pat));
242 for (idx, pat) in first_n.chain(last_n) {
243 if let PatKind::Wild = pat.kind {
246 self.insert_def_id(variant.fields[idx].did);
250 fn mark_live_symbols(&mut self) {
251 let mut scanned = FxHashSet::default();
252 while let Some(id) = self.worklist.pop() {
253 if !scanned.insert(id) {
257 // in the case of tuple struct constructors we want to check the item, not the generated
258 // tuple struct constructor function
259 let id = self.struct_constructors.get(&id).copied().unwrap_or(id);
261 if let Some(node) = self.tcx.hir().find_by_def_id(id) {
262 self.live_symbols.insert(id);
263 self.visit_node(node);
268 /// Automatically generated items marked with `rustc_trivial_field_reads`
269 /// will be ignored for the purposes of dead code analysis (see PR #85200
271 fn should_ignore_item(&mut self, def_id: DefId) -> bool {
272 if let Some(impl_of) = self.tcx.impl_of_method(def_id) {
273 if !self.tcx.has_attr(impl_of, sym::automatically_derived) {
277 if let Some(trait_of) = self.tcx.trait_id_of_impl(impl_of)
278 && self.tcx.has_attr(trait_of, sym::rustc_trivial_field_reads)
280 let trait_ref = self.tcx.impl_trait_ref(impl_of).unwrap();
281 if let ty::Adt(adt_def, _) = trait_ref.self_ty().kind()
282 && let Some(adt_def_id) = adt_def.did().as_local()
284 self.ignored_derived_traits
287 .push((trait_of, impl_of));
296 fn visit_node(&mut self, node: Node<'tcx>) {
297 if let Node::ImplItem(hir::ImplItem { def_id, .. }) = node
298 && self.should_ignore_item(def_id.to_def_id())
303 let had_repr_c = self.repr_has_repr_c;
304 let had_repr_simd = self.repr_has_repr_simd;
305 self.repr_has_repr_c = false;
306 self.repr_has_repr_simd = false;
308 Node::Item(item) => match item.kind {
309 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
310 let def = self.tcx.adt_def(item.def_id);
311 self.repr_has_repr_c = def.repr().c();
312 self.repr_has_repr_simd = def.repr().simd();
314 intravisit::walk_item(self, &item)
316 hir::ItemKind::ForeignMod { .. } => {}
317 _ => intravisit::walk_item(self, &item),
319 Node::TraitItem(trait_item) => {
320 intravisit::walk_trait_item(self, trait_item);
322 Node::ImplItem(impl_item) => {
323 let item = self.tcx.local_parent(impl_item.def_id);
324 if self.tcx.impl_trait_ref(item).is_none() {
325 //// If it's a type whose items are live, then it's live, too.
326 //// This is done to handle the case where, for example, the static
327 //// method of a private type is used, but the type itself is never
328 //// called directly.
329 let self_ty = self.tcx.type_of(item);
330 match *self_ty.kind() {
331 ty::Adt(def, _) => self.check_def_id(def.did()),
332 ty::Foreign(did) => self.check_def_id(did),
333 ty::Dynamic(data, ..) => {
334 if let Some(def_id) = data.principal_def_id() {
335 self.check_def_id(def_id)
341 intravisit::walk_impl_item(self, impl_item);
343 Node::ForeignItem(foreign_item) => {
344 intravisit::walk_foreign_item(self, &foreign_item);
348 self.repr_has_repr_simd = had_repr_simd;
349 self.repr_has_repr_c = had_repr_c;
352 fn mark_as_used_if_union(&mut self, adt: ty::AdtDef<'tcx>, fields: &[hir::ExprField<'_>]) {
353 if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did().is_local() {
354 for field in fields {
355 let index = self.tcx.field_index(field.hir_id, self.typeck_results());
356 self.insert_def_id(adt.non_enum_variant().fields[index].did);
362 impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
363 fn visit_nested_body(&mut self, body: hir::BodyId) {
364 let old_maybe_typeck_results =
365 self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
366 let body = self.tcx.hir().body(body);
367 self.visit_body(body);
368 self.maybe_typeck_results = old_maybe_typeck_results;
371 fn visit_variant_data(
373 def: &'tcx hir::VariantData<'tcx>,
375 _: &hir::Generics<'_>,
380 let has_repr_c = self.repr_has_repr_c;
381 let has_repr_simd = self.repr_has_repr_simd;
382 let live_fields = def.fields().iter().filter_map(|f| {
383 let def_id = tcx.hir().local_def_id(f.hir_id);
384 if has_repr_c || (f.is_positional() && has_repr_simd) {
387 if !tcx.visibility(f.hir_id.owner).is_public() {
390 if tcx.visibility(def_id).is_public() { Some(def_id) } else { None }
392 self.live_symbols.extend(live_fields);
394 intravisit::walk_struct_def(self, def);
397 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
399 hir::ExprKind::Path(ref qpath @ hir::QPath::TypeRelative(..)) => {
400 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
401 self.handle_res(res);
403 hir::ExprKind::MethodCall(..) => {
404 self.lookup_and_handle_method(expr.hir_id);
406 hir::ExprKind::Field(ref lhs, ..) => {
407 self.handle_field_access(&lhs, expr.hir_id);
409 hir::ExprKind::Struct(ref qpath, ref fields, _) => {
410 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
411 self.handle_res(res);
412 if let ty::Adt(adt, _) = self.typeck_results().expr_ty(expr).kind() {
413 self.mark_as_used_if_union(*adt, fields);
419 intravisit::walk_expr(self, expr);
422 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
423 // Inside the body, ignore constructions of variants
424 // necessary for the pattern to match. Those construction sites
425 // can't be reached unless the variant is constructed elsewhere.
426 let len = self.ignore_variant_stack.len();
427 self.ignore_variant_stack.extend(arm.pat.necessary_variants());
428 intravisit::walk_arm(self, arm);
429 self.ignore_variant_stack.truncate(len);
432 fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
435 PatKind::Struct(ref path, ref fields, _) => {
436 let res = self.typeck_results().qpath_res(path, pat.hir_id);
437 self.handle_field_pattern_match(pat, res, fields);
439 PatKind::Path(ref qpath) => {
440 let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
441 self.handle_res(res);
443 PatKind::TupleStruct(ref qpath, ref fields, dotdot) => {
444 let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
445 self.handle_tuple_field_pattern_match(pat, res, fields, dotdot);
450 intravisit::walk_pat(self, pat);
454 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
455 self.handle_res(path.res);
456 intravisit::walk_path(self, path);
459 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
460 if let TyKind::OpaqueDef(item_id, _) = ty.kind {
461 let item = self.tcx.hir().item(item_id);
462 intravisit::walk_item(self, item);
464 intravisit::walk_ty(self, ty);
467 fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
468 // When inline const blocks are used in pattern position, paths
469 // referenced by it should be considered as used.
470 let in_pat = mem::replace(&mut self.in_pat, false);
472 self.live_symbols.insert(self.tcx.hir().local_def_id(c.hir_id));
473 intravisit::walk_anon_const(self, c);
475 self.in_pat = in_pat;
479 fn has_allow_dead_code_or_lang_attr_helper(
482 lint: &'static lint::Lint,
484 let attrs = tcx.hir().attrs(id);
485 if tcx.sess.contains_name(attrs, sym::lang) {
489 // Stable attribute for #[lang = "panic_impl"]
490 if tcx.sess.contains_name(attrs, sym::panic_handler) {
494 // (To be) stable attribute for #[lang = "oom"]
495 if tcx.sess.contains_name(attrs, sym::alloc_error_handler) {
499 let def_id = tcx.hir().local_def_id(id);
500 if tcx.def_kind(def_id).has_codegen_attrs() {
501 let cg_attrs = tcx.codegen_fn_attrs(def_id);
503 // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
504 // forcefully, e.g., for placing it in a specific section.
505 if cg_attrs.contains_extern_indicator()
506 || cg_attrs.flags.contains(CodegenFnAttrFlags::USED)
507 || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)
513 tcx.lint_level_at_node(lint, id).0 == lint::Allow
516 fn has_allow_dead_code_or_lang_attr(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {
517 has_allow_dead_code_or_lang_attr_helper(tcx, id, lint::builtin::DEAD_CODE)
520 // These check_* functions seeds items that
521 // 1) We want to explicitly consider as live:
522 // * Item annotated with #[allow(dead_code)]
523 // - This is done so that if we want to suppress warnings for a
524 // group of dead functions, we only have to annotate the "root".
525 // For example, if both `f` and `g` are dead and `f` calls `g`,
526 // then annotating `f` with `#[allow(dead_code)]` will suppress
527 // warning for both `f` and `g`.
528 // * Item annotated with #[lang=".."]
529 // - This is because lang items are always callable from elsewhere.
531 // 2) We are not sure to be live or not
532 // * Implementations of traits and trait methods
535 worklist: &mut Vec<LocalDefId>,
536 struct_constructors: &mut FxHashMap<LocalDefId, LocalDefId>,
539 let allow_dead_code = has_allow_dead_code_or_lang_attr(tcx, id.hir_id());
541 worklist.push(id.def_id);
544 match tcx.def_kind(id.def_id) {
546 let item = tcx.hir().item(id);
547 if let hir::ItemKind::Enum(ref enum_def, _) = item.kind {
551 enum_def.variants.iter().map(|variant| hir.local_def_id(variant.id)),
555 for variant in enum_def.variants {
556 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
558 .insert(hir.local_def_id(ctor_hir_id), hir.local_def_id(variant.id));
564 let of_trait = tcx.impl_trait_ref(id.def_id);
566 if of_trait.is_some() {
567 worklist.push(id.def_id);
570 // get DefIds from another query
571 let local_def_ids = tcx
572 .associated_item_def_ids(id.def_id)
574 .filter_map(|def_id| def_id.as_local());
576 // And we access the Map here to get HirId from LocalDefId
577 for id in local_def_ids {
578 if of_trait.is_some()
579 || has_allow_dead_code_or_lang_attr(tcx, tcx.hir().local_def_id_to_hir_id(id))
586 let item = tcx.hir().item(id);
587 if let hir::ItemKind::Struct(ref variant_data, _) = item.kind
588 && let Some(ctor_hir_id) = variant_data.ctor_hir_id()
590 struct_constructors.insert(tcx.hir().local_def_id(ctor_hir_id), item.def_id);
593 DefKind::GlobalAsm => {
594 // global_asm! is always live.
595 worklist.push(id.def_id);
601 fn check_trait_item<'tcx>(tcx: TyCtxt<'tcx>, worklist: &mut Vec<LocalDefId>, id: hir::TraitItemId) {
602 use hir::TraitItemKind::{Const, Fn};
603 if matches!(tcx.def_kind(id.def_id), DefKind::AssocConst | DefKind::AssocFn) {
604 let trait_item = tcx.hir().trait_item(id);
605 if matches!(trait_item.kind, Const(_, Some(_)) | Fn(_, hir::TraitFn::Provided(_)))
606 && has_allow_dead_code_or_lang_attr(tcx, trait_item.hir_id())
608 worklist.push(trait_item.def_id);
613 fn check_foreign_item<'tcx>(
615 worklist: &mut Vec<LocalDefId>,
616 id: hir::ForeignItemId,
618 if matches!(tcx.def_kind(id.def_id), DefKind::Static(_) | DefKind::Fn)
619 && has_allow_dead_code_or_lang_attr(tcx, id.hir_id())
621 worklist.push(id.def_id);
625 fn create_and_seed_worklist<'tcx>(
627 ) -> (Vec<LocalDefId>, FxHashMap<LocalDefId, LocalDefId>) {
628 let access_levels = &tcx.privacy_access_levels(());
629 // see `MarkSymbolVisitor::struct_constructors`
630 let mut struct_constructors = Default::default();
631 let mut worklist = access_levels
636 if level >= privacy::AccessLevel::Reachable { Some(id) } else { None }
640 .chain(tcx.entry_fn(()).and_then(|(def_id, _)| def_id.as_local()))
641 .collect::<Vec<_>>();
643 let crate_items = tcx.hir_crate_items(());
644 for id in crate_items.items() {
645 check_item(tcx, &mut worklist, &mut struct_constructors, id);
648 for id in crate_items.trait_items() {
649 check_trait_item(tcx, &mut worklist, id);
652 for id in crate_items.foreign_items() {
653 check_foreign_item(tcx, &mut worklist, id);
656 (worklist, struct_constructors)
659 fn live_symbols_and_ignored_derived_traits<'tcx>(
662 ) -> (FxHashSet<LocalDefId>, FxHashMap<LocalDefId, Vec<(DefId, DefId)>>) {
663 let (worklist, struct_constructors) = create_and_seed_worklist(tcx);
664 let mut symbol_visitor = MarkSymbolVisitor {
667 maybe_typeck_results: None,
668 live_symbols: Default::default(),
669 repr_has_repr_c: false,
670 repr_has_repr_simd: false,
672 ignore_variant_stack: vec![],
674 ignored_derived_traits: FxHashMap::default(),
676 symbol_visitor.mark_live_symbols();
677 (symbol_visitor.live_symbols, symbol_visitor.ignored_derived_traits)
686 struct DeadVisitor<'tcx> {
688 live_symbols: &'tcx FxHashSet<LocalDefId>,
689 ignored_derived_traits: &'tcx FxHashMap<LocalDefId, Vec<(DefId, DefId)>>,
692 enum ShouldWarnAboutField {
693 Yes(bool), // positional?
697 impl<'tcx> DeadVisitor<'tcx> {
698 fn should_warn_about_field(&mut self, field: &ty::FieldDef) -> ShouldWarnAboutField {
699 if self.live_symbols.contains(&field.did.expect_local()) {
700 return ShouldWarnAboutField::No;
702 let field_type = self.tcx.type_of(field.did);
703 if field_type.is_phantom_data() {
704 return ShouldWarnAboutField::No;
706 let is_positional = field.name.as_str().starts_with(|c: char| c.is_ascii_digit());
710 .layout_of(self.tcx.param_env(field.did).and(field_type))
711 .map_or(true, |layout| layout.is_zst())
713 return ShouldWarnAboutField::No;
715 ShouldWarnAboutField::Yes(is_positional)
718 fn warn_multiple_dead_codes(
720 dead_codes: &[LocalDefId],
722 parent_item: Option<LocalDefId>,
725 if let Some(&first_id) = dead_codes.first() {
727 let names: Vec<_> = dead_codes
729 .map(|&def_id| tcx.item_name(def_id.to_def_id()).to_string())
731 let spans: Vec<_> = dead_codes
733 .map(|&def_id| match tcx.def_ident_span(def_id) {
734 Some(s) => s.with_ctxt(tcx.def_span(def_id).ctxt()),
735 None => tcx.def_span(def_id),
739 tcx.struct_span_lint_hir(
741 lint::builtin::UNUSED_TUPLE_STRUCT_FIELDS
743 lint::builtin::DEAD_CODE
745 tcx.hir().local_def_id_to_hir_id(first_id),
746 MultiSpan::from_spans(spans.clone()),
748 let descr = tcx.def_kind(first_id).descr(first_id.to_def_id());
749 let span_len = dead_codes.len();
750 let names = match &names[..] {
751 _ if span_len > 6 => String::new(),
752 [name] => format!("`{name}` "),
753 [names @ .., last] => {
756 names.iter().map(|name| format!("`{name}`")).join(", ")
759 [] => unreachable!(),
761 let mut err = lint.build(&format!(
762 "{these}{descr}{s} {names}{are} never {participle}",
763 these = if span_len > 6 { "multiple " } else { "" },
764 s = pluralize!(span_len),
765 are = pluralize!("is", span_len),
769 err.multipart_suggestion(
771 "consider changing the field{s} to be of unit type to \
772 suppress this warning while preserving the field \
773 numbering, or remove the field{s}",
774 s = pluralize!(span_len)
776 spans.iter().map(|sp| (*sp, "()".to_string())).collect(),
777 // "HasPlaceholders" because applying this fix by itself isn't
778 // enough: All constructor calls have to be adjusted as well
779 Applicability::HasPlaceholders,
783 if let Some(parent_item) = parent_item {
784 let parent_descr = tcx.def_kind(parent_item).descr(parent_item.to_def_id());
786 tcx.def_ident_span(parent_item).unwrap(),
787 format!("{descr}{s} in this {parent_descr}", s = pluralize!(span_len)),
791 let encl_def_id = parent_item.unwrap_or(first_id);
792 if let Some(ign_traits) = self.ignored_derived_traits.get(&encl_def_id) {
793 let traits_str = ign_traits
795 .map(|(trait_id, _)| format!("`{}`", self.tcx.item_name(*trait_id)))
798 let plural_s = pluralize!(ign_traits.len());
799 let article = if ign_traits.len() > 1 { "" } else { "a " };
800 let is_are = if ign_traits.len() > 1 { "these are" } else { "this is" };
802 "`{}` has {}derived impl{} for the trait{} {}, but {} \
803 intentionally ignored during dead code analysis",
804 self.tcx.item_name(encl_def_id.to_def_id()),
819 fn warn_dead_fields_and_variants(
823 dead_codes: Vec<DeadVariant>,
826 let mut dead_codes = dead_codes
828 .filter(|v| !v.name.as_str().starts_with('_'))
830 .collect::<Vec<&DeadVariant>>();
831 if dead_codes.is_empty() {
834 dead_codes.sort_by_key(|v| v.level);
835 for (_, group) in &dead_codes.into_iter().group_by(|v| v.level) {
836 self.warn_multiple_dead_codes(
837 &group.map(|v| v.def_id).collect::<Vec<_>>(),
845 fn warn_dead_code(&mut self, id: LocalDefId, participle: &str) {
846 self.warn_multiple_dead_codes(&[id], participle, None, false);
849 fn check_definition(&mut self, def_id: LocalDefId) {
850 if self.live_symbols.contains(&def_id) {
853 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
854 if has_allow_dead_code_or_lang_attr(self.tcx, hir_id) {
857 let Some(name) = self.tcx.opt_item_name(def_id.to_def_id()) else {
860 if name.as_str().starts_with('_') {
863 match self.tcx.def_kind(def_id) {
872 | DefKind::ForeignTy => self.warn_dead_code(def_id, "used"),
873 DefKind::Struct => self.warn_dead_code(def_id, "constructed"),
874 DefKind::Variant | DefKind::Field => bug!("should be handled specially"),
880 fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalDefId) {
881 let (live_symbols, ignored_derived_traits) = tcx.live_symbols_and_ignored_derived_traits(());
882 let mut visitor = DeadVisitor { tcx, live_symbols, ignored_derived_traits };
884 let module_items = tcx.hir_module_items(module);
886 for item in module_items.items() {
887 if !live_symbols.contains(&item.def_id) {
888 let parent = tcx.local_parent(item.def_id);
889 if parent != module && !live_symbols.contains(&parent) {
890 // We already have diagnosed something.
893 visitor.check_definition(item.def_id);
897 let def_kind = tcx.def_kind(item.def_id);
898 if let DefKind::Struct | DefKind::Union | DefKind::Enum = def_kind {
899 let adt = tcx.adt_def(item.def_id);
900 let mut dead_variants = Vec::new();
902 for variant in adt.variants() {
903 let def_id = variant.def_id.expect_local();
904 if !live_symbols.contains(&def_id) {
905 // Record to group diagnostics.
906 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
907 let level = tcx.lint_level_at_node(lint::builtin::DEAD_CODE, hir_id).0;
908 dead_variants.push(DeadVariant { def_id, name: variant.name, level });
912 let mut is_positional = false;
913 let dead_fields = variant
916 .filter_map(|field| {
917 let def_id = field.did.expect_local();
918 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
919 if let ShouldWarnAboutField::Yes(is_pos) =
920 visitor.should_warn_about_field(&field)
925 is_positional = true;
926 lint::builtin::UNUSED_TUPLE_STRUCT_FIELDS
928 lint::builtin::DEAD_CODE
933 Some(DeadVariant { def_id, name: field.name, level })
939 visitor.warn_dead_fields_and_variants(def_id, "read", dead_fields, is_positional)
942 visitor.warn_dead_fields_and_variants(item.def_id, "constructed", dead_variants, false);
946 for impl_item in module_items.impl_items() {
947 visitor.check_definition(impl_item.def_id);
950 for foreign_item in module_items.foreign_items() {
951 visitor.check_definition(foreign_item.def_id);
954 // We do not warn trait items.
957 pub(crate) fn provide(providers: &mut Providers) {
959 Providers { live_symbols_and_ignored_derived_traits, check_mod_deathness, ..*providers };