rustc_passes/
dead.rs

1// This implements the dead-code warning pass.
2// All reachable symbols are live, code called from live code is live, code with certain lint
3// expectations such as `#[expect(unused)]` and `#[expect(dead_code)]` is live, and everything else
4// is dead.
5
6use 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::builtin::DEAD_CODE;
23use rustc_session::lint::{self, LintExpectationId};
24use rustc_span::{Symbol, sym};
25
26use crate::errors::{
27    ChangeFields, IgnoredDerivedImpls, MultipleDeadCodes, ParentInfo, UselessAssignment,
28};
29
30// Any local node that may call something in its body block should be
31// explored. For example, if it's a live Node::Item that is a
32// function, then we should explore its block to check for codes that
33// may need to be marked as live.
34fn 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/// Determine if a work from the worklist is coming from a `#[allow]`
60/// or a `#[expect]` of `dead_code`
61#[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    // maps from tuple struct constructors to tuple struct items
77    struct_constructors: LocalDefIdMap<LocalDefId>,
78    // maps from ADTs to ignored derived traits (e.g. Debug and Clone)
79    // and the span of their respective impl (i.e., part of the derive
80    // macro)
81    ignored_derived_traits: LocalDefIdMap<Vec<(DefId, DefId)>>,
82}
83
84impl<'tcx> MarkSymbolVisitor<'tcx> {
85    /// Gets the type-checking results for the current body.
86    /// As this will ICE if called outside bodies, only call when working with
87    /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
88    #[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)] // FIXME(81658): should be used + lint reinstated after #83171 relands.
163    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            // Ignore write to field
173            self.handle_assign(base);
174        } else {
175            self.visit_expr(expr);
176        }
177    }
178
179    #[allow(dead_code)] // FIXME(81658): should be used + lint reinstated after #83171 relands.
180    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                // we don't need to mark tuple fields as live,
290                // but we may need to mark subfields
291                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            // Avoid accessing the HIR for the synthesized associated type generated for RPITITs.
310            if self.tcx.is_impl_trait_in_trait(id.to_def_id()) {
311                self.live_symbols.insert(id);
312                continue;
313            }
314
315            // in the case of tuple struct constructors we want to check the item, not the generated
316            // tuple struct constructor function
317            let id = self.struct_constructors.get(&id).copied().unwrap_or(id);
318
319            // When using `#[allow]` or `#[expect]` of `dead_code`, we do a QOL improvement
320            // by declaring fn calls, statics, ... within said items as live, as well as
321            // the item itself, although technically this is not the case.
322            //
323            // This means that the lint for said items will never be fired.
324            //
325            // This doesn't make any difference for the item declared with `#[allow]`, as
326            // the lint firing will be a nop, as it will be silenced by the `#[allow]` of
327            // the item.
328            //
329            // However, for `#[expect]`, the presence or absence of the lint is relevant,
330            // so we don't add it to the list of live symbols when it comes from a
331            // `#[expect]`. This means that we will correctly report an item as live or not
332            // for the `#[expect]` case.
333            //
334            // Note that an item can and will be duplicated on the worklist with different
335            // `ComesFromAllowExpect`, particularly if it was added from the
336            // `effective_visibilities` query or from the `#[allow]`/`#[expect]` checks,
337            // this "duplication" is essential as otherwise a function with `#[expect]`
338            // called from a `pub fn` may be falsely reported as not live, falsely
339            // triggering the `unfulfilled_lint_expectations` lint.
340            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    /// Automatically generated items marked with `rustc_trivial_field_reads`
348    /// will be ignored for the purposes of dead code analysis (see PR #85200
349    /// for discussion).
350    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            // don't ignore impls for Enums and pub Structs whose methods don't have self receiver,
357            // cause external crate may call such methods to construct values of these types
358            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                    // for example, #[derive(Default)] pub struct T(i32);
369                    // external crate can call T::default() to construct T,
370                    // so that don't ignore impl Default for pub Enum and Structs
371                    DefKind::Struct | DefKind::Union if self.tcx.visibility(did).is_public() => {
372                        return false;
373                    }
374                    // don't ignore impl Default for Enums,
375                    // cause we don't know which variant is constructed
376                    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.local_trait_impls(item.owner_id.def_id) {
425                        if let ItemKind::Impl(impl_ref) = self.tcx.hir_expect_item(impl_def_id).kind
426                        {
427                            // skip items
428                            // mark dependent traits live
429                            intravisit::walk_generics(self, impl_ref.generics);
430                            // mark dependent parameters live
431                            intravisit::walk_path(self, impl_ref.of_trait.unwrap().path);
432                        }
433                    }
434
435                    intravisit::walk_item(self, item)
436                }
437                _ => intravisit::walk_item(self, item),
438            },
439            Node::TraitItem(trait_item) => {
440                // mark corresponding ImplTerm live
441                let trait_item_id = trait_item.owner_id.to_def_id();
442                if let Some(trait_id) = self.tcx.trait_of_item(trait_item_id) {
443                    // mark the trait live
444                    self.check_def_id(trait_id);
445
446                    for impl_id in self.tcx.all_impls(trait_id) {
447                        if let Some(local_impl_id) = impl_id.as_local()
448                            && let ItemKind::Impl(impl_ref) =
449                                self.tcx.hir_expect_item(local_impl_id).kind
450                        {
451                            if !matches!(trait_item.kind, hir::TraitItemKind::Type(..))
452                                && !ty_ref_to_pub_struct(self.tcx, impl_ref.self_ty)
453                            {
454                                // skip methods of private ty,
455                                // they would be solved in `solve_rest_impl_items`
456                                continue;
457                            }
458
459                            // mark self_ty live
460                            intravisit::walk_unambig_ty(self, impl_ref.self_ty);
461                            if let Some(&impl_item_id) =
462                                self.tcx.impl_item_implementor_ids(impl_id).get(&trait_item_id)
463                            {
464                                self.check_def_id(impl_item_id);
465                            }
466                        }
467                    }
468                }
469                intravisit::walk_trait_item(self, trait_item);
470            }
471            Node::ImplItem(impl_item) => {
472                let item = self.tcx.local_parent(impl_item.owner_id.def_id);
473                if self.tcx.impl_trait_ref(item).is_none() {
474                    //// If it's a type whose items are live, then it's live, too.
475                    //// This is done to handle the case where, for example, the static
476                    //// method of a private type is used, but the type itself is never
477                    //// called directly.
478                    let self_ty = self.tcx.type_of(item).instantiate_identity();
479                    match *self_ty.kind() {
480                        ty::Adt(def, _) => self.check_def_id(def.did()),
481                        ty::Foreign(did) => self.check_def_id(did),
482                        ty::Dynamic(data, ..) => {
483                            if let Some(def_id) = data.principal_def_id() {
484                                self.check_def_id(def_id)
485                            }
486                        }
487                        _ => {}
488                    }
489                }
490                intravisit::walk_impl_item(self, impl_item);
491            }
492            Node::ForeignItem(foreign_item) => {
493                intravisit::walk_foreign_item(self, foreign_item);
494            }
495            Node::OpaqueTy(opaq) => intravisit::walk_opaque_ty(self, opaq),
496            _ => {}
497        }
498        self.repr_has_repr_simd = had_repr_simd;
499        self.repr_unconditionally_treats_fields_as_live = unconditionally_treated_fields_as_live;
500    }
501
502    fn mark_as_used_if_union(&mut self, adt: ty::AdtDef<'tcx>, fields: &[hir::ExprField<'_>]) {
503        if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did().is_local() {
504            for field in fields {
505                let index = self.typeck_results().field_index(field.hir_id);
506                self.insert_def_id(adt.non_enum_variant().fields[index].did);
507            }
508        }
509    }
510
511    fn solve_rest_impl_items(&mut self, mut unsolved_impl_items: Vec<(hir::ItemId, LocalDefId)>) {
512        let mut ready;
513        (ready, unsolved_impl_items) =
514            unsolved_impl_items.into_iter().partition(|&(impl_id, impl_item_id)| {
515                self.impl_item_with_used_self(impl_id, impl_item_id)
516            });
517
518        while !ready.is_empty() {
519            self.worklist =
520                ready.into_iter().map(|(_, id)| (id, ComesFromAllowExpect::No)).collect();
521            self.mark_live_symbols();
522
523            (ready, unsolved_impl_items) =
524                unsolved_impl_items.into_iter().partition(|&(impl_id, impl_item_id)| {
525                    self.impl_item_with_used_self(impl_id, impl_item_id)
526                });
527        }
528    }
529
530    fn impl_item_with_used_self(&mut self, impl_id: hir::ItemId, impl_item_id: LocalDefId) -> bool {
531        if let TyKind::Path(hir::QPath::Resolved(_, path)) =
532            self.tcx.hir_item(impl_id).expect_impl().self_ty.kind
533            && let Res::Def(def_kind, def_id) = path.res
534            && let Some(local_def_id) = def_id.as_local()
535            && matches!(def_kind, DefKind::Struct | DefKind::Enum | DefKind::Union)
536        {
537            if self.tcx.visibility(impl_item_id).is_public() {
538                // for the public method, we don't know the trait item is used or not,
539                // so we mark the method live if the self is used
540                return self.live_symbols.contains(&local_def_id);
541            }
542
543            if let Some(trait_item_id) = self.tcx.associated_item(impl_item_id).trait_item_def_id
544                && let Some(local_id) = trait_item_id.as_local()
545            {
546                // for the private method, we can know the trait item is used or not,
547                // so we mark the method live if the self is used and the trait item is used
548                return self.live_symbols.contains(&local_id)
549                    && self.live_symbols.contains(&local_def_id);
550            }
551        }
552        false
553    }
554}
555
556impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
557    fn visit_nested_body(&mut self, body: hir::BodyId) {
558        let old_maybe_typeck_results =
559            self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
560        let body = self.tcx.hir_body(body);
561        self.visit_body(body);
562        self.maybe_typeck_results = old_maybe_typeck_results;
563    }
564
565    fn visit_variant_data(&mut self, def: &'tcx hir::VariantData<'tcx>) {
566        let tcx = self.tcx;
567        let unconditionally_treat_fields_as_live = self.repr_unconditionally_treats_fields_as_live;
568        let has_repr_simd = self.repr_has_repr_simd;
569        let effective_visibilities = &tcx.effective_visibilities(());
570        let live_fields = def.fields().iter().filter_map(|f| {
571            let def_id = f.def_id;
572            if unconditionally_treat_fields_as_live || (f.is_positional() && has_repr_simd) {
573                return Some(def_id);
574            }
575            if !effective_visibilities.is_reachable(f.hir_id.owner.def_id) {
576                return None;
577            }
578            if effective_visibilities.is_reachable(def_id) { Some(def_id) } else { None }
579        });
580        self.live_symbols.extend(live_fields);
581
582        intravisit::walk_struct_def(self, def);
583    }
584
585    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
586        match expr.kind {
587            hir::ExprKind::Path(ref qpath @ hir::QPath::TypeRelative(..)) => {
588                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
589                self.handle_res(res);
590            }
591            hir::ExprKind::MethodCall(..) => {
592                self.lookup_and_handle_method(expr.hir_id);
593            }
594            hir::ExprKind::Field(ref lhs, ..) => {
595                if self.typeck_results().opt_field_index(expr.hir_id).is_some() {
596                    self.handle_field_access(lhs, expr.hir_id);
597                } else {
598                    self.tcx.dcx().span_delayed_bug(expr.span, "couldn't resolve index for field");
599                }
600            }
601            hir::ExprKind::Struct(qpath, fields, _) => {
602                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
603                self.handle_res(res);
604                if let ty::Adt(adt, _) = self.typeck_results().expr_ty(expr).kind() {
605                    self.mark_as_used_if_union(*adt, fields);
606                }
607            }
608            hir::ExprKind::Closure(cls) => {
609                self.insert_def_id(cls.def_id.to_def_id());
610            }
611            hir::ExprKind::OffsetOf(..) => {
612                self.handle_offset_of(expr);
613            }
614            _ => (),
615        }
616
617        intravisit::walk_expr(self, expr);
618    }
619
620    fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
621        // Inside the body, ignore constructions of variants
622        // necessary for the pattern to match. Those construction sites
623        // can't be reached unless the variant is constructed elsewhere.
624        let len = self.ignore_variant_stack.len();
625        self.ignore_variant_stack.extend(arm.pat.necessary_variants());
626        intravisit::walk_arm(self, arm);
627        self.ignore_variant_stack.truncate(len);
628    }
629
630    fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
631        self.in_pat = true;
632        match pat.kind {
633            PatKind::Struct(ref path, fields, _) => {
634                let res = self.typeck_results().qpath_res(path, pat.hir_id);
635                self.handle_field_pattern_match(pat, res, fields);
636            }
637            PatKind::TupleStruct(ref qpath, fields, dotdot) => {
638                let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
639                self.handle_tuple_field_pattern_match(pat, res, fields, dotdot);
640            }
641            _ => (),
642        }
643
644        intravisit::walk_pat(self, pat);
645        self.in_pat = false;
646    }
647
648    fn visit_pat_expr(&mut self, expr: &'tcx rustc_hir::PatExpr<'tcx>) {
649        match &expr.kind {
650            rustc_hir::PatExprKind::Path(qpath) => {
651                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
652                self.handle_res(res);
653            }
654            _ => {}
655        }
656        intravisit::walk_pat_expr(self, expr);
657    }
658
659    fn visit_path(&mut self, path: &hir::Path<'tcx>, _: hir::HirId) {
660        self.handle_res(path.res);
661        intravisit::walk_path(self, path);
662    }
663
664    fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
665        // When inline const blocks are used in pattern position, paths
666        // referenced by it should be considered as used.
667        let in_pat = mem::replace(&mut self.in_pat, false);
668
669        self.live_symbols.insert(c.def_id);
670        intravisit::walk_anon_const(self, c);
671
672        self.in_pat = in_pat;
673    }
674
675    fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) {
676        // When inline const blocks are used in pattern position, paths
677        // referenced by it should be considered as used.
678        let in_pat = mem::replace(&mut self.in_pat, false);
679
680        self.live_symbols.insert(c.def_id);
681        intravisit::walk_inline_const(self, c);
682
683        self.in_pat = in_pat;
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            // Stable attribute for #[lang = "panic_impl"]
694            || 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            // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
708            // forcefully, e.g., for placing it in a specific section.
709            cg_attrs.contains_extern_indicator()
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
724// These check_* functions seeds items that
725//   1) We want to explicitly consider as live:
726//     * Item annotated with #[allow(dead_code)]
727//         - This is done so that if we want to suppress warnings for a
728//           group of dead functions, we only have to annotate the "root".
729//           For example, if both `f` and `g` are dead and `f` calls `g`,
730//           then annotating `f` with `#[allow(dead_code)]` will suppress
731//           warning for both `f` and `g`.
732//     * Item annotated with #[lang=".."]
733//         - This is because lang items are always callable from elsewhere.
734//   or
735//   2) We are not sure to be live or not
736//     * Implementations of traits and trait methods
737fn check_item<'tcx>(
738    tcx: TyCtxt<'tcx>,
739    worklist: &mut Vec<(LocalDefId, ComesFromAllowExpect)>,
740    struct_constructors: &mut LocalDefIdMap<LocalDefId>,
741    unsolved_impl_items: &mut Vec<(hir::ItemId, LocalDefId)>,
742    id: hir::ItemId,
743) {
744    let allow_dead_code = has_allow_dead_code_or_lang_attr(tcx, id.owner_id.def_id);
745    if let Some(comes_from_allow) = allow_dead_code {
746        worklist.push((id.owner_id.def_id, comes_from_allow));
747    }
748
749    match tcx.def_kind(id.owner_id) {
750        DefKind::Enum => {
751            let item = tcx.hir_item(id);
752            if let hir::ItemKind::Enum(_, ref enum_def, _) = item.kind {
753                if let Some(comes_from_allow) = allow_dead_code {
754                    worklist.extend(
755                        enum_def.variants.iter().map(|variant| (variant.def_id, comes_from_allow)),
756                    );
757                }
758
759                for variant in enum_def.variants {
760                    if let Some(ctor_def_id) = variant.data.ctor_def_id() {
761                        struct_constructors.insert(ctor_def_id, variant.def_id);
762                    }
763                }
764            }
765        }
766        DefKind::Impl { of_trait } => {
767            // get DefIds from another query
768            let local_def_ids = tcx
769                .associated_item_def_ids(id.owner_id)
770                .iter()
771                .filter_map(|def_id| def_id.as_local());
772
773            let ty_is_pub = ty_ref_to_pub_struct(tcx, tcx.hir_item(id).expect_impl().self_ty);
774
775            // And we access the Map here to get HirId from LocalDefId
776            for local_def_id in local_def_ids {
777                // check the function may construct Self
778                let mut may_construct_self = false;
779                if let Some(fn_sig) =
780                    tcx.hir_fn_sig_by_hir_id(tcx.local_def_id_to_hir_id(local_def_id))
781                {
782                    may_construct_self =
783                        matches!(fn_sig.decl.implicit_self, hir::ImplicitSelfKind::None);
784                }
785
786                // for trait impl blocks,
787                // mark the method live if the self_ty is public,
788                // or the method is public and may construct self
789                if of_trait
790                    && (!matches!(tcx.def_kind(local_def_id), DefKind::AssocFn)
791                        || tcx.visibility(local_def_id).is_public()
792                            && (ty_is_pub || may_construct_self))
793                {
794                    worklist.push((local_def_id, ComesFromAllowExpect::No));
795                } else if let Some(comes_from_allow) =
796                    has_allow_dead_code_or_lang_attr(tcx, local_def_id)
797                {
798                    worklist.push((local_def_id, comes_from_allow));
799                } else if of_trait {
800                    // private method || public method not constructs self
801                    unsolved_impl_items.push((id, local_def_id));
802                }
803            }
804        }
805        DefKind::Struct => {
806            let item = tcx.hir_item(id);
807            if let hir::ItemKind::Struct(_, ref variant_data, _) = item.kind
808                && let Some(ctor_def_id) = variant_data.ctor_def_id()
809            {
810                struct_constructors.insert(ctor_def_id, item.owner_id.def_id);
811            }
812        }
813        DefKind::GlobalAsm => {
814            // global_asm! is always live.
815            worklist.push((id.owner_id.def_id, ComesFromAllowExpect::No));
816        }
817        _ => {}
818    }
819}
820
821fn check_trait_item(
822    tcx: TyCtxt<'_>,
823    worklist: &mut Vec<(LocalDefId, ComesFromAllowExpect)>,
824    id: hir::TraitItemId,
825) {
826    use hir::TraitItemKind::{Const, Fn};
827    if matches!(tcx.def_kind(id.owner_id), DefKind::AssocConst | DefKind::AssocFn) {
828        let trait_item = tcx.hir_trait_item(id);
829        if matches!(trait_item.kind, Const(_, Some(_)) | Fn(..))
830            && let Some(comes_from_allow) =
831                has_allow_dead_code_or_lang_attr(tcx, trait_item.owner_id.def_id)
832        {
833            worklist.push((trait_item.owner_id.def_id, comes_from_allow));
834        }
835    }
836}
837
838fn check_foreign_item(
839    tcx: TyCtxt<'_>,
840    worklist: &mut Vec<(LocalDefId, ComesFromAllowExpect)>,
841    id: hir::ForeignItemId,
842) {
843    if matches!(tcx.def_kind(id.owner_id), DefKind::Static { .. } | DefKind::Fn)
844        && let Some(comes_from_allow) = has_allow_dead_code_or_lang_attr(tcx, id.owner_id.def_id)
845    {
846        worklist.push((id.owner_id.def_id, comes_from_allow));
847    }
848}
849
850fn create_and_seed_worklist(
851    tcx: TyCtxt<'_>,
852) -> (
853    Vec<(LocalDefId, ComesFromAllowExpect)>,
854    LocalDefIdMap<LocalDefId>,
855    Vec<(hir::ItemId, LocalDefId)>,
856) {
857    let effective_visibilities = &tcx.effective_visibilities(());
858    // see `MarkSymbolVisitor::struct_constructors`
859    let mut unsolved_impl_item = Vec::new();
860    let mut struct_constructors = Default::default();
861    let mut worklist = effective_visibilities
862        .iter()
863        .filter_map(|(&id, effective_vis)| {
864            effective_vis
865                .is_public_at_level(Level::Reachable)
866                .then_some(id)
867                .map(|id| (id, ComesFromAllowExpect::No))
868        })
869        // Seed entry point
870        .chain(
871            tcx.entry_fn(())
872                .and_then(|(def_id, _)| def_id.as_local().map(|id| (id, ComesFromAllowExpect::No))),
873        )
874        .collect::<Vec<_>>();
875
876    let crate_items = tcx.hir_crate_items(());
877    for id in crate_items.free_items() {
878        check_item(tcx, &mut worklist, &mut struct_constructors, &mut unsolved_impl_item, id);
879    }
880
881    for id in crate_items.trait_items() {
882        check_trait_item(tcx, &mut worklist, id);
883    }
884
885    for id in crate_items.foreign_items() {
886        check_foreign_item(tcx, &mut worklist, id);
887    }
888
889    (worklist, struct_constructors, unsolved_impl_item)
890}
891
892fn live_symbols_and_ignored_derived_traits(
893    tcx: TyCtxt<'_>,
894    (): (),
895) -> (LocalDefIdSet, LocalDefIdMap<Vec<(DefId, DefId)>>) {
896    let (worklist, struct_constructors, unsolved_impl_items) = create_and_seed_worklist(tcx);
897    let mut symbol_visitor = MarkSymbolVisitor {
898        worklist,
899        tcx,
900        maybe_typeck_results: None,
901        live_symbols: Default::default(),
902        repr_unconditionally_treats_fields_as_live: false,
903        repr_has_repr_simd: false,
904        in_pat: false,
905        ignore_variant_stack: vec![],
906        struct_constructors,
907        ignored_derived_traits: Default::default(),
908    };
909    symbol_visitor.mark_live_symbols();
910    symbol_visitor.solve_rest_impl_items(unsolved_impl_items);
911
912    (symbol_visitor.live_symbols, symbol_visitor.ignored_derived_traits)
913}
914
915struct DeadItem {
916    def_id: LocalDefId,
917    name: Symbol,
918    level: (lint::Level, Option<LintExpectationId>),
919}
920
921struct DeadVisitor<'tcx> {
922    tcx: TyCtxt<'tcx>,
923    live_symbols: &'tcx LocalDefIdSet,
924    ignored_derived_traits: &'tcx LocalDefIdMap<Vec<(DefId, DefId)>>,
925}
926
927enum ShouldWarnAboutField {
928    Yes,
929    No,
930}
931
932#[derive(Debug, Copy, Clone, PartialEq, Eq)]
933enum ReportOn {
934    TupleField,
935    NamedField,
936}
937
938impl<'tcx> DeadVisitor<'tcx> {
939    fn should_warn_about_field(&mut self, field: &ty::FieldDef) -> ShouldWarnAboutField {
940        if self.live_symbols.contains(&field.did.expect_local()) {
941            return ShouldWarnAboutField::No;
942        }
943        let field_type = self.tcx.type_of(field.did).instantiate_identity();
944        if field_type.is_phantom_data() {
945            return ShouldWarnAboutField::No;
946        }
947        let is_positional = field.name.as_str().starts_with(|c: char| c.is_ascii_digit());
948        if is_positional
949            && self
950                .tcx
951                .layout_of(
952                    ty::TypingEnv::non_body_analysis(self.tcx, field.did)
953                        .as_query_input(field_type),
954                )
955                .map_or(true, |layout| layout.is_zst())
956        {
957            return ShouldWarnAboutField::No;
958        }
959        ShouldWarnAboutField::Yes
960    }
961
962    fn def_lint_level(&self, id: LocalDefId) -> (lint::Level, Option<LintExpectationId>) {
963        let hir_id = self.tcx.local_def_id_to_hir_id(id);
964        let level = self.tcx.lint_level_at_node(DEAD_CODE, hir_id);
965        (level.level, level.lint_id)
966    }
967
968    // # Panics
969    // All `dead_codes` must have the same lint level, otherwise we will intentionally ICE.
970    // This is because we emit a multi-spanned lint using the lint level of the `dead_codes`'s
971    // first local def id.
972    // Prefer calling `Self.warn_dead_code` or `Self.warn_dead_code_grouped_by_lint_level`
973    // since those methods group by lint level before calling this method.
974    fn lint_at_single_level(
975        &self,
976        dead_codes: &[&DeadItem],
977        participle: &str,
978        parent_item: Option<LocalDefId>,
979        report_on: ReportOn,
980    ) {
981        fn get_parent_if_enum_variant<'tcx>(
982            tcx: TyCtxt<'tcx>,
983            may_variant: LocalDefId,
984        ) -> LocalDefId {
985            if let Node::Variant(_) = tcx.hir_node_by_def_id(may_variant)
986                && let Some(enum_did) = tcx.opt_parent(may_variant.to_def_id())
987                && let Some(enum_local_id) = enum_did.as_local()
988                && let Node::Item(item) = tcx.hir_node_by_def_id(enum_local_id)
989                && let ItemKind::Enum(..) = item.kind
990            {
991                enum_local_id
992            } else {
993                may_variant
994            }
995        }
996
997        let Some(&first_item) = dead_codes.first() else {
998            return;
999        };
1000        let tcx = self.tcx;
1001
1002        let first_lint_level = first_item.level;
1003        assert!(dead_codes.iter().skip(1).all(|item| item.level == first_lint_level));
1004
1005        let names: Vec<_> = dead_codes.iter().map(|item| item.name).collect();
1006        let spans: Vec<_> = dead_codes
1007            .iter()
1008            .map(|item| match tcx.def_ident_span(item.def_id) {
1009                Some(s) => s.with_ctxt(tcx.def_span(item.def_id).ctxt()),
1010                None => tcx.def_span(item.def_id),
1011            })
1012            .collect();
1013
1014        let descr = tcx.def_descr(first_item.def_id.to_def_id());
1015        // `impl` blocks are "batched" and (unlike other batching) might
1016        // contain different kinds of associated items.
1017        let descr = if dead_codes.iter().any(|item| tcx.def_descr(item.def_id.to_def_id()) != descr)
1018        {
1019            "associated item"
1020        } else {
1021            descr
1022        };
1023        let num = dead_codes.len();
1024        let multiple = num > 6;
1025        let name_list = names.into();
1026
1027        let parent_info = if let Some(parent_item) = parent_item {
1028            let parent_descr = tcx.def_descr(parent_item.to_def_id());
1029            let span = if let DefKind::Impl { .. } = tcx.def_kind(parent_item) {
1030                tcx.def_span(parent_item)
1031            } else {
1032                tcx.def_ident_span(parent_item).unwrap()
1033            };
1034            Some(ParentInfo { num, descr, parent_descr, span })
1035        } else {
1036            None
1037        };
1038
1039        let encl_def_id = parent_item.unwrap_or(first_item.def_id);
1040        // If parent of encl_def_id is an enum, use the parent ID instead.
1041        let encl_def_id = get_parent_if_enum_variant(tcx, encl_def_id);
1042
1043        let ignored_derived_impls =
1044            if let Some(ign_traits) = self.ignored_derived_traits.get(&encl_def_id) {
1045                let trait_list = ign_traits
1046                    .iter()
1047                    .map(|(trait_id, _)| self.tcx.item_name(*trait_id))
1048                    .collect::<Vec<_>>();
1049                let trait_list_len = trait_list.len();
1050                Some(IgnoredDerivedImpls {
1051                    name: self.tcx.item_name(encl_def_id.to_def_id()),
1052                    trait_list: trait_list.into(),
1053                    trait_list_len,
1054                })
1055            } else {
1056                None
1057            };
1058
1059        let diag = match report_on {
1060            ReportOn::TupleField => {
1061                let tuple_fields = if let Some(parent_id) = parent_item
1062                    && let node = tcx.hir_node_by_def_id(parent_id)
1063                    && let hir::Node::Item(hir::Item {
1064                        kind: hir::ItemKind::Struct(_, hir::VariantData::Tuple(fields, _, _), _),
1065                        ..
1066                    }) = node
1067                {
1068                    *fields
1069                } else {
1070                    &[]
1071                };
1072
1073                let trailing_tuple_fields = if tuple_fields.len() >= dead_codes.len() {
1074                    LocalDefIdSet::from_iter(
1075                        tuple_fields
1076                            .iter()
1077                            .skip(tuple_fields.len() - dead_codes.len())
1078                            .map(|f| f.def_id),
1079                    )
1080                } else {
1081                    LocalDefIdSet::default()
1082                };
1083
1084                let fields_suggestion =
1085                    // Suggest removal if all tuple fields are at the end.
1086                    // Otherwise suggest removal or changing to unit type
1087                    if dead_codes.iter().all(|dc| trailing_tuple_fields.contains(&dc.def_id)) {
1088                        ChangeFields::Remove { num }
1089                    } else {
1090                        ChangeFields::ChangeToUnitTypeOrRemove { num, spans: spans.clone() }
1091                    };
1092
1093                MultipleDeadCodes::UnusedTupleStructFields {
1094                    multiple,
1095                    num,
1096                    descr,
1097                    participle,
1098                    name_list,
1099                    change_fields_suggestion: fields_suggestion,
1100                    parent_info,
1101                    ignored_derived_impls,
1102                }
1103            }
1104            ReportOn::NamedField => MultipleDeadCodes::DeadCodes {
1105                multiple,
1106                num,
1107                descr,
1108                participle,
1109                name_list,
1110                parent_info,
1111                ignored_derived_impls,
1112            },
1113        };
1114
1115        let hir_id = tcx.local_def_id_to_hir_id(first_item.def_id);
1116        self.tcx.emit_node_span_lint(DEAD_CODE, hir_id, MultiSpan::from_spans(spans), diag);
1117    }
1118
1119    fn warn_multiple(
1120        &self,
1121        def_id: LocalDefId,
1122        participle: &str,
1123        dead_codes: Vec<DeadItem>,
1124        report_on: ReportOn,
1125    ) {
1126        let mut dead_codes = dead_codes
1127            .iter()
1128            .filter(|v| !v.name.as_str().starts_with('_'))
1129            .collect::<Vec<&DeadItem>>();
1130        if dead_codes.is_empty() {
1131            return;
1132        }
1133        // FIXME: `dead_codes` should probably be morally equivalent to `IndexMap<(Level, LintExpectationId), (DefId, Symbol)>`
1134        dead_codes.sort_by_key(|v| v.level.0);
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        // if we cannot get a name for the item, then we just assume that it is
1172        // live. I mean, we can't really emit a lint.
1173        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 we have diagnosed the trait, do not diagnose unused methods
1192        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                // We have diagnosed unused methods in traits
1197                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                // We already have diagnosed something.
1221                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                    // Record to group diagnostics.
1235                    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}