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::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.parent(impl_item.owner_id.to_def_id())
384            && self.tcx.is_automatically_derived(impl_of)
385            && let trait_ref = self.tcx.impl_trait_ref(impl_of).instantiate_identity()
386            && {

        #[allow(deprecated)]
        {
            {
                'done:
                    {
                    for i in self.tcx.get_all_attrs(trait_ref.def_id) {
                        #[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)
387        {
388            if let ty::Adt(adt_def, _) = trait_ref.self_ty().kind()
389                && let Some(adt_def_id) = adt_def.did().as_local()
390            {
391                self.ignored_derived_traits.entry(adt_def_id).or_default().insert(trait_ref.def_id);
392            }
393            return true;
394        }
395
396        false
397    }
398
399    fn visit_node(
400        &mut self,
401        node: Node<'tcx>,
402    ) -> <MarkSymbolVisitor<'tcx> as Visitor<'tcx>>::Result {
403        if let Node::ImplItem(impl_item) = node
404            && self.should_ignore_impl_item(impl_item)
405        {
406            return ControlFlow::Continue(());
407        }
408
409        let unconditionally_treated_fields_as_live =
410            self.repr_unconditionally_treats_fields_as_live;
411        let had_repr_simd = self.repr_has_repr_simd;
412        self.repr_unconditionally_treats_fields_as_live = false;
413        self.repr_has_repr_simd = false;
414        let walk_result = match node {
415            Node::Item(item) => match item.kind {
416                hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
417                    let def = self.tcx.adt_def(item.owner_id);
418                    self.repr_unconditionally_treats_fields_as_live =
419                        def.repr().c() || def.repr().transparent();
420                    self.repr_has_repr_simd = def.repr().simd();
421
422                    intravisit::walk_item(self, item)
423                }
424                hir::ItemKind::ForeignMod { .. } => ControlFlow::Continue(()),
425                hir::ItemKind::Trait(.., trait_item_refs) => {
426                    // mark assoc ty live if the trait is live
427                    for trait_item in trait_item_refs {
428                        if self.tcx.def_kind(trait_item.owner_id) == DefKind::AssocTy {
429                            self.check_def_id(trait_item.owner_id.to_def_id());
430                        }
431                    }
432                    intravisit::walk_item(self, item)
433                }
434                _ => intravisit::walk_item(self, item),
435            },
436            Node::TraitItem(trait_item) => {
437                // mark the trait live
438                let trait_item_id = trait_item.owner_id.to_def_id();
439                if let Some(trait_id) = self.tcx.trait_of_assoc(trait_item_id) {
440                    self.check_def_id(trait_id);
441                }
442                intravisit::walk_trait_item(self, trait_item)
443            }
444            Node::ImplItem(impl_item) => {
445                let item = self.tcx.local_parent(impl_item.owner_id.def_id);
446                if let hir::ImplItemImplKind::Inherent { .. } = impl_item.impl_kind {
447                    //// If it's a type whose items are live, then it's live, too.
448                    //// This is done to handle the case where, for example, the static
449                    //// method of a private type is used, but the type itself is never
450                    //// called directly.
451                    let self_ty = self.tcx.type_of(item).instantiate_identity();
452                    match *self_ty.kind() {
453                        ty::Adt(def, _) => self.check_def_id(def.did()),
454                        ty::Foreign(did) => self.check_def_id(did),
455                        ty::Dynamic(data, ..) => {
456                            if let Some(def_id) = data.principal_def_id() {
457                                self.check_def_id(def_id)
458                            }
459                        }
460                        _ => {}
461                    }
462                }
463                intravisit::walk_impl_item(self, impl_item)
464            }
465            Node::ForeignItem(foreign_item) => intravisit::walk_foreign_item(self, foreign_item),
466            Node::OpaqueTy(opaq) => intravisit::walk_opaque_ty(self, opaq),
467            _ => ControlFlow::Continue(()),
468        };
469        self.repr_has_repr_simd = had_repr_simd;
470        self.repr_unconditionally_treats_fields_as_live = unconditionally_treated_fields_as_live;
471
472        walk_result
473    }
474
475    fn mark_as_used_if_union(&mut self, adt: ty::AdtDef<'tcx>, fields: &[hir::ExprField<'_>]) {
476        if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did().is_local() {
477            for field in fields {
478                let index = self.typeck_results().field_index(field.hir_id);
479                self.insert_def_id(adt.non_enum_variant().fields[index].did);
480            }
481        }
482    }
483
484    /// Returns whether `local_def_id` is potentially alive or not.
485    /// `local_def_id` points to an impl or an impl item,
486    /// both impl and impl item that may be passed to this function are of a trait,
487    /// and added into the unsolved_items during `create_and_seed_worklist`
488    fn check_impl_or_impl_item_live(&mut self, local_def_id: LocalDefId) -> bool {
489        let (impl_block_id, trait_def_id) = match self.tcx.def_kind(local_def_id) {
490            // assoc impl items of traits are live if the corresponding trait items are live
491            DefKind::AssocConst { .. } | DefKind::AssocTy | DefKind::AssocFn => {
492                let trait_item_id =
493                    self.tcx.trait_item_of(local_def_id).and_then(|def_id| def_id.as_local());
494                (self.tcx.local_parent(local_def_id), trait_item_id)
495            }
496            // impl items are live if the corresponding traits are live
497            DefKind::Impl { of_trait: true } => {
498                (local_def_id, self.tcx.impl_trait_id(local_def_id).as_local())
499            }
500            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
501        };
502
503        if let Some(trait_def_id) = trait_def_id
504            && !self.live_symbols.contains(&trait_def_id)
505        {
506            return false;
507        }
508
509        // The impl or impl item is used if the corresponding trait or trait item is used and the ty is used.
510        if let ty::Adt(adt, _) = self.tcx.type_of(impl_block_id).instantiate_identity().kind()
511            && let Some(adt_def_id) = adt.did().as_local()
512            && !self.live_symbols.contains(&adt_def_id)
513        {
514            return false;
515        }
516
517        true
518    }
519}
520
521impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
522    type Result = ControlFlow<ErrorGuaranteed>;
523
524    fn visit_nested_body(&mut self, body: hir::BodyId) -> Self::Result {
525        let typeck_results = self.tcx.typeck_body(body);
526
527        // The result shouldn't be tainted, otherwise it will cause ICE.
528        if let Some(guar) = typeck_results.tainted_by_errors {
529            return ControlFlow::Break(guar);
530        }
531
532        let old_maybe_typeck_results = self.maybe_typeck_results.replace(typeck_results);
533        let body = self.tcx.hir_body(body);
534        let result = self.visit_body(body);
535        self.maybe_typeck_results = old_maybe_typeck_results;
536
537        result
538    }
539
540    fn visit_variant_data(&mut self, def: &'tcx hir::VariantData<'tcx>) -> Self::Result {
541        let tcx = self.tcx;
542        let unconditionally_treat_fields_as_live = self.repr_unconditionally_treats_fields_as_live;
543        let has_repr_simd = self.repr_has_repr_simd;
544        let effective_visibilities = &tcx.effective_visibilities(());
545        let live_fields = def.fields().iter().filter_map(|f| {
546            let def_id = f.def_id;
547            if unconditionally_treat_fields_as_live || (f.is_positional() && has_repr_simd) {
548                return Some(def_id);
549            }
550            if !effective_visibilities.is_reachable(f.hir_id.owner.def_id) {
551                return None;
552            }
553            if effective_visibilities.is_reachable(def_id) { Some(def_id) } else { None }
554        });
555        self.live_symbols.extend(live_fields);
556
557        intravisit::walk_struct_def(self, def)
558    }
559
560    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) -> Self::Result {
561        match expr.kind {
562            hir::ExprKind::Path(ref qpath @ QPath::TypeRelative(..)) => {
563                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
564                self.handle_res(res);
565            }
566            hir::ExprKind::MethodCall(..) => {
567                self.lookup_and_handle_method(expr.hir_id);
568            }
569            hir::ExprKind::Field(ref lhs, ..) => {
570                if self.typeck_results().opt_field_index(expr.hir_id).is_some() {
571                    self.handle_field_access(lhs, expr.hir_id);
572                } else {
573                    self.tcx.dcx().span_delayed_bug(expr.span, "couldn't resolve index for field");
574                }
575            }
576            hir::ExprKind::Struct(qpath, fields, _) => {
577                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
578                self.handle_res(res);
579                if let ty::Adt(adt, _) = self.typeck_results().expr_ty(expr).kind() {
580                    self.mark_as_used_if_union(*adt, fields);
581                }
582            }
583            hir::ExprKind::Closure(cls) => {
584                self.insert_def_id(cls.def_id.to_def_id());
585            }
586            hir::ExprKind::OffsetOf(..) => {
587                self.handle_offset_of(expr);
588            }
589            hir::ExprKind::Assign(ref lhs, ..) => {
590                self.handle_assign(lhs);
591                self.check_for_self_assign(expr);
592            }
593            _ => (),
594        }
595
596        intravisit::walk_expr(self, expr)
597    }
598
599    fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) -> Self::Result {
600        // Inside the body, ignore constructions of variants
601        // necessary for the pattern to match. Those construction sites
602        // can't be reached unless the variant is constructed elsewhere.
603        let len = self.ignore_variant_stack.len();
604        self.ignore_variant_stack.extend(arm.pat.necessary_variants());
605        let result = intravisit::walk_arm(self, arm);
606        self.ignore_variant_stack.truncate(len);
607
608        result
609    }
610
611    fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Self::Result {
612        self.in_pat = true;
613        match pat.kind {
614            PatKind::Struct(ref path, fields, _) => {
615                let res = self.typeck_results().qpath_res(path, pat.hir_id);
616                self.handle_field_pattern_match(pat, res, fields);
617            }
618            PatKind::TupleStruct(ref qpath, fields, dotdot) => {
619                let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
620                self.handle_tuple_field_pattern_match(pat, res, fields, dotdot);
621            }
622            _ => (),
623        }
624
625        let result = intravisit::walk_pat(self, pat);
626        self.in_pat = false;
627
628        result
629    }
630
631    fn visit_pat_expr(&mut self, expr: &'tcx rustc_hir::PatExpr<'tcx>) -> Self::Result {
632        match &expr.kind {
633            rustc_hir::PatExprKind::Path(qpath) => {
634                // mark the type of variant live when meeting E::V in expr
635                if let ty::Adt(adt, _) = self.typeck_results().node_type(expr.hir_id).kind() {
636                    self.check_def_id(adt.did());
637                }
638
639                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
640                self.handle_res(res);
641            }
642            _ => {}
643        }
644        intravisit::walk_pat_expr(self, expr)
645    }
646
647    fn visit_path(&mut self, path: &hir::Path<'tcx>, _: hir::HirId) -> Self::Result {
648        self.handle_res(path.res);
649        intravisit::walk_path(self, path)
650    }
651
652    fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) -> Self::Result {
653        // When inline const blocks are used in pattern position, paths
654        // referenced by it should be considered as used.
655        let in_pat = mem::replace(&mut self.in_pat, false);
656
657        self.live_symbols.insert(c.def_id);
658        let result = intravisit::walk_anon_const(self, c);
659
660        self.in_pat = in_pat;
661
662        result
663    }
664
665    fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) -> Self::Result {
666        // When inline const blocks are used in pattern position, paths
667        // referenced by it should be considered as used.
668        let in_pat = mem::replace(&mut self.in_pat, false);
669
670        self.live_symbols.insert(c.def_id);
671        let result = intravisit::walk_inline_const(self, c);
672
673        self.in_pat = in_pat;
674
675        result
676    }
677
678    fn visit_trait_ref(&mut self, t: &'tcx hir::TraitRef<'tcx>) -> Self::Result {
679        if let Some(trait_def_id) = t.path.res.opt_def_id()
680            && let Some(segment) = t.path.segments.last()
681            && let Some(args) = segment.args
682        {
683            for constraint in args.constraints {
684                if let Some(local_def_id) = self
685                    .tcx
686                    .associated_items(trait_def_id)
687                    .find_by_ident_and_kind(
688                        self.tcx,
689                        constraint.ident,
690                        AssocTag::Const,
691                        trait_def_id,
692                    )
693                    .and_then(|item| item.def_id.as_local())
694                {
695                    self.worklist.push((local_def_id, ComesFromAllowExpect::No));
696                }
697            }
698        }
699
700        intravisit::walk_trait_ref(self, t)
701    }
702}
703
704fn has_allow_dead_code_or_lang_attr(
705    tcx: TyCtxt<'_>,
706    def_id: LocalDefId,
707) -> Option<ComesFromAllowExpect> {
708    fn has_allow_expect_dead_code(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
709        let hir_id = tcx.local_def_id_to_hir_id(def_id);
710        let lint_level = tcx.lint_level_at_node(lint::builtin::DEAD_CODE, hir_id).level;
711        #[allow(non_exhaustive_omitted_patterns)] match lint_level {
    lint::Allow | lint::Expect => true,
    _ => false,
}matches!(lint_level, lint::Allow | lint::Expect)
712    }
713
714    fn has_used_like_attr(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
715        tcx.def_kind(def_id).has_codegen_attrs() && {
716            let cg_attrs = tcx.codegen_fn_attrs(def_id);
717
718            // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
719            // forcefully, e.g., for placing it in a specific section.
720            cg_attrs.contains_extern_indicator()
721                || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)
722                || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)
723        }
724    }
725
726    if has_allow_expect_dead_code(tcx, def_id) {
727        Some(ComesFromAllowExpect::Yes)
728    } else if has_used_like_attr(tcx, def_id) || {

        #[allow(deprecated)]
        {
            {
                'done:
                    {
                    for i in tcx.get_all_attrs(def_id) {
                        #[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(..)) {
729        Some(ComesFromAllowExpect::No)
730    } else {
731        None
732    }
733}
734
735/// Examine the given definition and record it in the worklist if it should be considered live.
736///
737/// We want to explicitly consider as live:
738/// * Item annotated with #[allow(dead_code)]
739///       This is done so that if we want to suppress warnings for a
740///       group of dead functions, we only have to annotate the "root".
741///       For example, if both `f` and `g` are dead and `f` calls `g`,
742///       then annotating `f` with `#[allow(dead_code)]` will suppress
743///       warning for both `f` and `g`.
744///
745/// * Item annotated with #[lang=".."]
746///       Lang items are always callable from elsewhere.
747///
748/// For trait methods and implementations of traits, we are not certain that the definitions are
749/// live at this stage. We record them in `unsolved_items` for later examination.
750fn maybe_record_as_seed<'tcx>(
751    tcx: TyCtxt<'tcx>,
752    owner_id: hir::OwnerId,
753    worklist: &mut Vec<(LocalDefId, ComesFromAllowExpect)>,
754    unsolved_items: &mut Vec<LocalDefId>,
755) {
756    let allow_dead_code = has_allow_dead_code_or_lang_attr(tcx, owner_id.def_id);
757    if let Some(comes_from_allow) = allow_dead_code {
758        worklist.push((owner_id.def_id, comes_from_allow));
759    }
760
761    match tcx.def_kind(owner_id) {
762        DefKind::Enum => {
763            if let Some(comes_from_allow) = allow_dead_code {
764                let adt = tcx.adt_def(owner_id);
765                worklist.extend(
766                    adt.variants()
767                        .iter()
768                        .map(|variant| (variant.def_id.expect_local(), comes_from_allow)),
769                );
770            }
771        }
772        DefKind::AssocFn | DefKind::AssocConst { .. } | DefKind::AssocTy => {
773            if allow_dead_code.is_none() {
774                let parent = tcx.local_parent(owner_id.def_id);
775                match tcx.def_kind(parent) {
776                    DefKind::Impl { of_trait: false } | DefKind::Trait => {}
777                    DefKind::Impl { of_trait: true } => {
778                        if let Some(trait_item_def_id) =
779                            tcx.associated_item(owner_id.def_id).trait_item_def_id()
780                            && let Some(trait_item_local_def_id) = trait_item_def_id.as_local()
781                            && let Some(comes_from_allow) =
782                                has_allow_dead_code_or_lang_attr(tcx, trait_item_local_def_id)
783                        {
784                            worklist.push((owner_id.def_id, comes_from_allow));
785                        }
786
787                        // We only care about associated items of traits,
788                        // because they cannot be visited directly,
789                        // so we later mark them as live if their corresponding traits
790                        // or trait items and self types are both live,
791                        // but inherent associated items can be visited and marked directly.
792                        unsolved_items.push(owner_id.def_id);
793                    }
794                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
795                }
796            }
797        }
798        DefKind::Impl { of_trait: true } => {
799            if allow_dead_code.is_none() {
800                if let Some(trait_def_id) =
801                    tcx.impl_trait_ref(owner_id.def_id).skip_binder().def_id.as_local()
802                    && let Some(comes_from_allow) =
803                        has_allow_dead_code_or_lang_attr(tcx, trait_def_id)
804                {
805                    worklist.push((owner_id.def_id, comes_from_allow));
806                }
807
808                unsolved_items.push(owner_id.def_id);
809            }
810        }
811        DefKind::GlobalAsm => {
812            // global_asm! is always live.
813            worklist.push((owner_id.def_id, ComesFromAllowExpect::No));
814        }
815        DefKind::Const { .. } => {
816            if tcx.item_name(owner_id.def_id) == kw::Underscore {
817                // `const _` is always live, as that syntax only exists for the side effects
818                // of type checking and evaluating the constant expression, and marking them
819                // as dead code would defeat that purpose.
820                worklist.push((owner_id.def_id, ComesFromAllowExpect::No));
821            }
822        }
823        _ => {}
824    }
825}
826
827fn create_and_seed_worklist(
828    tcx: TyCtxt<'_>,
829) -> (Vec<(LocalDefId, ComesFromAllowExpect)>, Vec<LocalDefId>) {
830    let effective_visibilities = &tcx.effective_visibilities(());
831    let mut unsolved_impl_item = Vec::new();
832    let mut worklist = effective_visibilities
833        .iter()
834        .filter_map(|(&id, effective_vis)| {
835            effective_vis
836                .is_public_at_level(Level::Reachable)
837                .then_some(id)
838                .map(|id| (id, ComesFromAllowExpect::No))
839        })
840        // Seed entry point
841        .chain(
842            tcx.entry_fn(())
843                .and_then(|(def_id, _)| def_id.as_local().map(|id| (id, ComesFromAllowExpect::No))),
844        )
845        .collect::<Vec<_>>();
846
847    let crate_items = tcx.hir_crate_items(());
848    for id in crate_items.owners() {
849        maybe_record_as_seed(tcx, id, &mut worklist, &mut unsolved_impl_item);
850    }
851
852    (worklist, unsolved_impl_item)
853}
854
855fn live_symbols_and_ignored_derived_traits(
856    tcx: TyCtxt<'_>,
857    (): (),
858) -> Result<(LocalDefIdSet, LocalDefIdMap<FxIndexSet<DefId>>), ErrorGuaranteed> {
859    let (worklist, mut unsolved_items) = create_and_seed_worklist(tcx);
860    let mut symbol_visitor = MarkSymbolVisitor {
861        worklist,
862        tcx,
863        maybe_typeck_results: None,
864        scanned: Default::default(),
865        live_symbols: Default::default(),
866        repr_unconditionally_treats_fields_as_live: false,
867        repr_has_repr_simd: false,
868        in_pat: false,
869        ignore_variant_stack: ::alloc::vec::Vec::new()vec![],
870        ignored_derived_traits: Default::default(),
871    };
872    if let ControlFlow::Break(guar) = symbol_visitor.mark_live_symbols() {
873        return Err(guar);
874    }
875
876    // We have marked the primary seeds as live. We now need to process unsolved items from traits
877    // and trait impls: add them to the work list if the trait or the implemented type is live.
878    let mut items_to_check: Vec<_> = unsolved_items
879        .extract_if(.., |&mut local_def_id| {
880            symbol_visitor.check_impl_or_impl_item_live(local_def_id)
881        })
882        .collect();
883
884    while !items_to_check.is_empty() {
885        symbol_visitor
886            .worklist
887            .extend(items_to_check.drain(..).map(|id| (id, ComesFromAllowExpect::No)));
888        if let ControlFlow::Break(guar) = symbol_visitor.mark_live_symbols() {
889            return Err(guar);
890        }
891
892        items_to_check.extend(unsolved_items.extract_if(.., |&mut local_def_id| {
893            symbol_visitor.check_impl_or_impl_item_live(local_def_id)
894        }));
895    }
896
897    Ok((symbol_visitor.live_symbols, symbol_visitor.ignored_derived_traits))
898}
899
900struct DeadItem {
901    def_id: LocalDefId,
902    name: Symbol,
903    level: (lint::Level, Option<LintExpectationId>),
904}
905
906struct DeadVisitor<'tcx> {
907    tcx: TyCtxt<'tcx>,
908    live_symbols: &'tcx LocalDefIdSet,
909    ignored_derived_traits: &'tcx LocalDefIdMap<FxIndexSet<DefId>>,
910}
911
912enum ShouldWarnAboutField {
913    Yes,
914    No,
915}
916
917#[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)]
918enum ReportOn {
919    /// Report on something that hasn't got a proper name to refer to
920    TupleField,
921    /// Report on something that has got a name, which could be a field but also a method
922    NamedField,
923}
924
925impl<'tcx> DeadVisitor<'tcx> {
926    fn should_warn_about_field(&mut self, field: &ty::FieldDef) -> ShouldWarnAboutField {
927        if self.live_symbols.contains(&field.did.expect_local()) {
928            return ShouldWarnAboutField::No;
929        }
930        let field_type = self.tcx.type_of(field.did).instantiate_identity();
931        if field_type.is_phantom_data() {
932            return ShouldWarnAboutField::No;
933        }
934        let is_positional = field.name.as_str().starts_with(|c: char| c.is_ascii_digit());
935        if is_positional
936            && self
937                .tcx
938                .layout_of(
939                    ty::TypingEnv::non_body_analysis(self.tcx, field.did)
940                        .as_query_input(field_type),
941                )
942                .map_or(true, |layout| layout.is_zst())
943        {
944            return ShouldWarnAboutField::No;
945        }
946        ShouldWarnAboutField::Yes
947    }
948
949    fn def_lint_level(&self, id: LocalDefId) -> (lint::Level, Option<LintExpectationId>) {
950        let hir_id = self.tcx.local_def_id_to_hir_id(id);
951        let level = self.tcx.lint_level_at_node(DEAD_CODE, hir_id);
952        (level.level, level.lint_id)
953    }
954
955    // # Panics
956    // All `dead_codes` must have the same lint level, otherwise we will intentionally ICE.
957    // This is because we emit a multi-spanned lint using the lint level of the `dead_codes`'s
958    // first local def id.
959    // Prefer calling `Self.warn_dead_code` or `Self.warn_dead_code_grouped_by_lint_level`
960    // since those methods group by lint level before calling this method.
961    fn lint_at_single_level(
962        &self,
963        dead_codes: &[&DeadItem],
964        participle: &str,
965        parent_item: Option<LocalDefId>,
966        report_on: ReportOn,
967    ) {
968        let Some(&first_item) = dead_codes.first() else { return };
969        let tcx = self.tcx;
970
971        let first_lint_level = first_item.level;
972        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));
973
974        let names: Vec<_> = dead_codes.iter().map(|item| item.name).collect();
975        let spans: Vec<_> = dead_codes
976            .iter()
977            .map(|item| {
978                let span = tcx.def_span(item.def_id);
979                let ident_span = tcx.def_ident_span(item.def_id);
980                // FIXME(cjgillot) this SyntaxContext manipulation does not make any sense.
981                ident_span.map(|s| s.with_ctxt(span.ctxt())).unwrap_or(span)
982            })
983            .collect();
984
985        let mut descr = tcx.def_descr(first_item.def_id.to_def_id());
986        // `impl` blocks are "batched" and (unlike other batching) might
987        // contain different kinds of associated items.
988        if dead_codes.iter().any(|item| tcx.def_descr(item.def_id.to_def_id()) != descr) {
989            descr = "associated item"
990        }
991
992        let num = dead_codes.len();
993        let multiple = num > 6;
994        let name_list = names.into();
995
996        let parent_info = parent_item.map(|parent_item| {
997            let parent_descr = tcx.def_descr(parent_item.to_def_id());
998            let span = if let DefKind::Impl { .. } = tcx.def_kind(parent_item) {
999                tcx.def_span(parent_item)
1000            } else {
1001                tcx.def_ident_span(parent_item).unwrap()
1002            };
1003            ParentInfo { num, descr, parent_descr, span }
1004        });
1005
1006        let mut encl_def_id = parent_item.unwrap_or(first_item.def_id);
1007        // `ignored_derived_traits` is computed for the enum, not for the variants.
1008        if let DefKind::Variant = tcx.def_kind(encl_def_id) {
1009            encl_def_id = tcx.local_parent(encl_def_id);
1010        }
1011
1012        let ignored_derived_impls =
1013            self.ignored_derived_traits.get(&encl_def_id).map(|ign_traits| {
1014                let trait_list = ign_traits
1015                    .iter()
1016                    .map(|trait_id| self.tcx.item_name(*trait_id))
1017                    .collect::<Vec<_>>();
1018                let trait_list_len = trait_list.len();
1019                IgnoredDerivedImpls {
1020                    name: self.tcx.item_name(encl_def_id.to_def_id()),
1021                    trait_list: trait_list.into(),
1022                    trait_list_len,
1023                }
1024            });
1025
1026        let diag = match report_on {
1027            ReportOn::TupleField => {
1028                let tuple_fields = if let Some(parent_id) = parent_item
1029                    && let node = tcx.hir_node_by_def_id(parent_id)
1030                    && let hir::Node::Item(hir::Item {
1031                        kind: hir::ItemKind::Struct(_, _, hir::VariantData::Tuple(fields, _, _)),
1032                        ..
1033                    }) = node
1034                {
1035                    *fields
1036                } else {
1037                    &[]
1038                };
1039
1040                let trailing_tuple_fields = if tuple_fields.len() >= dead_codes.len() {
1041                    LocalDefIdSet::from_iter(
1042                        tuple_fields
1043                            .iter()
1044                            .skip(tuple_fields.len() - dead_codes.len())
1045                            .map(|f| f.def_id),
1046                    )
1047                } else {
1048                    LocalDefIdSet::default()
1049                };
1050
1051                let fields_suggestion =
1052                    // Suggest removal if all tuple fields are at the end.
1053                    // Otherwise suggest removal or changing to unit type
1054                    if dead_codes.iter().all(|dc| trailing_tuple_fields.contains(&dc.def_id)) {
1055                        ChangeFields::Remove { num }
1056                    } else {
1057                        ChangeFields::ChangeToUnitTypeOrRemove { num, spans: spans.clone() }
1058                    };
1059
1060                MultipleDeadCodes::UnusedTupleStructFields {
1061                    multiple,
1062                    num,
1063                    descr,
1064                    participle,
1065                    name_list,
1066                    change_fields_suggestion: fields_suggestion,
1067                    parent_info,
1068                    ignored_derived_impls,
1069                }
1070            }
1071            ReportOn::NamedField => {
1072                let enum_variants_with_same_name = dead_codes
1073                    .iter()
1074                    .filter_map(|dead_item| {
1075                        if let DefKind::AssocFn | DefKind::AssocConst { .. } =
1076                            tcx.def_kind(dead_item.def_id)
1077                            && let impl_did = tcx.local_parent(dead_item.def_id)
1078                            && let DefKind::Impl { of_trait: false } = tcx.def_kind(impl_did)
1079                            && let ty::Adt(maybe_enum, _) =
1080                                tcx.type_of(impl_did).instantiate_identity().kind()
1081                            && maybe_enum.is_enum()
1082                            && let Some(variant) =
1083                                maybe_enum.variants().iter().find(|i| i.name == dead_item.name)
1084                        {
1085                            Some(crate::errors::EnumVariantSameName {
1086                                dead_descr: tcx.def_descr(dead_item.def_id.to_def_id()),
1087                                dead_name: dead_item.name,
1088                                variant_span: tcx.def_span(variant.def_id),
1089                            })
1090                        } else {
1091                            None
1092                        }
1093                    })
1094                    .collect();
1095
1096                MultipleDeadCodes::DeadCodes {
1097                    multiple,
1098                    num,
1099                    descr,
1100                    participle,
1101                    name_list,
1102                    parent_info,
1103                    ignored_derived_impls,
1104                    enum_variants_with_same_name,
1105                }
1106            }
1107        };
1108
1109        let hir_id = tcx.local_def_id_to_hir_id(first_item.def_id);
1110        self.tcx.emit_node_span_lint(DEAD_CODE, hir_id, MultiSpan::from_spans(spans), diag);
1111    }
1112
1113    fn warn_multiple(
1114        &self,
1115        def_id: LocalDefId,
1116        participle: &str,
1117        dead_codes: Vec<DeadItem>,
1118        report_on: ReportOn,
1119    ) {
1120        let mut dead_codes = dead_codes
1121            .iter()
1122            .filter(|v| !v.name.as_str().starts_with('_'))
1123            .collect::<Vec<&DeadItem>>();
1124        if dead_codes.is_empty() {
1125            return;
1126        }
1127        // FIXME: `dead_codes` should probably be morally equivalent to `IndexMap<(Level, LintExpectationId), (DefId, Symbol)>`
1128        dead_codes.sort_by_key(|v| v.level.0);
1129        for group in dead_codes.chunk_by(|a, b| a.level == b.level) {
1130            self.lint_at_single_level(&group, participle, Some(def_id), report_on);
1131        }
1132    }
1133
1134    fn warn_dead_code(&mut self, id: LocalDefId, participle: &str) {
1135        let item = DeadItem {
1136            def_id: id,
1137            name: self.tcx.item_name(id.to_def_id()),
1138            level: self.def_lint_level(id),
1139        };
1140        self.lint_at_single_level(&[&item], participle, None, ReportOn::NamedField);
1141    }
1142
1143    fn check_definition(&mut self, def_id: LocalDefId) {
1144        if self.is_live_code(def_id) {
1145            return;
1146        }
1147        match self.tcx.def_kind(def_id) {
1148            DefKind::AssocConst { .. }
1149            | DefKind::AssocTy
1150            | DefKind::AssocFn
1151            | DefKind::Fn
1152            | DefKind::Static { .. }
1153            | DefKind::Const { .. }
1154            | DefKind::TyAlias
1155            | DefKind::Enum
1156            | DefKind::Union
1157            | DefKind::ForeignTy
1158            | DefKind::Trait => self.warn_dead_code(def_id, "used"),
1159            DefKind::Struct => self.warn_dead_code(def_id, "constructed"),
1160            DefKind::Variant | DefKind::Field => ::rustc_middle::util::bug::bug_fmt(format_args!("should be handled specially"))bug!("should be handled specially"),
1161            _ => {}
1162        }
1163    }
1164
1165    fn is_live_code(&self, def_id: LocalDefId) -> bool {
1166        // if we cannot get a name for the item, then we just assume that it is
1167        // live. I mean, we can't really emit a lint.
1168        let Some(name) = self.tcx.opt_item_name(def_id.to_def_id()) else {
1169            return true;
1170        };
1171
1172        self.live_symbols.contains(&def_id) || name.as_str().starts_with('_')
1173    }
1174}
1175
1176fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalModDefId) {
1177    let Ok((live_symbols, ignored_derived_traits)) =
1178        tcx.live_symbols_and_ignored_derived_traits(()).as_ref()
1179    else {
1180        return;
1181    };
1182
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        // Only diagnose unused assoc items in inherent impl and used trait,
1192        // for unused assoc items in impls of trait,
1193        // we have diagnosed them in the trait if they are unused,
1194        // for unused assoc items in unused trait,
1195        // we have diagnosed the unused trait.
1196        if def_kind == (DefKind::Impl { of_trait: false })
1197            || (def_kind == DefKind::Trait && live_symbols.contains(&item.owner_id.def_id))
1198        {
1199            for &def_id in tcx.associated_item_def_ids(item.owner_id.def_id) {
1200                if let Some(local_def_id) = def_id.as_local()
1201                    && !visitor.is_live_code(local_def_id)
1202                {
1203                    let name = tcx.item_name(def_id);
1204                    let level = visitor.def_lint_level(local_def_id);
1205                    dead_codes.push(DeadItem { def_id: local_def_id, name, level });
1206                }
1207            }
1208        }
1209        if !dead_codes.is_empty() {
1210            visitor.warn_multiple(item.owner_id.def_id, "used", dead_codes, ReportOn::NamedField);
1211        }
1212
1213        if !live_symbols.contains(&item.owner_id.def_id) {
1214            let parent = tcx.local_parent(item.owner_id.def_id);
1215            if parent != module.to_local_def_id() && !live_symbols.contains(&parent) {
1216                // We already have diagnosed something.
1217                continue;
1218            }
1219            visitor.check_definition(item.owner_id.def_id);
1220            continue;
1221        }
1222
1223        if let DefKind::Struct | DefKind::Union | DefKind::Enum = def_kind {
1224            let adt = tcx.adt_def(item.owner_id);
1225            let mut dead_variants = Vec::new();
1226
1227            for variant in adt.variants() {
1228                let def_id = variant.def_id.expect_local();
1229                if !live_symbols.contains(&def_id) {
1230                    // Record to group diagnostics.
1231                    let level = visitor.def_lint_level(def_id);
1232                    dead_variants.push(DeadItem { def_id, name: variant.name, level });
1233                    continue;
1234                }
1235
1236                let is_positional = variant.fields.raw.first().is_some_and(|field| {
1237                    field.name.as_str().starts_with(|c: char| c.is_ascii_digit())
1238                });
1239                let report_on =
1240                    if is_positional { ReportOn::TupleField } else { ReportOn::NamedField };
1241                let dead_fields = variant
1242                    .fields
1243                    .iter()
1244                    .filter_map(|field| {
1245                        let def_id = field.did.expect_local();
1246                        if let ShouldWarnAboutField::Yes = visitor.should_warn_about_field(field) {
1247                            let level = visitor.def_lint_level(def_id);
1248                            Some(DeadItem { def_id, name: field.name, level })
1249                        } else {
1250                            None
1251                        }
1252                    })
1253                    .collect();
1254                visitor.warn_multiple(def_id, "read", dead_fields, report_on);
1255            }
1256
1257            visitor.warn_multiple(
1258                item.owner_id.def_id,
1259                "constructed",
1260                dead_variants,
1261                ReportOn::NamedField,
1262            );
1263        }
1264    }
1265
1266    for foreign_item in module_items.foreign_items() {
1267        visitor.check_definition(foreign_item.owner_id.def_id);
1268    }
1269}
1270
1271pub(crate) fn provide(providers: &mut Providers) {
1272    *providers =
1273        Providers { live_symbols_and_ignored_derived_traits, check_mod_deathness, ..*providers };
1274}