Skip to main content

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;
7use std::ops::ControlFlow;
8
9use hir::def_id::{LocalDefIdMap, LocalDefIdSet};
10use rustc_abi::FieldIdx;
11use rustc_data_structures::fx::FxIndexSet;
12use rustc_errors::{ErrorGuaranteed, 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, QPath, find_attr};
17use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
18use rustc_middle::middle::privacy::Level;
19use rustc_middle::query::Providers;
20use rustc_middle::ty::{self, AssocTag, TyCtxt};
21use rustc_middle::{bug, span_bug};
22use rustc_session::lint::builtin::DEAD_CODE;
23use rustc_session::lint::{self, LintExpectationId};
24use rustc_span::{Symbol, kw};
25
26use crate::errors::{
27    ChangeFields, IgnoredDerivedImpls, MultipleDeadCodes, ParentInfo, UselessAssignment,
28};
29
30/// Any local definition that may call something in its body block should be explored. For example,
31/// if it's a live function, then we should explore its block to check for codes that may need to
32/// be marked as live.
33fn should_explore(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
34    match tcx.def_kind(def_id) {
35        DefKind::Mod
36        | DefKind::Struct
37        | DefKind::Union
38        | DefKind::Enum
39        | DefKind::Variant
40        | DefKind::Trait
41        | DefKind::TyAlias
42        | DefKind::ForeignTy
43        | DefKind::TraitAlias
44        | DefKind::AssocTy
45        | DefKind::Fn
46        | DefKind::Const { .. }
47        | DefKind::Static { .. }
48        | DefKind::AssocFn
49        | DefKind::AssocConst { .. }
50        | DefKind::Macro(_)
51        | DefKind::GlobalAsm
52        | DefKind::Impl { .. }
53        | DefKind::OpaqueTy
54        | DefKind::AnonConst
55        | DefKind::InlineConst
56        | DefKind::ExternCrate
57        | DefKind::Use
58        | DefKind::Ctor(..)
59        | DefKind::ForeignMod => true,
60
61        DefKind::TyParam
62        | DefKind::ConstParam
63        | DefKind::Field
64        | DefKind::LifetimeParam
65        | DefKind::Closure
66        | DefKind::SyntheticCoroutineBody => false,
67    }
68}
69
70/// Determine if a work from the worklist is coming from a `#[allow]`
71/// or a `#[expect]` of `dead_code`
72#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ComesFromAllowExpect {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ComesFromAllowExpect::Yes => "Yes",
                ComesFromAllowExpect::No => "No",
            })
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for ComesFromAllowExpect { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ComesFromAllowExpect {
    #[inline]
    fn clone(&self) -> ComesFromAllowExpect { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::Eq for ComesFromAllowExpect {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for ComesFromAllowExpect {
    #[inline]
    fn eq(&self, other: &ComesFromAllowExpect) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::hash::Hash for ComesFromAllowExpect {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state)
    }
}Hash)]
73enum ComesFromAllowExpect {
74    Yes,
75    No,
76}
77
78struct MarkSymbolVisitor<'tcx> {
79    worklist: Vec<(LocalDefId, ComesFromAllowExpect)>,
80    tcx: TyCtxt<'tcx>,
81    maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
82    scanned: LocalDefIdSet,
83    live_symbols: LocalDefIdSet,
84    repr_unconditionally_treats_fields_as_live: bool,
85    repr_has_repr_simd: bool,
86    in_pat: bool,
87    ignore_variant_stack: Vec<DefId>,
88    // maps from ADTs to ignored derived traits (e.g. Debug and Clone)
89    // and the span of their respective impl (i.e., part of the derive
90    // macro)
91    ignored_derived_traits: LocalDefIdMap<FxIndexSet<DefId>>,
92}
93
94impl<'tcx> MarkSymbolVisitor<'tcx> {
95    /// Gets the type-checking results for the current body.
96    /// As this will ICE if called outside bodies, only call when working with
97    /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
98    #[track_caller]
99    fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
100        self.maybe_typeck_results
101            .expect("`MarkSymbolVisitor::typeck_results` called outside of body")
102    }
103
104    fn check_def_id(&mut self, def_id: DefId) {
105        if let Some(def_id) = def_id.as_local() {
106            if should_explore(self.tcx, def_id) {
107                self.worklist.push((def_id, ComesFromAllowExpect::No));
108            }
109            self.live_symbols.insert(def_id);
110        }
111    }
112
113    fn insert_def_id(&mut self, def_id: DefId) {
114        if let Some(def_id) = def_id.as_local() {
115            if true {
    if !!should_explore(self.tcx, def_id) {
        ::core::panicking::panic("assertion failed: !should_explore(self.tcx, def_id)")
    };
};debug_assert!(!should_explore(self.tcx, def_id));
116            self.live_symbols.insert(def_id);
117        }
118    }
119
120    fn handle_res(&mut self, res: Res) {
121        match res {
122            Res::Def(
123                DefKind::Const { .. }
124                | DefKind::AssocConst { .. }
125                | DefKind::AssocTy
126                | DefKind::TyAlias,
127                def_id,
128            ) => {
129                self.check_def_id(def_id);
130            }
131            Res::PrimTy(..) | Res::SelfCtor(..) | Res::Local(..) => {}
132            Res::Def(DefKind::Ctor(CtorOf::Variant, ..), ctor_def_id) => {
133                // Using a variant in patterns should not make the variant live,
134                // since we can just remove the match arm that matches the pattern
135                if self.in_pat {
136                    return;
137                }
138                let variant_id = self.tcx.parent(ctor_def_id);
139                let enum_id = self.tcx.parent(variant_id);
140                self.check_def_id(enum_id);
141                if !self.ignore_variant_stack.contains(&ctor_def_id) {
142                    self.check_def_id(variant_id);
143                }
144            }
145            Res::Def(DefKind::Variant, variant_id) => {
146                // Using a variant in patterns should not make the variant live,
147                // since we can just remove the match arm that matches the pattern
148                if self.in_pat {
149                    return;
150                }
151                let enum_id = self.tcx.parent(variant_id);
152                self.check_def_id(enum_id);
153                if !self.ignore_variant_stack.contains(&variant_id) {
154                    self.check_def_id(variant_id);
155                }
156            }
157            Res::Def(_, def_id) => self.check_def_id(def_id),
158            Res::SelfTyParam { trait_: t } => self.check_def_id(t),
159            Res::SelfTyAlias { alias_to: i, .. } => self.check_def_id(i),
160            Res::ToolMod | Res::NonMacroAttr(..) | Res::OpenMod(..) | Res::Err => {}
161        }
162    }
163
164    fn lookup_and_handle_method(&mut self, id: hir::HirId) {
165        if let Some(def_id) = self.typeck_results().type_dependent_def_id(id) {
166            self.check_def_id(def_id);
167        } else {
168            if !self.typeck_results().tainted_by_errors.is_some() {
    {
        ::core::panicking::panic_fmt(format_args!("no type-dependent def for method"));
    }
};assert!(
169                self.typeck_results().tainted_by_errors.is_some(),
170                "no type-dependent def for method"
171            );
172        }
173    }
174
175    fn handle_field_access(&mut self, lhs: &hir::Expr<'_>, hir_id: hir::HirId) {
176        match self.typeck_results().expr_ty_adjusted(lhs).kind() {
177            ty::Adt(def, _) => {
178                let index = self.typeck_results().field_index(hir_id);
179                self.insert_def_id(def.non_enum_variant().fields[index].did);
180            }
181            ty::Tuple(..) => {}
182            ty::Error(_) => {}
183            kind => ::rustc_middle::util::bug::span_bug_fmt(lhs.span,
    format_args!("named field access on non-ADT: {0:?}", kind))span_bug!(lhs.span, "named field access on non-ADT: {kind:?}"),
184        }
185    }
186
187    fn handle_assign(&mut self, expr: &'tcx hir::Expr<'tcx>) {
188        if self
189            .typeck_results()
190            .expr_adjustments(expr)
191            .iter()
192            .any(|adj| #[allow(non_exhaustive_omitted_patterns)] match adj.kind {
    ty::adjustment::Adjust::Deref(_) => true,
    _ => false,
}matches!(adj.kind, ty::adjustment::Adjust::Deref(_)))
193        {
194            let _ = self.visit_expr(expr);
195        } else if let hir::ExprKind::Field(base, ..) = expr.kind {
196            // Ignore write to field
197            self.handle_assign(base);
198        } else {
199            let _ = self.visit_expr(expr);
200        }
201    }
202
203    fn check_for_self_assign(&mut self, assign: &'tcx hir::Expr<'tcx>) {
204        fn check_for_self_assign_helper<'tcx>(
205            typeck_results: &'tcx ty::TypeckResults<'tcx>,
206            lhs: &'tcx hir::Expr<'tcx>,
207            rhs: &'tcx hir::Expr<'tcx>,
208        ) -> bool {
209            match (&lhs.kind, &rhs.kind) {
210                (hir::ExprKind::Path(qpath_l), hir::ExprKind::Path(qpath_r)) => {
211                    if let (Res::Local(id_l), Res::Local(id_r)) = (
212                        typeck_results.qpath_res(qpath_l, lhs.hir_id),
213                        typeck_results.qpath_res(qpath_r, rhs.hir_id),
214                    ) {
215                        if id_l == id_r {
216                            return true;
217                        }
218                    }
219                    return false;
220                }
221                (hir::ExprKind::Field(lhs_l, ident_l), hir::ExprKind::Field(lhs_r, ident_r)) => {
222                    if ident_l == ident_r {
223                        return check_for_self_assign_helper(typeck_results, lhs_l, lhs_r);
224                    }
225                    return false;
226                }
227                _ => {
228                    return false;
229                }
230            }
231        }
232
233        if let hir::ExprKind::Assign(lhs, rhs, _) = assign.kind
234            && check_for_self_assign_helper(self.typeck_results(), lhs, rhs)
235            && !assign.span.from_expansion()
236        {
237            let is_field_assign = #[allow(non_exhaustive_omitted_patterns)] match lhs.kind {
    hir::ExprKind::Field(..) => true,
    _ => false,
}matches!(lhs.kind, hir::ExprKind::Field(..));
238            self.tcx.emit_node_span_lint(
239                lint::builtin::DEAD_CODE,
240                assign.hir_id,
241                assign.span,
242                UselessAssignment { is_field_assign, ty: self.typeck_results().expr_ty(lhs) },
243            )
244        }
245    }
246
247    fn handle_field_pattern_match(
248        &mut self,
249        lhs: &hir::Pat<'_>,
250        res: Res,
251        pats: &[hir::PatField<'_>],
252    ) {
253        let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
254            ty::Adt(adt, _) => {
255                // Marks the ADT live if its variant appears as the pattern,
256                // considering cases when we have `let T(x) = foo()` and `fn foo<T>() -> T;`,
257                // we will lose the liveness info of `T` cause we cannot mark it live when visiting `foo`.
258                // Related issue: https://github.com/rust-lang/rust/issues/120770
259                self.check_def_id(adt.did());
260                adt.variant_of_res(res)
261            }
262            _ => ::rustc_middle::util::bug::span_bug_fmt(lhs.span,
    format_args!("non-ADT in struct pattern"))span_bug!(lhs.span, "non-ADT in struct pattern"),
263        };
264        for pat in pats {
265            if let PatKind::Wild = pat.pat.kind {
266                continue;
267            }
268            let index = self.typeck_results().field_index(pat.hir_id);
269            self.insert_def_id(variant.fields[index].did);
270        }
271    }
272
273    fn handle_tuple_field_pattern_match(
274        &mut self,
275        lhs: &hir::Pat<'_>,
276        res: Res,
277        pats: &[hir::Pat<'_>],
278        dotdot: hir::DotDotPos,
279    ) {
280        let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
281            ty::Adt(adt, _) => {
282                // Marks the ADT live if its variant appears as the pattern
283                self.check_def_id(adt.did());
284                adt.variant_of_res(res)
285            }
286            _ => {
287                self.tcx.dcx().span_delayed_bug(lhs.span, "non-ADT in tuple struct pattern");
288                return;
289            }
290        };
291        let dotdot = dotdot.as_opt_usize().unwrap_or(pats.len());
292        let first_n = pats.iter().enumerate().take(dotdot);
293        let missing = variant.fields.len() - pats.len();
294        let last_n = pats.iter().enumerate().skip(dotdot).map(|(idx, pat)| (idx + missing, pat));
295        for (idx, pat) in first_n.chain(last_n) {
296            if let PatKind::Wild = pat.kind {
297                continue;
298            }
299            self.insert_def_id(variant.fields[FieldIdx::from_usize(idx)].did);
300        }
301    }
302
303    fn handle_offset_of(&mut self, expr: &'tcx hir::Expr<'tcx>) {
304        let indices = self
305            .typeck_results()
306            .offset_of_data()
307            .get(expr.hir_id)
308            .expect("no offset_of_data for offset_of");
309
310        for &(current_ty, variant, field) in indices {
311            match current_ty.kind() {
312                ty::Adt(def, _) => {
313                    let field = &def.variant(variant).fields[field];
314                    self.insert_def_id(field.did);
315                }
316                // we don't need to mark tuple fields as live,
317                // but we may need to mark subfields
318                ty::Tuple(_) => {}
319                _ => ::rustc_middle::util::bug::span_bug_fmt(expr.span,
    format_args!("named field access on non-ADT"))span_bug!(expr.span, "named field access on non-ADT"),
320            }
321        }
322    }
323
324    fn mark_live_symbols(&mut self) -> <MarkSymbolVisitor<'tcx> as Visitor<'tcx>>::Result {
325        while let Some(work) = self.worklist.pop() {
326            let (mut id, comes_from_allow_expect) = work;
327
328            // in the case of tuple struct constructors we want to check the item,
329            // not the generated tuple struct constructor function
330            if let DefKind::Ctor(..) = self.tcx.def_kind(id) {
331                id = self.tcx.local_parent(id);
332            }
333
334            // When using `#[allow]` or `#[expect]` of `dead_code`, we do a QOL improvement
335            // by declaring fn calls, statics, ... within said items as live, as well as
336            // the item itself, although technically this is not the case.
337            //
338            // This means that the lint for said items will never be fired.
339            //
340            // This doesn't make any difference for the item declared with `#[allow]`, as
341            // the lint firing will be a nop, as it will be silenced by the `#[allow]` of
342            // the item.
343            //
344            // However, for `#[expect]`, the presence or absence of the lint is relevant,
345            // so we don't add it to the list of live symbols when it comes from a
346            // `#[expect]`. This means that we will correctly report an item as live or not
347            // for the `#[expect]` case.
348            //
349            // Note that an item can and will be duplicated on the worklist with different
350            // `ComesFromAllowExpect`, particularly if it was added from the
351            // `effective_visibilities` query or from the `#[allow]`/`#[expect]` checks,
352            // this "duplication" is essential as otherwise a function with `#[expect]`
353            // called from a `pub fn` may be falsely reported as not live, falsely
354            // triggering the `unfulfilled_lint_expectations` lint.
355            match comes_from_allow_expect {
356                ComesFromAllowExpect::Yes => {}
357                ComesFromAllowExpect::No => {
358                    self.live_symbols.insert(id);
359                }
360            }
361
362            if !self.scanned.insert(id) {
363                continue;
364            }
365
366            // Avoid accessing the HIR for the synthesized associated type generated for RPITITs.
367            if self.tcx.is_impl_trait_in_trait(id.to_def_id()) {
368                self.live_symbols.insert(id);
369                continue;
370            }
371
372            self.visit_node(self.tcx.hir_node_by_def_id(id))?;
373        }
374
375        ControlFlow::Continue(())
376    }
377
378    /// Automatically generated items marked with `rustc_trivial_field_reads`
379    /// will be ignored for the purposes of dead code analysis (see PR #85200
380    /// for discussion).
381    fn should_ignore_impl_item(&mut self, impl_item: &hir::ImplItem<'_>) -> bool {
382        if let hir::ImplItemImplKind::Trait { .. } = impl_item.impl_kind
383            && let impl_of = self.tcx.local_parent(impl_item.owner_id.def_id)
384            && self.tcx.is_automatically_derived(impl_of.to_def_id())
385            && let trait_ref =
386                self.tcx.impl_trait_ref(impl_of).instantiate_identity().skip_norm_wip()
387            && {
        {
            'done:
                {
                for i in
                    ::rustc_hir::attrs::HasAttrs::get_attrs(trait_ref.def_id,
                        &self.tcx) {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(RustcTrivialFieldReads) => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(self.tcx, trait_ref.def_id, RustcTrivialFieldReads)
388        {
389            if let ty::Adt(adt_def, _) = trait_ref.self_ty().kind()
390                && let Some(adt_def_id) = adt_def.did().as_local()
391            {
392                self.ignored_derived_traits.entry(adt_def_id).or_default().insert(trait_ref.def_id);
393            }
394            return true;
395        }
396
397        false
398    }
399
400    fn visit_node(
401        &mut self,
402        node: Node<'tcx>,
403    ) -> <MarkSymbolVisitor<'tcx> as Visitor<'tcx>>::Result {
404        if let Node::ImplItem(impl_item) = node
405            && self.should_ignore_impl_item(impl_item)
406        {
407            return ControlFlow::Continue(());
408        }
409
410        let unconditionally_treated_fields_as_live =
411            self.repr_unconditionally_treats_fields_as_live;
412        let had_repr_simd = self.repr_has_repr_simd;
413        self.repr_unconditionally_treats_fields_as_live = false;
414        self.repr_has_repr_simd = false;
415        let walk_result = match node {
416            Node::Item(item) => match item.kind {
417                hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
418                    let def = self.tcx.adt_def(item.owner_id);
419                    self.repr_unconditionally_treats_fields_as_live =
420                        def.repr().c() || def.repr().transparent();
421                    self.repr_has_repr_simd = def.repr().simd();
422
423                    intravisit::walk_item(self, item)
424                }
425                hir::ItemKind::ForeignMod { .. } => ControlFlow::Continue(()),
426                hir::ItemKind::Trait(.., trait_item_refs) => {
427                    // mark assoc ty live if the trait is live
428                    for trait_item in trait_item_refs {
429                        if self.tcx.def_kind(trait_item.owner_id) == DefKind::AssocTy {
430                            self.check_def_id(trait_item.owner_id.to_def_id());
431                        }
432                    }
433                    intravisit::walk_item(self, item)
434                }
435                _ => intravisit::walk_item(self, item),
436            },
437            Node::TraitItem(trait_item) => {
438                // mark the trait live
439                let trait_item_id = trait_item.owner_id.to_def_id();
440                if let Some(trait_id) = self.tcx.trait_of_assoc(trait_item_id) {
441                    self.check_def_id(trait_id);
442                }
443                intravisit::walk_trait_item(self, trait_item)
444            }
445            Node::ImplItem(impl_item) => {
446                let item = self.tcx.local_parent(impl_item.owner_id.def_id);
447                if let hir::ImplItemImplKind::Inherent { .. } = impl_item.impl_kind {
448                    //// If it's a type whose items are live, then it's live, too.
449                    //// This is done to handle the case where, for example, the static
450                    //// method of a private type is used, but the type itself is never
451                    //// called directly.
452                    let self_ty = self.tcx.type_of(item).instantiate_identity().skip_norm_wip();
453                    match *self_ty.kind() {
454                        ty::Adt(def, _) => self.check_def_id(def.did()),
455                        ty::Foreign(did) => self.check_def_id(did),
456                        ty::Dynamic(data, ..) => {
457                            if let Some(def_id) = data.principal_def_id() {
458                                self.check_def_id(def_id)
459                            }
460                        }
461                        _ => {}
462                    }
463                }
464                intravisit::walk_impl_item(self, impl_item)
465            }
466            Node::ForeignItem(foreign_item) => intravisit::walk_foreign_item(self, foreign_item),
467            Node::OpaqueTy(opaq) => intravisit::walk_opaque_ty(self, opaq),
468            _ => ControlFlow::Continue(()),
469        };
470        self.repr_has_repr_simd = had_repr_simd;
471        self.repr_unconditionally_treats_fields_as_live = unconditionally_treated_fields_as_live;
472
473        walk_result
474    }
475
476    fn mark_as_used_if_union(&mut self, adt: ty::AdtDef<'tcx>, fields: &[hir::ExprField<'_>]) {
477        if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did().is_local() {
478            for field in fields {
479                let index = self.typeck_results().field_index(field.hir_id);
480                self.insert_def_id(adt.non_enum_variant().fields[index].did);
481            }
482        }
483    }
484
485    /// Returns whether `local_def_id` is potentially alive or not.
486    /// `local_def_id` points to an impl or an impl item,
487    /// both impl and impl item that may be passed to this function are of a trait,
488    /// and added into the unsolved_items during `create_and_seed_worklist`
489    fn check_impl_or_impl_item_live(&mut self, local_def_id: LocalDefId) -> bool {
490        let (impl_block_id, trait_def_id) = match self.tcx.def_kind(local_def_id) {
491            // assoc impl items of traits are live if the corresponding trait items are live
492            DefKind::AssocConst { .. } | DefKind::AssocTy | DefKind::AssocFn => {
493                let trait_item_id =
494                    self.tcx.trait_item_of(local_def_id).and_then(|def_id| def_id.as_local());
495                (self.tcx.local_parent(local_def_id), trait_item_id)
496            }
497            // impl items are live if the corresponding traits are live
498            DefKind::Impl { of_trait: true } => {
499                (local_def_id, self.tcx.impl_trait_id(local_def_id).as_local())
500            }
501            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
502        };
503
504        if let Some(trait_def_id) = trait_def_id
505            && !self.live_symbols.contains(&trait_def_id)
506        {
507            return false;
508        }
509
510        // The impl or impl item is used if the corresponding trait or trait item is used and the ty is used.
511        if let ty::Adt(adt, _) =
512            self.tcx.type_of(impl_block_id).instantiate_identity().skip_norm_wip().kind()
513            && let Some(adt_def_id) = adt.did().as_local()
514            && !self.live_symbols.contains(&adt_def_id)
515        {
516            return false;
517        }
518
519        true
520    }
521}
522
523impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
524    type Result = ControlFlow<ErrorGuaranteed>;
525
526    fn visit_nested_body(&mut self, body: hir::BodyId) -> Self::Result {
527        let typeck_results = self.tcx.typeck_body(body);
528
529        // The result shouldn't be tainted, otherwise it will cause ICE.
530        if let Some(guar) = typeck_results.tainted_by_errors {
531            return ControlFlow::Break(guar);
532        }
533
534        let old_maybe_typeck_results = self.maybe_typeck_results.replace(typeck_results);
535        let body = self.tcx.hir_body(body);
536        let result = self.visit_body(body);
537        self.maybe_typeck_results = old_maybe_typeck_results;
538
539        result
540    }
541
542    fn visit_variant_data(&mut self, def: &'tcx hir::VariantData<'tcx>) -> Self::Result {
543        let tcx = self.tcx;
544        let unconditionally_treat_fields_as_live = self.repr_unconditionally_treats_fields_as_live;
545        let has_repr_simd = self.repr_has_repr_simd;
546        let effective_visibilities = &tcx.effective_visibilities(());
547        let live_fields = def.fields().iter().filter_map(|f| {
548            let def_id = f.def_id;
549            if unconditionally_treat_fields_as_live || (f.is_positional() && has_repr_simd) {
550                return Some(def_id);
551            }
552            if !effective_visibilities.is_reachable(f.hir_id.owner.def_id) {
553                return None;
554            }
555            if effective_visibilities.is_reachable(def_id) { Some(def_id) } else { None }
556        });
557        self.live_symbols.extend(live_fields);
558
559        intravisit::walk_struct_def(self, def)
560    }
561
562    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) -> Self::Result {
563        match expr.kind {
564            hir::ExprKind::Path(ref qpath @ QPath::TypeRelative(..)) => {
565                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
566                self.handle_res(res);
567            }
568            hir::ExprKind::MethodCall(..) => {
569                self.lookup_and_handle_method(expr.hir_id);
570            }
571            hir::ExprKind::Field(ref lhs, ..) => {
572                if self.typeck_results().opt_field_index(expr.hir_id).is_some() {
573                    self.handle_field_access(lhs, expr.hir_id);
574                } else {
575                    self.tcx.dcx().span_delayed_bug(expr.span, "couldn't resolve index for field");
576                }
577            }
578            hir::ExprKind::Struct(qpath, fields, _) => {
579                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
580                self.handle_res(res);
581                if let ty::Adt(adt, _) = self.typeck_results().expr_ty(expr).kind() {
582                    self.mark_as_used_if_union(*adt, fields);
583                }
584            }
585            hir::ExprKind::Closure(cls) => {
586                self.insert_def_id(cls.def_id.to_def_id());
587            }
588            hir::ExprKind::OffsetOf(..) => {
589                self.handle_offset_of(expr);
590            }
591            hir::ExprKind::Assign(ref lhs, ..) => {
592                self.handle_assign(lhs);
593                self.check_for_self_assign(expr);
594            }
595            _ => (),
596        }
597
598        intravisit::walk_expr(self, expr)
599    }
600
601    fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) -> Self::Result {
602        // Inside the body, ignore constructions of variants
603        // necessary for the pattern to match. Those construction sites
604        // can't be reached unless the variant is constructed elsewhere.
605        let len = self.ignore_variant_stack.len();
606        self.ignore_variant_stack.extend(arm.pat.necessary_variants());
607        let result = intravisit::walk_arm(self, arm);
608        self.ignore_variant_stack.truncate(len);
609
610        result
611    }
612
613    fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Self::Result {
614        self.in_pat = true;
615        match pat.kind {
616            PatKind::Struct(ref path, fields, _) => {
617                let res = self.typeck_results().qpath_res(path, pat.hir_id);
618                self.handle_field_pattern_match(pat, res, fields);
619            }
620            PatKind::TupleStruct(ref qpath, fields, dotdot) => {
621                let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
622                self.handle_tuple_field_pattern_match(pat, res, fields, dotdot);
623            }
624            _ => (),
625        }
626
627        let result = intravisit::walk_pat(self, pat);
628        self.in_pat = false;
629
630        result
631    }
632
633    fn visit_pat_expr(&mut self, expr: &'tcx rustc_hir::PatExpr<'tcx>) -> Self::Result {
634        match &expr.kind {
635            rustc_hir::PatExprKind::Path(qpath) => {
636                // mark the type of variant live when meeting E::V in expr
637                if let ty::Adt(adt, _) = self.typeck_results().node_type(expr.hir_id).kind() {
638                    self.check_def_id(adt.did());
639                }
640
641                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
642                self.handle_res(res);
643            }
644            _ => {}
645        }
646        intravisit::walk_pat_expr(self, expr)
647    }
648
649    fn visit_path(&mut self, path: &hir::Path<'tcx>, _: hir::HirId) -> Self::Result {
650        self.handle_res(path.res);
651        intravisit::walk_path(self, path)
652    }
653
654    fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) -> Self::Result {
655        // When inline const blocks are used in pattern position, paths
656        // referenced by it should be considered as used.
657        let in_pat = mem::replace(&mut self.in_pat, false);
658
659        self.live_symbols.insert(c.def_id);
660        let result = intravisit::walk_anon_const(self, c);
661
662        self.in_pat = in_pat;
663
664        result
665    }
666
667    fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) -> Self::Result {
668        // When inline const blocks are used in pattern position, paths
669        // referenced by it should be considered as used.
670        let in_pat = mem::replace(&mut self.in_pat, false);
671
672        self.live_symbols.insert(c.def_id);
673        let result = intravisit::walk_inline_const(self, c);
674
675        self.in_pat = in_pat;
676
677        result
678    }
679
680    fn visit_trait_ref(&mut self, t: &'tcx hir::TraitRef<'tcx>) -> Self::Result {
681        if let Some(trait_def_id) = t.path.res.opt_def_id()
682            && let Some(segment) = t.path.segments.last()
683            && let Some(args) = segment.args
684        {
685            for constraint in args.constraints {
686                if let Some(local_def_id) = self
687                    .tcx
688                    .associated_items(trait_def_id)
689                    .find_by_ident_and_kind(
690                        self.tcx,
691                        constraint.ident,
692                        AssocTag::Const,
693                        trait_def_id,
694                    )
695                    .and_then(|item| item.def_id.as_local())
696                {
697                    self.worklist.push((local_def_id, ComesFromAllowExpect::No));
698                }
699            }
700        }
701
702        intravisit::walk_trait_ref(self, t)
703    }
704}
705
706fn has_allow_dead_code_or_lang_attr(
707    tcx: TyCtxt<'_>,
708    def_id: LocalDefId,
709) -> Option<ComesFromAllowExpect> {
710    fn has_allow_expect_dead_code(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
711        let hir_id = tcx.local_def_id_to_hir_id(def_id);
712        let lint_level = tcx.lint_level_at_node(lint::builtin::DEAD_CODE, hir_id).level;
713        #[allow(non_exhaustive_omitted_patterns)] match lint_level {
    lint::Allow | lint::Expect => true,
    _ => false,
}matches!(lint_level, lint::Allow | lint::Expect)
714    }
715
716    fn has_used_like_attr(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
717        tcx.def_kind(def_id).has_codegen_attrs() && {
718            let cg_attrs = tcx.codegen_fn_attrs(def_id);
719
720            // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
721            // forcefully, e.g., for placing it in a specific section.
722            cg_attrs.contains_extern_indicator()
723                || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)
724                || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)
725        }
726    }
727
728    if has_allow_expect_dead_code(tcx, def_id) {
729        Some(ComesFromAllowExpect::Yes)
730    } else if has_used_like_attr(tcx, def_id) || {
        {
            'done:
                {
                for i in ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &tcx)
                    {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(Lang(..)) => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(tcx, def_id, Lang(..)) {
731        Some(ComesFromAllowExpect::No)
732    } else {
733        None
734    }
735}
736
737/// Examine the given definition and record it in the worklist if it should be considered live.
738///
739/// We want to explicitly consider as live:
740/// * Item annotated with #[allow(dead_code)]
741///       This is done so that if we want to suppress warnings for a
742///       group of dead functions, we only have to annotate the "root".
743///       For example, if both `f` and `g` are dead and `f` calls `g`,
744///       then annotating `f` with `#[allow(dead_code)]` will suppress
745///       warning for both `f` and `g`.
746///
747/// * Item annotated with #[lang=".."]
748///       Lang items are always callable from elsewhere.
749///
750/// For trait methods and implementations of traits, we are not certain that the definitions are
751/// live at this stage. We record them in `unsolved_items` for later examination.
752fn maybe_record_as_seed<'tcx>(
753    tcx: TyCtxt<'tcx>,
754    owner_id: hir::OwnerId,
755    worklist: &mut Vec<(LocalDefId, ComesFromAllowExpect)>,
756    unsolved_items: &mut Vec<LocalDefId>,
757) {
758    let allow_dead_code = has_allow_dead_code_or_lang_attr(tcx, owner_id.def_id);
759    if let Some(comes_from_allow) = allow_dead_code {
760        worklist.push((owner_id.def_id, comes_from_allow));
761    }
762
763    match tcx.def_kind(owner_id) {
764        DefKind::Enum => {
765            if let Some(comes_from_allow) = allow_dead_code {
766                let adt = tcx.adt_def(owner_id);
767                worklist.extend(
768                    adt.variants()
769                        .iter()
770                        .map(|variant| (variant.def_id.expect_local(), comes_from_allow)),
771                );
772            }
773        }
774        DefKind::AssocFn | DefKind::AssocConst { .. } | DefKind::AssocTy => {
775            if allow_dead_code.is_none() {
776                let parent = tcx.local_parent(owner_id.def_id);
777                match tcx.def_kind(parent) {
778                    DefKind::Impl { of_trait: false } | DefKind::Trait => {}
779                    DefKind::Impl { of_trait: true } => {
780                        if let Some(trait_item_def_id) =
781                            tcx.associated_item(owner_id.def_id).trait_item_def_id()
782                            && let Some(trait_item_local_def_id) = trait_item_def_id.as_local()
783                            && let Some(comes_from_allow) =
784                                has_allow_dead_code_or_lang_attr(tcx, trait_item_local_def_id)
785                        {
786                            worklist.push((owner_id.def_id, comes_from_allow));
787                        }
788
789                        // We only care about associated items of traits,
790                        // because they cannot be visited directly,
791                        // so we later mark them as live if their corresponding traits
792                        // or trait items and self types are both live,
793                        // but inherent associated items can be visited and marked directly.
794                        unsolved_items.push(owner_id.def_id);
795                    }
796                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
797                }
798            }
799        }
800        DefKind::Impl { of_trait: true } => {
801            if allow_dead_code.is_none() {
802                if let Some(trait_def_id) =
803                    tcx.impl_trait_ref(owner_id.def_id).skip_binder().def_id.as_local()
804                    && let Some(comes_from_allow) =
805                        has_allow_dead_code_or_lang_attr(tcx, trait_def_id)
806                {
807                    worklist.push((owner_id.def_id, comes_from_allow));
808                }
809
810                unsolved_items.push(owner_id.def_id);
811            }
812        }
813        DefKind::GlobalAsm => {
814            // global_asm! is always live.
815            worklist.push((owner_id.def_id, ComesFromAllowExpect::No));
816        }
817        DefKind::Const { .. } => {
818            if tcx.item_name(owner_id.def_id) == kw::Underscore {
819                // `const _` is always live, as that syntax only exists for the side effects
820                // of type checking and evaluating the constant expression, and marking them
821                // as dead code would defeat that purpose.
822                worklist.push((owner_id.def_id, ComesFromAllowExpect::No));
823            }
824        }
825        _ => {}
826    }
827}
828
829fn create_and_seed_worklist(
830    tcx: TyCtxt<'_>,
831) -> (Vec<(LocalDefId, ComesFromAllowExpect)>, Vec<LocalDefId>) {
832    let effective_visibilities = &tcx.effective_visibilities(());
833    let mut unsolved_impl_item = Vec::new();
834    let mut worklist = effective_visibilities
835        .iter()
836        .filter_map(|(&id, effective_vis)| {
837            effective_vis
838                .is_public_at_level(Level::Reachable)
839                .then_some(id)
840                .map(|id| (id, ComesFromAllowExpect::No))
841        })
842        // Seed entry point
843        .chain(
844            tcx.entry_fn(())
845                .and_then(|(def_id, _)| def_id.as_local().map(|id| (id, ComesFromAllowExpect::No))),
846        )
847        .collect::<Vec<_>>();
848
849    let crate_items = tcx.hir_crate_items(());
850    for id in crate_items.owners() {
851        maybe_record_as_seed(tcx, id, &mut worklist, &mut unsolved_impl_item);
852    }
853
854    (worklist, unsolved_impl_item)
855}
856
857fn live_symbols_and_ignored_derived_traits(
858    tcx: TyCtxt<'_>,
859    (): (),
860) -> Result<(LocalDefIdSet, LocalDefIdMap<FxIndexSet<DefId>>), ErrorGuaranteed> {
861    let (worklist, mut unsolved_items) = create_and_seed_worklist(tcx);
862    let mut symbol_visitor = MarkSymbolVisitor {
863        worklist,
864        tcx,
865        maybe_typeck_results: None,
866        scanned: Default::default(),
867        live_symbols: Default::default(),
868        repr_unconditionally_treats_fields_as_live: false,
869        repr_has_repr_simd: false,
870        in_pat: false,
871        ignore_variant_stack: ::alloc::vec::Vec::new()vec![],
872        ignored_derived_traits: Default::default(),
873    };
874    if let ControlFlow::Break(guar) = symbol_visitor.mark_live_symbols() {
875        return Err(guar);
876    }
877
878    // We have marked the primary seeds as live. We now need to process unsolved items from traits
879    // and trait impls: add them to the work list if the trait or the implemented type is live.
880    let mut items_to_check: Vec<_> = unsolved_items
881        .extract_if(.., |&mut local_def_id| {
882            symbol_visitor.check_impl_or_impl_item_live(local_def_id)
883        })
884        .collect();
885
886    while !items_to_check.is_empty() {
887        symbol_visitor
888            .worklist
889            .extend(items_to_check.drain(..).map(|id| (id, ComesFromAllowExpect::No)));
890        if let ControlFlow::Break(guar) = symbol_visitor.mark_live_symbols() {
891            return Err(guar);
892        }
893
894        items_to_check.extend(unsolved_items.extract_if(.., |&mut local_def_id| {
895            symbol_visitor.check_impl_or_impl_item_live(local_def_id)
896        }));
897    }
898
899    Ok((symbol_visitor.live_symbols, symbol_visitor.ignored_derived_traits))
900}
901
902struct DeadItem {
903    def_id: LocalDefId,
904    name: Symbol,
905    level: (lint::Level, Option<LintExpectationId>),
906}
907
908struct DeadVisitor<'tcx> {
909    tcx: TyCtxt<'tcx>,
910    live_symbols: &'tcx LocalDefIdSet,
911    ignored_derived_traits: &'tcx LocalDefIdMap<FxIndexSet<DefId>>,
912}
913
914enum ShouldWarnAboutField {
915    Yes,
916    No,
917}
918
919#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ReportOn {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ReportOn::TupleField => "TupleField",
                ReportOn::NamedField => "NamedField",
            })
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for ReportOn { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ReportOn {
    #[inline]
    fn clone(&self) -> ReportOn { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ReportOn {
    #[inline]
    fn eq(&self, other: &ReportOn) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ReportOn {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
920enum ReportOn {
921    /// Report on something that hasn't got a proper name to refer to
922    TupleField,
923    /// Report on something that has got a name, which could be a field but also a method
924    NamedField,
925}
926
927impl<'tcx> DeadVisitor<'tcx> {
928    fn should_warn_about_field(&mut self, field: &ty::FieldDef) -> ShouldWarnAboutField {
929        if self.live_symbols.contains(&field.did.expect_local()) {
930            return ShouldWarnAboutField::No;
931        }
932        let field_type = self.tcx.type_of(field.did).instantiate_identity().skip_norm_wip();
933        if field_type.is_phantom_data() {
934            return ShouldWarnAboutField::No;
935        }
936        let is_positional = field.name.as_str().starts_with(|c: char| c.is_ascii_digit());
937        if is_positional
938            && self
939                .tcx
940                .layout_of(
941                    ty::TypingEnv::non_body_analysis(self.tcx, field.did)
942                        .as_query_input(field_type),
943                )
944                .map_or(true, |layout| layout.is_zst())
945        {
946            return ShouldWarnAboutField::No;
947        }
948        ShouldWarnAboutField::Yes
949    }
950
951    fn def_lint_level(&self, id: LocalDefId) -> (lint::Level, Option<LintExpectationId>) {
952        let hir_id = self.tcx.local_def_id_to_hir_id(id);
953        let level = self.tcx.lint_level_at_node(DEAD_CODE, hir_id);
954        (level.level, level.lint_id)
955    }
956
957    // # Panics
958    // All `dead_codes` must have the same lint level, otherwise we will intentionally ICE.
959    // This is because we emit a multi-spanned lint using the lint level of the `dead_codes`'s
960    // first local def id.
961    // Prefer calling `Self.warn_dead_code` or `Self.warn_dead_code_grouped_by_lint_level`
962    // since those methods group by lint level before calling this method.
963    fn lint_at_single_level(
964        &self,
965        dead_codes: &[&DeadItem],
966        participle: &str,
967        parent_item: Option<LocalDefId>,
968        report_on: ReportOn,
969    ) {
970        let Some(&first_item) = dead_codes.first() else { return };
971        let tcx = self.tcx;
972
973        let first_lint_level = first_item.level;
974        if !dead_codes.iter().skip(1).all(|item| item.level == first_lint_level) {
    ::core::panicking::panic("assertion failed: dead_codes.iter().skip(1).all(|item| item.level == first_lint_level)")
};assert!(dead_codes.iter().skip(1).all(|item| item.level == first_lint_level));
975
976        let names: Vec<_> = dead_codes.iter().map(|item| item.name).collect();
977        let spans: Vec<_> = dead_codes
978            .iter()
979            .map(|item| {
980                let span = tcx.def_span(item.def_id);
981                let ident_span = tcx.def_ident_span(item.def_id);
982                // FIXME(cjgillot) this SyntaxContext manipulation does not make any sense.
983                ident_span.map(|s| s.with_ctxt(span.ctxt())).unwrap_or(span)
984            })
985            .collect();
986
987        let mut descr = tcx.def_descr(first_item.def_id.to_def_id());
988        // `impl` blocks are "batched" and (unlike other batching) might
989        // contain different kinds of associated items.
990        if dead_codes.iter().any(|item| tcx.def_descr(item.def_id.to_def_id()) != descr) {
991            descr = "associated item"
992        }
993
994        let num = dead_codes.len();
995        let multiple = num > 6;
996        let name_list = names.into();
997
998        let parent_info = parent_item.map(|parent_item| {
999            let parent_descr = tcx.def_descr(parent_item.to_def_id());
1000            let span = if let DefKind::Impl { .. } = tcx.def_kind(parent_item) {
1001                tcx.def_span(parent_item)
1002            } else {
1003                tcx.def_ident_span(parent_item).unwrap()
1004            };
1005            ParentInfo { num, descr, parent_descr, span }
1006        });
1007
1008        let mut encl_def_id = parent_item.unwrap_or(first_item.def_id);
1009        // `ignored_derived_traits` is computed for the enum, not for the variants.
1010        if let DefKind::Variant = tcx.def_kind(encl_def_id) {
1011            encl_def_id = tcx.local_parent(encl_def_id);
1012        }
1013
1014        let ignored_derived_impls =
1015            self.ignored_derived_traits.get(&encl_def_id).map(|ign_traits| {
1016                let trait_list = ign_traits
1017                    .iter()
1018                    .map(|trait_id| self.tcx.item_name(*trait_id))
1019                    .collect::<Vec<_>>();
1020                let trait_list_len = trait_list.len();
1021                IgnoredDerivedImpls {
1022                    name: self.tcx.item_name(encl_def_id.to_def_id()),
1023                    trait_list: trait_list.into(),
1024                    trait_list_len,
1025                }
1026            });
1027
1028        let diag = match report_on {
1029            ReportOn::TupleField => {
1030                let tuple_fields = if let Some(parent_id) = parent_item
1031                    && let node = tcx.hir_node_by_def_id(parent_id)
1032                    && let hir::Node::Item(hir::Item {
1033                        kind: hir::ItemKind::Struct(_, _, hir::VariantData::Tuple(fields, _, _)),
1034                        ..
1035                    }) = node
1036                {
1037                    *fields
1038                } else {
1039                    &[]
1040                };
1041
1042                let trailing_tuple_fields = if tuple_fields.len() >= dead_codes.len() {
1043                    LocalDefIdSet::from_iter(
1044                        tuple_fields
1045                            .iter()
1046                            .skip(tuple_fields.len() - dead_codes.len())
1047                            .map(|f| f.def_id),
1048                    )
1049                } else {
1050                    LocalDefIdSet::default()
1051                };
1052
1053                let fields_suggestion =
1054                    // Suggest removal if all tuple fields are at the end.
1055                    // Otherwise suggest removal or changing to unit type
1056                    if dead_codes.iter().all(|dc| trailing_tuple_fields.contains(&dc.def_id)) {
1057                        ChangeFields::Remove { num }
1058                    } else {
1059                        ChangeFields::ChangeToUnitTypeOrRemove { num, spans: spans.clone() }
1060                    };
1061
1062                MultipleDeadCodes::UnusedTupleStructFields {
1063                    multiple,
1064                    num,
1065                    descr,
1066                    participle,
1067                    name_list,
1068                    change_fields_suggestion: fields_suggestion,
1069                    parent_info,
1070                    ignored_derived_impls,
1071                }
1072            }
1073            ReportOn::NamedField => {
1074                let enum_variants_with_same_name = dead_codes
1075                    .iter()
1076                    .filter_map(|dead_item| {
1077                        if let DefKind::AssocFn | DefKind::AssocConst { .. } =
1078                            tcx.def_kind(dead_item.def_id)
1079                            && let impl_did = tcx.local_parent(dead_item.def_id)
1080                            && let DefKind::Impl { of_trait: false } = tcx.def_kind(impl_did)
1081                            && let ty::Adt(maybe_enum, _) =
1082                                tcx.type_of(impl_did).instantiate_identity().skip_norm_wip().kind()
1083                            && maybe_enum.is_enum()
1084                            && let Some(variant) =
1085                                maybe_enum.variants().iter().find(|i| i.name == dead_item.name)
1086                        {
1087                            Some(crate::errors::EnumVariantSameName {
1088                                dead_descr: tcx.def_descr(dead_item.def_id.to_def_id()),
1089                                dead_name: dead_item.name,
1090                                variant_span: tcx.def_span(variant.def_id),
1091                            })
1092                        } else {
1093                            None
1094                        }
1095                    })
1096                    .collect();
1097
1098                MultipleDeadCodes::DeadCodes {
1099                    multiple,
1100                    num,
1101                    descr,
1102                    participle,
1103                    name_list,
1104                    parent_info,
1105                    ignored_derived_impls,
1106                    enum_variants_with_same_name,
1107                }
1108            }
1109        };
1110
1111        let hir_id = tcx.local_def_id_to_hir_id(first_item.def_id);
1112        self.tcx.emit_node_span_lint(DEAD_CODE, hir_id, MultiSpan::from_spans(spans), diag);
1113    }
1114
1115    fn warn_multiple(
1116        &self,
1117        def_id: LocalDefId,
1118        participle: &str,
1119        dead_codes: Vec<DeadItem>,
1120        report_on: ReportOn,
1121    ) {
1122        let mut dead_codes = dead_codes
1123            .iter()
1124            .filter(|v| !v.name.as_str().starts_with('_'))
1125            .collect::<Vec<&DeadItem>>();
1126        if dead_codes.is_empty() {
1127            return;
1128        }
1129        // FIXME: `dead_codes` should probably be morally equivalent to `IndexMap<(Level, LintExpectationId), (DefId, Symbol)>`
1130        dead_codes.sort_by_key(|v| v.level.0);
1131        for group in dead_codes.chunk_by(|a, b| a.level == b.level) {
1132            self.lint_at_single_level(&group, participle, Some(def_id), report_on);
1133        }
1134    }
1135
1136    fn warn_dead_code(&mut self, id: LocalDefId, participle: &str) {
1137        let item = DeadItem {
1138            def_id: id,
1139            name: self.tcx.item_name(id.to_def_id()),
1140            level: self.def_lint_level(id),
1141        };
1142        self.lint_at_single_level(&[&item], participle, None, ReportOn::NamedField);
1143    }
1144
1145    fn check_definition(&mut self, def_id: LocalDefId) {
1146        if self.is_live_code(def_id) {
1147            return;
1148        }
1149        match self.tcx.def_kind(def_id) {
1150            DefKind::AssocConst { .. }
1151            | DefKind::AssocTy
1152            | DefKind::AssocFn
1153            | DefKind::Fn
1154            | DefKind::Static { .. }
1155            | DefKind::Const { .. }
1156            | DefKind::TyAlias
1157            | DefKind::Enum
1158            | DefKind::Union
1159            | DefKind::ForeignTy
1160            | DefKind::Trait => self.warn_dead_code(def_id, "used"),
1161            DefKind::Struct => self.warn_dead_code(def_id, "constructed"),
1162            DefKind::Variant | DefKind::Field => ::rustc_middle::util::bug::bug_fmt(format_args!("should be handled specially"))bug!("should be handled specially"),
1163            _ => {}
1164        }
1165    }
1166
1167    fn is_live_code(&self, def_id: LocalDefId) -> bool {
1168        // if we cannot get a name for the item, then we just assume that it is
1169        // live. I mean, we can't really emit a lint.
1170        let Some(name) = self.tcx.opt_item_name(def_id.to_def_id()) else {
1171            return true;
1172        };
1173
1174        self.live_symbols.contains(&def_id) || name.as_str().starts_with('_')
1175    }
1176}
1177
1178fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalModDefId) {
1179    let Ok((live_symbols, ignored_derived_traits)) =
1180        tcx.live_symbols_and_ignored_derived_traits(()).as_ref()
1181    else {
1182        return;
1183    };
1184
1185    let mut visitor = DeadVisitor { tcx, live_symbols, ignored_derived_traits };
1186
1187    let module_items = tcx.hir_module_items(module);
1188
1189    for item in module_items.free_items() {
1190        let def_kind = tcx.def_kind(item.owner_id);
1191
1192        let mut dead_codes = Vec::new();
1193        // Only diagnose unused assoc items in inherent impl and used trait,
1194        // for unused assoc items in impls of trait,
1195        // we have diagnosed them in the trait if they are unused,
1196        // for unused assoc items in unused trait,
1197        // we have diagnosed the unused trait.
1198        if def_kind == (DefKind::Impl { of_trait: false })
1199            || (def_kind == DefKind::Trait && live_symbols.contains(&item.owner_id.def_id))
1200        {
1201            for &def_id in tcx.associated_item_def_ids(item.owner_id.def_id) {
1202                if let Some(local_def_id) = def_id.as_local()
1203                    && !visitor.is_live_code(local_def_id)
1204                {
1205                    let name = tcx.item_name(def_id);
1206                    let level = visitor.def_lint_level(local_def_id);
1207                    dead_codes.push(DeadItem { def_id: local_def_id, name, level });
1208                }
1209            }
1210        }
1211        if !dead_codes.is_empty() {
1212            visitor.warn_multiple(item.owner_id.def_id, "used", dead_codes, ReportOn::NamedField);
1213        }
1214
1215        if !live_symbols.contains(&item.owner_id.def_id) {
1216            let parent = tcx.local_parent(item.owner_id.def_id);
1217            if parent != module.to_local_def_id() && !live_symbols.contains(&parent) {
1218                // We already have diagnosed something.
1219                continue;
1220            }
1221            visitor.check_definition(item.owner_id.def_id);
1222            continue;
1223        }
1224
1225        if let DefKind::Struct | DefKind::Union | DefKind::Enum = def_kind {
1226            let adt = tcx.adt_def(item.owner_id);
1227            let mut dead_variants = Vec::new();
1228
1229            for variant in adt.variants() {
1230                let def_id = variant.def_id.expect_local();
1231                if !live_symbols.contains(&def_id) {
1232                    // Record to group diagnostics.
1233                    let level = visitor.def_lint_level(def_id);
1234                    dead_variants.push(DeadItem { def_id, name: variant.name, level });
1235                    continue;
1236                }
1237
1238                let is_positional = variant.fields.raw.first().is_some_and(|field| {
1239                    field.name.as_str().starts_with(|c: char| c.is_ascii_digit())
1240                });
1241                let report_on =
1242                    if is_positional { ReportOn::TupleField } else { ReportOn::NamedField };
1243                let dead_fields = variant
1244                    .fields
1245                    .iter()
1246                    .filter_map(|field| {
1247                        let def_id = field.did.expect_local();
1248                        if let ShouldWarnAboutField::Yes = visitor.should_warn_about_field(field) {
1249                            let level = visitor.def_lint_level(def_id);
1250                            Some(DeadItem { def_id, name: field.name, level })
1251                        } else {
1252                            None
1253                        }
1254                    })
1255                    .collect();
1256                visitor.warn_multiple(def_id, "read", dead_fields, report_on);
1257            }
1258
1259            visitor.warn_multiple(
1260                item.owner_id.def_id,
1261                "constructed",
1262                dead_variants,
1263                ReportOn::NamedField,
1264            );
1265        }
1266    }
1267
1268    for foreign_item in module_items.foreign_items() {
1269        visitor.check_definition(foreign_item.owner_id.def_id);
1270    }
1271}
1272
1273pub(crate) fn provide(providers: &mut Providers) {
1274    *providers =
1275        Providers { live_symbols_and_ignored_derived_traits, check_mod_deathness, ..*providers };
1276}