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 {
    #[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 | DefKind::AssocConst | DefKind::AssocTy | DefKind::TyAlias,
124                def_id,
125            ) => {
126                self.check_def_id(def_id);
127            }
128            Res::PrimTy(..) | Res::SelfCtor(..) | Res::Local(..) => {}
129            Res::Def(DefKind::Ctor(CtorOf::Variant, ..), ctor_def_id) => {
130                // Using a variant in patterns should not make the variant live,
131                // since we can just remove the match arm that matches the pattern
132                if self.in_pat {
133                    return;
134                }
135                let variant_id = self.tcx.parent(ctor_def_id);
136                let enum_id = self.tcx.parent(variant_id);
137                self.check_def_id(enum_id);
138                if !self.ignore_variant_stack.contains(&ctor_def_id) {
139                    self.check_def_id(variant_id);
140                }
141            }
142            Res::Def(DefKind::Variant, variant_id) => {
143                // Using a variant in patterns should not make the variant live,
144                // since we can just remove the match arm that matches the pattern
145                if self.in_pat {
146                    return;
147                }
148                let enum_id = self.tcx.parent(variant_id);
149                self.check_def_id(enum_id);
150                if !self.ignore_variant_stack.contains(&variant_id) {
151                    self.check_def_id(variant_id);
152                }
153            }
154            Res::Def(_, def_id) => self.check_def_id(def_id),
155            Res::SelfTyParam { trait_: t } => self.check_def_id(t),
156            Res::SelfTyAlias { alias_to: i, .. } => self.check_def_id(i),
157            Res::ToolMod | Res::NonMacroAttr(..) | Res::Err => {}
158        }
159    }
160
161    fn lookup_and_handle_method(&mut self, id: hir::HirId) {
162        if let Some(def_id) = self.typeck_results().type_dependent_def_id(id) {
163            self.check_def_id(def_id);
164        } else {
165            if !self.typeck_results().tainted_by_errors.is_some() {
    {
        ::core::panicking::panic_fmt(format_args!("no type-dependent def for method"));
    }
};assert!(
166                self.typeck_results().tainted_by_errors.is_some(),
167                "no type-dependent def for method"
168            );
169        }
170    }
171
172    fn handle_field_access(&mut self, lhs: &hir::Expr<'_>, hir_id: hir::HirId) {
173        match self.typeck_results().expr_ty_adjusted(lhs).kind() {
174            ty::Adt(def, _) => {
175                let index = self.typeck_results().field_index(hir_id);
176                self.insert_def_id(def.non_enum_variant().fields[index].did);
177            }
178            ty::Tuple(..) => {}
179            ty::Error(_) => {}
180            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:?}"),
181        }
182    }
183
184    fn handle_assign(&mut self, expr: &'tcx hir::Expr<'tcx>) {
185        if self
186            .typeck_results()
187            .expr_adjustments(expr)
188            .iter()
189            .any(|adj| #[allow(non_exhaustive_omitted_patterns)] match adj.kind {
    ty::adjustment::Adjust::Deref(_) => true,
    _ => false,
}matches!(adj.kind, ty::adjustment::Adjust::Deref(_)))
190        {
191            let _ = self.visit_expr(expr);
192        } else if let hir::ExprKind::Field(base, ..) = expr.kind {
193            // Ignore write to field
194            self.handle_assign(base);
195        } else {
196            let _ = self.visit_expr(expr);
197        }
198    }
199
200    fn check_for_self_assign(&mut self, assign: &'tcx hir::Expr<'tcx>) {
201        fn check_for_self_assign_helper<'tcx>(
202            typeck_results: &'tcx ty::TypeckResults<'tcx>,
203            lhs: &'tcx hir::Expr<'tcx>,
204            rhs: &'tcx hir::Expr<'tcx>,
205        ) -> bool {
206            match (&lhs.kind, &rhs.kind) {
207                (hir::ExprKind::Path(qpath_l), hir::ExprKind::Path(qpath_r)) => {
208                    if let (Res::Local(id_l), Res::Local(id_r)) = (
209                        typeck_results.qpath_res(qpath_l, lhs.hir_id),
210                        typeck_results.qpath_res(qpath_r, rhs.hir_id),
211                    ) {
212                        if id_l == id_r {
213                            return true;
214                        }
215                    }
216                    return false;
217                }
218                (hir::ExprKind::Field(lhs_l, ident_l), hir::ExprKind::Field(lhs_r, ident_r)) => {
219                    if ident_l == ident_r {
220                        return check_for_self_assign_helper(typeck_results, lhs_l, lhs_r);
221                    }
222                    return false;
223                }
224                _ => {
225                    return false;
226                }
227            }
228        }
229
230        if let hir::ExprKind::Assign(lhs, rhs, _) = assign.kind
231            && check_for_self_assign_helper(self.typeck_results(), lhs, rhs)
232            && !assign.span.from_expansion()
233        {
234            let is_field_assign = #[allow(non_exhaustive_omitted_patterns)] match lhs.kind {
    hir::ExprKind::Field(..) => true,
    _ => false,
}matches!(lhs.kind, hir::ExprKind::Field(..));
235            self.tcx.emit_node_span_lint(
236                lint::builtin::DEAD_CODE,
237                assign.hir_id,
238                assign.span,
239                UselessAssignment { is_field_assign, ty: self.typeck_results().expr_ty(lhs) },
240            )
241        }
242    }
243
244    fn handle_field_pattern_match(
245        &mut self,
246        lhs: &hir::Pat<'_>,
247        res: Res,
248        pats: &[hir::PatField<'_>],
249    ) {
250        let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
251            ty::Adt(adt, _) => {
252                // Marks the ADT live if its variant appears as the pattern,
253                // considering cases when we have `let T(x) = foo()` and `fn foo<T>() -> T;`,
254                // we will lose the liveness info of `T` cause we cannot mark it live when visiting `foo`.
255                // Related issue: https://github.com/rust-lang/rust/issues/120770
256                self.check_def_id(adt.did());
257                adt.variant_of_res(res)
258            }
259            _ => ::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"),
260        };
261        for pat in pats {
262            if let PatKind::Wild = pat.pat.kind {
263                continue;
264            }
265            let index = self.typeck_results().field_index(pat.hir_id);
266            self.insert_def_id(variant.fields[index].did);
267        }
268    }
269
270    fn handle_tuple_field_pattern_match(
271        &mut self,
272        lhs: &hir::Pat<'_>,
273        res: Res,
274        pats: &[hir::Pat<'_>],
275        dotdot: hir::DotDotPos,
276    ) {
277        let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
278            ty::Adt(adt, _) => {
279                // Marks the ADT live if its variant appears as the pattern
280                self.check_def_id(adt.did());
281                adt.variant_of_res(res)
282            }
283            _ => {
284                self.tcx.dcx().span_delayed_bug(lhs.span, "non-ADT in tuple struct pattern");
285                return;
286            }
287        };
288        let dotdot = dotdot.as_opt_usize().unwrap_or(pats.len());
289        let first_n = pats.iter().enumerate().take(dotdot);
290        let missing = variant.fields.len() - pats.len();
291        let last_n = pats.iter().enumerate().skip(dotdot).map(|(idx, pat)| (idx + missing, pat));
292        for (idx, pat) in first_n.chain(last_n) {
293            if let PatKind::Wild = pat.kind {
294                continue;
295            }
296            self.insert_def_id(variant.fields[FieldIdx::from_usize(idx)].did);
297        }
298    }
299
300    fn handle_offset_of(&mut self, expr: &'tcx hir::Expr<'tcx>) {
301        let indices = self
302            .typeck_results()
303            .offset_of_data()
304            .get(expr.hir_id)
305            .expect("no offset_of_data for offset_of");
306
307        for &(current_ty, variant, field) in indices {
308            match current_ty.kind() {
309                ty::Adt(def, _) => {
310                    let field = &def.variant(variant).fields[field];
311                    self.insert_def_id(field.did);
312                }
313                // we don't need to mark tuple fields as live,
314                // but we may need to mark subfields
315                ty::Tuple(_) => {}
316                _ => ::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"),
317            }
318        }
319    }
320
321    fn mark_live_symbols(&mut self) -> <MarkSymbolVisitor<'tcx> as Visitor<'tcx>>::Result {
322        while let Some(work) = self.worklist.pop() {
323            let (mut id, comes_from_allow_expect) = work;
324
325            // in the case of tuple struct constructors we want to check the item,
326            // not the generated tuple struct constructor function
327            if let DefKind::Ctor(..) = self.tcx.def_kind(id) {
328                id = self.tcx.local_parent(id);
329            }
330
331            // When using `#[allow]` or `#[expect]` of `dead_code`, we do a QOL improvement
332            // by declaring fn calls, statics, ... within said items as live, as well as
333            // the item itself, although technically this is not the case.
334            //
335            // This means that the lint for said items will never be fired.
336            //
337            // This doesn't make any difference for the item declared with `#[allow]`, as
338            // the lint firing will be a nop, as it will be silenced by the `#[allow]` of
339            // the item.
340            //
341            // However, for `#[expect]`, the presence or absence of the lint is relevant,
342            // so we don't add it to the list of live symbols when it comes from a
343            // `#[expect]`. This means that we will correctly report an item as live or not
344            // for the `#[expect]` case.
345            //
346            // Note that an item can and will be duplicated on the worklist with different
347            // `ComesFromAllowExpect`, particularly if it was added from the
348            // `effective_visibilities` query or from the `#[allow]`/`#[expect]` checks,
349            // this "duplication" is essential as otherwise a function with `#[expect]`
350            // called from a `pub fn` may be falsely reported as not live, falsely
351            // triggering the `unfulfilled_lint_expectations` lint.
352            match comes_from_allow_expect {
353                ComesFromAllowExpect::Yes => {}
354                ComesFromAllowExpect::No => {
355                    self.live_symbols.insert(id);
356                }
357            }
358
359            if !self.scanned.insert(id) {
360                continue;
361            }
362
363            // Avoid accessing the HIR for the synthesized associated type generated for RPITITs.
364            if self.tcx.is_impl_trait_in_trait(id.to_def_id()) {
365                self.live_symbols.insert(id);
366                continue;
367            }
368
369            self.visit_node(self.tcx.hir_node_by_def_id(id))?;
370        }
371
372        ControlFlow::Continue(())
373    }
374
375    /// Automatically generated items marked with `rustc_trivial_field_reads`
376    /// will be ignored for the purposes of dead code analysis (see PR #85200
377    /// for discussion).
378    fn should_ignore_impl_item(&mut self, impl_item: &hir::ImplItem<'_>) -> bool {
379        if let hir::ImplItemImplKind::Trait { .. } = impl_item.impl_kind
380            && let impl_of = self.tcx.parent(impl_item.owner_id.to_def_id())
381            && self.tcx.is_automatically_derived(impl_of)
382            && let trait_ref = self.tcx.impl_trait_ref(impl_of).instantiate_identity()
383            && {

        #[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)
384        {
385            if let ty::Adt(adt_def, _) = trait_ref.self_ty().kind()
386                && let Some(adt_def_id) = adt_def.did().as_local()
387            {
388                self.ignored_derived_traits.entry(adt_def_id).or_default().insert(trait_ref.def_id);
389            }
390            return true;
391        }
392
393        false
394    }
395
396    fn visit_node(
397        &mut self,
398        node: Node<'tcx>,
399    ) -> <MarkSymbolVisitor<'tcx> as Visitor<'tcx>>::Result {
400        if let Node::ImplItem(impl_item) = node
401            && self.should_ignore_impl_item(impl_item)
402        {
403            return ControlFlow::Continue(());
404        }
405
406        let unconditionally_treated_fields_as_live =
407            self.repr_unconditionally_treats_fields_as_live;
408        let had_repr_simd = self.repr_has_repr_simd;
409        self.repr_unconditionally_treats_fields_as_live = false;
410        self.repr_has_repr_simd = false;
411        let walk_result = match node {
412            Node::Item(item) => match item.kind {
413                hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
414                    let def = self.tcx.adt_def(item.owner_id);
415                    self.repr_unconditionally_treats_fields_as_live =
416                        def.repr().c() || def.repr().transparent();
417                    self.repr_has_repr_simd = def.repr().simd();
418
419                    intravisit::walk_item(self, item)
420                }
421                hir::ItemKind::ForeignMod { .. } => ControlFlow::Continue(()),
422                hir::ItemKind::Trait(.., trait_item_refs) => {
423                    // mark assoc ty live if the trait is live
424                    for trait_item in trait_item_refs {
425                        if self.tcx.def_kind(trait_item.owner_id) == DefKind::AssocTy {
426                            self.check_def_id(trait_item.owner_id.to_def_id());
427                        }
428                    }
429                    intravisit::walk_item(self, item)
430                }
431                _ => intravisit::walk_item(self, item),
432            },
433            Node::TraitItem(trait_item) => {
434                // mark the trait live
435                let trait_item_id = trait_item.owner_id.to_def_id();
436                if let Some(trait_id) = self.tcx.trait_of_assoc(trait_item_id) {
437                    self.check_def_id(trait_id);
438                }
439                intravisit::walk_trait_item(self, trait_item)
440            }
441            Node::ImplItem(impl_item) => {
442                let item = self.tcx.local_parent(impl_item.owner_id.def_id);
443                if let hir::ImplItemImplKind::Inherent { .. } = impl_item.impl_kind {
444                    //// If it's a type whose items are live, then it's live, too.
445                    //// This is done to handle the case where, for example, the static
446                    //// method of a private type is used, but the type itself is never
447                    //// called directly.
448                    let self_ty = self.tcx.type_of(item).instantiate_identity();
449                    match *self_ty.kind() {
450                        ty::Adt(def, _) => self.check_def_id(def.did()),
451                        ty::Foreign(did) => self.check_def_id(did),
452                        ty::Dynamic(data, ..) => {
453                            if let Some(def_id) = data.principal_def_id() {
454                                self.check_def_id(def_id)
455                            }
456                        }
457                        _ => {}
458                    }
459                }
460                intravisit::walk_impl_item(self, impl_item)
461            }
462            Node::ForeignItem(foreign_item) => intravisit::walk_foreign_item(self, foreign_item),
463            Node::OpaqueTy(opaq) => intravisit::walk_opaque_ty(self, opaq),
464            _ => ControlFlow::Continue(()),
465        };
466        self.repr_has_repr_simd = had_repr_simd;
467        self.repr_unconditionally_treats_fields_as_live = unconditionally_treated_fields_as_live;
468
469        walk_result
470    }
471
472    fn mark_as_used_if_union(&mut self, adt: ty::AdtDef<'tcx>, fields: &[hir::ExprField<'_>]) {
473        if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did().is_local() {
474            for field in fields {
475                let index = self.typeck_results().field_index(field.hir_id);
476                self.insert_def_id(adt.non_enum_variant().fields[index].did);
477            }
478        }
479    }
480
481    /// Returns whether `local_def_id` is potentially alive or not.
482    /// `local_def_id` points to an impl or an impl item,
483    /// both impl and impl item that may be passed to this function are of a trait,
484    /// and added into the unsolved_items during `create_and_seed_worklist`
485    fn check_impl_or_impl_item_live(&mut self, local_def_id: LocalDefId) -> bool {
486        let (impl_block_id, trait_def_id) = match self.tcx.def_kind(local_def_id) {
487            // assoc impl items of traits are live if the corresponding trait items are live
488            DefKind::AssocConst | DefKind::AssocTy | DefKind::AssocFn => {
489                let trait_item_id =
490                    self.tcx.trait_item_of(local_def_id).and_then(|def_id| def_id.as_local());
491                (self.tcx.local_parent(local_def_id), trait_item_id)
492            }
493            // impl items are live if the corresponding traits are live
494            DefKind::Impl { of_trait: true } => {
495                (local_def_id, self.tcx.impl_trait_id(local_def_id).as_local())
496            }
497            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
498        };
499
500        if let Some(trait_def_id) = trait_def_id
501            && !self.live_symbols.contains(&trait_def_id)
502        {
503            return false;
504        }
505
506        // The impl or impl item is used if the corresponding trait or trait item is used and the ty is used.
507        if let ty::Adt(adt, _) = self.tcx.type_of(impl_block_id).instantiate_identity().kind()
508            && let Some(adt_def_id) = adt.did().as_local()
509            && !self.live_symbols.contains(&adt_def_id)
510        {
511            return false;
512        }
513
514        true
515    }
516}
517
518impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
519    type Result = ControlFlow<ErrorGuaranteed>;
520
521    fn visit_nested_body(&mut self, body: hir::BodyId) -> Self::Result {
522        let typeck_results = self.tcx.typeck_body(body);
523
524        // The result shouldn't be tainted, otherwise it will cause ICE.
525        if let Some(guar) = typeck_results.tainted_by_errors {
526            return ControlFlow::Break(guar);
527        }
528
529        let old_maybe_typeck_results = self.maybe_typeck_results.replace(typeck_results);
530        let body = self.tcx.hir_body(body);
531        let result = self.visit_body(body);
532        self.maybe_typeck_results = old_maybe_typeck_results;
533
534        result
535    }
536
537    fn visit_variant_data(&mut self, def: &'tcx hir::VariantData<'tcx>) -> Self::Result {
538        let tcx = self.tcx;
539        let unconditionally_treat_fields_as_live = self.repr_unconditionally_treats_fields_as_live;
540        let has_repr_simd = self.repr_has_repr_simd;
541        let effective_visibilities = &tcx.effective_visibilities(());
542        let live_fields = def.fields().iter().filter_map(|f| {
543            let def_id = f.def_id;
544            if unconditionally_treat_fields_as_live || (f.is_positional() && has_repr_simd) {
545                return Some(def_id);
546            }
547            if !effective_visibilities.is_reachable(f.hir_id.owner.def_id) {
548                return None;
549            }
550            if effective_visibilities.is_reachable(def_id) { Some(def_id) } else { None }
551        });
552        self.live_symbols.extend(live_fields);
553
554        intravisit::walk_struct_def(self, def)
555    }
556
557    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) -> Self::Result {
558        match expr.kind {
559            hir::ExprKind::Path(ref qpath @ QPath::TypeRelative(..)) => {
560                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
561                self.handle_res(res);
562            }
563            hir::ExprKind::MethodCall(..) => {
564                self.lookup_and_handle_method(expr.hir_id);
565            }
566            hir::ExprKind::Field(ref lhs, ..) => {
567                if self.typeck_results().opt_field_index(expr.hir_id).is_some() {
568                    self.handle_field_access(lhs, expr.hir_id);
569                } else {
570                    self.tcx.dcx().span_delayed_bug(expr.span, "couldn't resolve index for field");
571                }
572            }
573            hir::ExprKind::Struct(qpath, fields, _) => {
574                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
575                self.handle_res(res);
576                if let ty::Adt(adt, _) = self.typeck_results().expr_ty(expr).kind() {
577                    self.mark_as_used_if_union(*adt, fields);
578                }
579            }
580            hir::ExprKind::Closure(cls) => {
581                self.insert_def_id(cls.def_id.to_def_id());
582            }
583            hir::ExprKind::OffsetOf(..) => {
584                self.handle_offset_of(expr);
585            }
586            hir::ExprKind::Assign(ref lhs, ..) => {
587                self.handle_assign(lhs);
588                self.check_for_self_assign(expr);
589            }
590            _ => (),
591        }
592
593        intravisit::walk_expr(self, expr)
594    }
595
596    fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) -> Self::Result {
597        // Inside the body, ignore constructions of variants
598        // necessary for the pattern to match. Those construction sites
599        // can't be reached unless the variant is constructed elsewhere.
600        let len = self.ignore_variant_stack.len();
601        self.ignore_variant_stack.extend(arm.pat.necessary_variants());
602        let result = intravisit::walk_arm(self, arm);
603        self.ignore_variant_stack.truncate(len);
604
605        result
606    }
607
608    fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Self::Result {
609        self.in_pat = true;
610        match pat.kind {
611            PatKind::Struct(ref path, fields, _) => {
612                let res = self.typeck_results().qpath_res(path, pat.hir_id);
613                self.handle_field_pattern_match(pat, res, fields);
614            }
615            PatKind::TupleStruct(ref qpath, fields, dotdot) => {
616                let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
617                self.handle_tuple_field_pattern_match(pat, res, fields, dotdot);
618            }
619            _ => (),
620        }
621
622        let result = intravisit::walk_pat(self, pat);
623        self.in_pat = false;
624
625        result
626    }
627
628    fn visit_pat_expr(&mut self, expr: &'tcx rustc_hir::PatExpr<'tcx>) -> Self::Result {
629        match &expr.kind {
630            rustc_hir::PatExprKind::Path(qpath) => {
631                // mark the type of variant live when meeting E::V in expr
632                if let ty::Adt(adt, _) = self.typeck_results().node_type(expr.hir_id).kind() {
633                    self.check_def_id(adt.did());
634                }
635
636                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
637                self.handle_res(res);
638            }
639            _ => {}
640        }
641        intravisit::walk_pat_expr(self, expr)
642    }
643
644    fn visit_path(&mut self, path: &hir::Path<'tcx>, _: hir::HirId) -> Self::Result {
645        self.handle_res(path.res);
646        intravisit::walk_path(self, path)
647    }
648
649    fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) -> Self::Result {
650        // When inline const blocks are used in pattern position, paths
651        // referenced by it should be considered as used.
652        let in_pat = mem::replace(&mut self.in_pat, false);
653
654        self.live_symbols.insert(c.def_id);
655        let result = intravisit::walk_anon_const(self, c);
656
657        self.in_pat = in_pat;
658
659        result
660    }
661
662    fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) -> Self::Result {
663        // When inline const blocks are used in pattern position, paths
664        // referenced by it should be considered as used.
665        let in_pat = mem::replace(&mut self.in_pat, false);
666
667        self.live_symbols.insert(c.def_id);
668        let result = intravisit::walk_inline_const(self, c);
669
670        self.in_pat = in_pat;
671
672        result
673    }
674
675    fn visit_trait_ref(&mut self, t: &'tcx hir::TraitRef<'tcx>) -> Self::Result {
676        if let Some(trait_def_id) = t.path.res.opt_def_id()
677            && let Some(segment) = t.path.segments.last()
678            && let Some(args) = segment.args
679        {
680            for constraint in args.constraints {
681                if let Some(local_def_id) = self
682                    .tcx
683                    .associated_items(trait_def_id)
684                    .find_by_ident_and_kind(
685                        self.tcx,
686                        constraint.ident,
687                        AssocTag::Const,
688                        trait_def_id,
689                    )
690                    .and_then(|item| item.def_id.as_local())
691                {
692                    self.worklist.push((local_def_id, ComesFromAllowExpect::No));
693                }
694            }
695        }
696
697        intravisit::walk_trait_ref(self, t)
698    }
699}
700
701fn has_allow_dead_code_or_lang_attr(
702    tcx: TyCtxt<'_>,
703    def_id: LocalDefId,
704) -> Option<ComesFromAllowExpect> {
705    fn has_allow_expect_dead_code(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
706        let hir_id = tcx.local_def_id_to_hir_id(def_id);
707        let lint_level = tcx.lint_level_at_node(lint::builtin::DEAD_CODE, hir_id).level;
708        #[allow(non_exhaustive_omitted_patterns)] match lint_level {
    lint::Allow | lint::Expect => true,
    _ => false,
}matches!(lint_level, lint::Allow | lint::Expect)
709    }
710
711    fn has_used_like_attr(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
712        tcx.def_kind(def_id).has_codegen_attrs() && {
713            let cg_attrs = tcx.codegen_fn_attrs(def_id);
714
715            // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
716            // forcefully, e.g., for placing it in a specific section.
717            cg_attrs.contains_extern_indicator()
718                || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)
719                || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)
720        }
721    }
722
723    if has_allow_expect_dead_code(tcx, def_id) {
724        Some(ComesFromAllowExpect::Yes)
725    } 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(..)) {
726        Some(ComesFromAllowExpect::No)
727    } else {
728        None
729    }
730}
731
732/// Examine the given definition and record it in the worklist if it should be considered live.
733///
734/// We want to explicitly consider as live:
735/// * Item annotated with #[allow(dead_code)]
736///       This is done so that if we want to suppress warnings for a
737///       group of dead functions, we only have to annotate the "root".
738///       For example, if both `f` and `g` are dead and `f` calls `g`,
739///       then annotating `f` with `#[allow(dead_code)]` will suppress
740///       warning for both `f` and `g`.
741///
742/// * Item annotated with #[lang=".."]
743///       Lang items are always callable from elsewhere.
744///
745/// For trait methods and implementations of traits, we are not certain that the definitions are
746/// live at this stage. We record them in `unsolved_items` for later examination.
747fn maybe_record_as_seed<'tcx>(
748    tcx: TyCtxt<'tcx>,
749    owner_id: hir::OwnerId,
750    worklist: &mut Vec<(LocalDefId, ComesFromAllowExpect)>,
751    unsolved_items: &mut Vec<LocalDefId>,
752) {
753    let allow_dead_code = has_allow_dead_code_or_lang_attr(tcx, owner_id.def_id);
754    if let Some(comes_from_allow) = allow_dead_code {
755        worklist.push((owner_id.def_id, comes_from_allow));
756    }
757
758    match tcx.def_kind(owner_id) {
759        DefKind::Enum => {
760            if let Some(comes_from_allow) = allow_dead_code {
761                let adt = tcx.adt_def(owner_id);
762                worklist.extend(
763                    adt.variants()
764                        .iter()
765                        .map(|variant| (variant.def_id.expect_local(), comes_from_allow)),
766                );
767            }
768        }
769        DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy => {
770            if allow_dead_code.is_none() {
771                let parent = tcx.local_parent(owner_id.def_id);
772                match tcx.def_kind(parent) {
773                    DefKind::Impl { of_trait: false } | DefKind::Trait => {}
774                    DefKind::Impl { of_trait: true } => {
775                        if let Some(trait_item_def_id) =
776                            tcx.associated_item(owner_id.def_id).trait_item_def_id()
777                            && let Some(trait_item_local_def_id) = trait_item_def_id.as_local()
778                            && let Some(comes_from_allow) =
779                                has_allow_dead_code_or_lang_attr(tcx, trait_item_local_def_id)
780                        {
781                            worklist.push((owner_id.def_id, comes_from_allow));
782                        }
783
784                        // We only care about associated items of traits,
785                        // because they cannot be visited directly,
786                        // so we later mark them as live if their corresponding traits
787                        // or trait items and self types are both live,
788                        // but inherent associated items can be visited and marked directly.
789                        unsolved_items.push(owner_id.def_id);
790                    }
791                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
792                }
793            }
794        }
795        DefKind::Impl { of_trait: true } => {
796            if allow_dead_code.is_none() {
797                if let Some(trait_def_id) =
798                    tcx.impl_trait_ref(owner_id.def_id).skip_binder().def_id.as_local()
799                    && let Some(comes_from_allow) =
800                        has_allow_dead_code_or_lang_attr(tcx, trait_def_id)
801                {
802                    worklist.push((owner_id.def_id, comes_from_allow));
803                }
804
805                unsolved_items.push(owner_id.def_id);
806            }
807        }
808        DefKind::GlobalAsm => {
809            // global_asm! is always live.
810            worklist.push((owner_id.def_id, ComesFromAllowExpect::No));
811        }
812        DefKind::Const => {
813            if tcx.item_name(owner_id.def_id) == kw::Underscore {
814                // `const _` is always live, as that syntax only exists for the side effects
815                // of type checking and evaluating the constant expression, and marking them
816                // as dead code would defeat that purpose.
817                worklist.push((owner_id.def_id, ComesFromAllowExpect::No));
818            }
819        }
820        _ => {}
821    }
822}
823
824fn create_and_seed_worklist(
825    tcx: TyCtxt<'_>,
826) -> (Vec<(LocalDefId, ComesFromAllowExpect)>, Vec<LocalDefId>) {
827    let effective_visibilities = &tcx.effective_visibilities(());
828    let mut unsolved_impl_item = Vec::new();
829    let mut worklist = effective_visibilities
830        .iter()
831        .filter_map(|(&id, effective_vis)| {
832            effective_vis
833                .is_public_at_level(Level::Reachable)
834                .then_some(id)
835                .map(|id| (id, ComesFromAllowExpect::No))
836        })
837        // Seed entry point
838        .chain(
839            tcx.entry_fn(())
840                .and_then(|(def_id, _)| def_id.as_local().map(|id| (id, ComesFromAllowExpect::No))),
841        )
842        .collect::<Vec<_>>();
843
844    let crate_items = tcx.hir_crate_items(());
845    for id in crate_items.owners() {
846        maybe_record_as_seed(tcx, id, &mut worklist, &mut unsolved_impl_item);
847    }
848
849    (worklist, unsolved_impl_item)
850}
851
852fn live_symbols_and_ignored_derived_traits(
853    tcx: TyCtxt<'_>,
854    (): (),
855) -> Result<(LocalDefIdSet, LocalDefIdMap<FxIndexSet<DefId>>), ErrorGuaranteed> {
856    let (worklist, mut unsolved_items) = create_and_seed_worklist(tcx);
857    let mut symbol_visitor = MarkSymbolVisitor {
858        worklist,
859        tcx,
860        maybe_typeck_results: None,
861        scanned: Default::default(),
862        live_symbols: Default::default(),
863        repr_unconditionally_treats_fields_as_live: false,
864        repr_has_repr_simd: false,
865        in_pat: false,
866        ignore_variant_stack: ::alloc::vec::Vec::new()vec![],
867        ignored_derived_traits: Default::default(),
868    };
869    if let ControlFlow::Break(guar) = symbol_visitor.mark_live_symbols() {
870        return Err(guar);
871    }
872
873    // We have marked the primary seeds as live. We now need to process unsolved items from traits
874    // and trait impls: add them to the work list if the trait or the implemented type is live.
875    let mut items_to_check: Vec<_> = unsolved_items
876        .extract_if(.., |&mut local_def_id| {
877            symbol_visitor.check_impl_or_impl_item_live(local_def_id)
878        })
879        .collect();
880
881    while !items_to_check.is_empty() {
882        symbol_visitor
883            .worklist
884            .extend(items_to_check.drain(..).map(|id| (id, ComesFromAllowExpect::No)));
885        if let ControlFlow::Break(guar) = symbol_visitor.mark_live_symbols() {
886            return Err(guar);
887        }
888
889        items_to_check.extend(unsolved_items.extract_if(.., |&mut local_def_id| {
890            symbol_visitor.check_impl_or_impl_item_live(local_def_id)
891        }));
892    }
893
894    Ok((symbol_visitor.live_symbols, symbol_visitor.ignored_derived_traits))
895}
896
897struct DeadItem {
898    def_id: LocalDefId,
899    name: Symbol,
900    level: (lint::Level, Option<LintExpectationId>),
901}
902
903struct DeadVisitor<'tcx> {
904    tcx: TyCtxt<'tcx>,
905    live_symbols: &'tcx LocalDefIdSet,
906    ignored_derived_traits: &'tcx LocalDefIdMap<FxIndexSet<DefId>>,
907}
908
909enum ShouldWarnAboutField {
910    Yes,
911    No,
912}
913
914#[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 {
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
915enum ReportOn {
916    /// Report on something that hasn't got a proper name to refer to
917    TupleField,
918    /// Report on something that has got a name, which could be a field but also a method
919    NamedField,
920}
921
922impl<'tcx> DeadVisitor<'tcx> {
923    fn should_warn_about_field(&mut self, field: &ty::FieldDef) -> ShouldWarnAboutField {
924        if self.live_symbols.contains(&field.did.expect_local()) {
925            return ShouldWarnAboutField::No;
926        }
927        let field_type = self.tcx.type_of(field.did).instantiate_identity();
928        if field_type.is_phantom_data() {
929            return ShouldWarnAboutField::No;
930        }
931        let is_positional = field.name.as_str().starts_with(|c: char| c.is_ascii_digit());
932        if is_positional
933            && self
934                .tcx
935                .layout_of(
936                    ty::TypingEnv::non_body_analysis(self.tcx, field.did)
937                        .as_query_input(field_type),
938                )
939                .map_or(true, |layout| layout.is_zst())
940        {
941            return ShouldWarnAboutField::No;
942        }
943        ShouldWarnAboutField::Yes
944    }
945
946    fn def_lint_level(&self, id: LocalDefId) -> (lint::Level, Option<LintExpectationId>) {
947        let hir_id = self.tcx.local_def_id_to_hir_id(id);
948        let level = self.tcx.lint_level_at_node(DEAD_CODE, hir_id);
949        (level.level, level.lint_id)
950    }
951
952    // # Panics
953    // All `dead_codes` must have the same lint level, otherwise we will intentionally ICE.
954    // This is because we emit a multi-spanned lint using the lint level of the `dead_codes`'s
955    // first local def id.
956    // Prefer calling `Self.warn_dead_code` or `Self.warn_dead_code_grouped_by_lint_level`
957    // since those methods group by lint level before calling this method.
958    fn lint_at_single_level(
959        &self,
960        dead_codes: &[&DeadItem],
961        participle: &str,
962        parent_item: Option<LocalDefId>,
963        report_on: ReportOn,
964    ) {
965        let Some(&first_item) = dead_codes.first() else { return };
966        let tcx = self.tcx;
967
968        let first_lint_level = first_item.level;
969        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));
970
971        let names: Vec<_> = dead_codes.iter().map(|item| item.name).collect();
972        let spans: Vec<_> = dead_codes
973            .iter()
974            .map(|item| {
975                let span = tcx.def_span(item.def_id);
976                let ident_span = tcx.def_ident_span(item.def_id);
977                // FIXME(cjgillot) this SyntaxContext manipulation does not make any sense.
978                ident_span.map(|s| s.with_ctxt(span.ctxt())).unwrap_or(span)
979            })
980            .collect();
981
982        let mut descr = tcx.def_descr(first_item.def_id.to_def_id());
983        // `impl` blocks are "batched" and (unlike other batching) might
984        // contain different kinds of associated items.
985        if dead_codes.iter().any(|item| tcx.def_descr(item.def_id.to_def_id()) != descr) {
986            descr = "associated item"
987        }
988
989        let num = dead_codes.len();
990        let multiple = num > 6;
991        let name_list = names.into();
992
993        let parent_info = parent_item.map(|parent_item| {
994            let parent_descr = tcx.def_descr(parent_item.to_def_id());
995            let span = if let DefKind::Impl { .. } = tcx.def_kind(parent_item) {
996                tcx.def_span(parent_item)
997            } else {
998                tcx.def_ident_span(parent_item).unwrap()
999            };
1000            ParentInfo { num, descr, parent_descr, span }
1001        });
1002
1003        let mut encl_def_id = parent_item.unwrap_or(first_item.def_id);
1004        // `ignored_derived_traits` is computed for the enum, not for the variants.
1005        if let DefKind::Variant = tcx.def_kind(encl_def_id) {
1006            encl_def_id = tcx.local_parent(encl_def_id);
1007        }
1008
1009        let ignored_derived_impls =
1010            self.ignored_derived_traits.get(&encl_def_id).map(|ign_traits| {
1011                let trait_list = ign_traits
1012                    .iter()
1013                    .map(|trait_id| self.tcx.item_name(*trait_id))
1014                    .collect::<Vec<_>>();
1015                let trait_list_len = trait_list.len();
1016                IgnoredDerivedImpls {
1017                    name: self.tcx.item_name(encl_def_id.to_def_id()),
1018                    trait_list: trait_list.into(),
1019                    trait_list_len,
1020                }
1021            });
1022
1023        let diag = match report_on {
1024            ReportOn::TupleField => {
1025                let tuple_fields = if let Some(parent_id) = parent_item
1026                    && let node = tcx.hir_node_by_def_id(parent_id)
1027                    && let hir::Node::Item(hir::Item {
1028                        kind: hir::ItemKind::Struct(_, _, hir::VariantData::Tuple(fields, _, _)),
1029                        ..
1030                    }) = node
1031                {
1032                    *fields
1033                } else {
1034                    &[]
1035                };
1036
1037                let trailing_tuple_fields = if tuple_fields.len() >= dead_codes.len() {
1038                    LocalDefIdSet::from_iter(
1039                        tuple_fields
1040                            .iter()
1041                            .skip(tuple_fields.len() - dead_codes.len())
1042                            .map(|f| f.def_id),
1043                    )
1044                } else {
1045                    LocalDefIdSet::default()
1046                };
1047
1048                let fields_suggestion =
1049                    // Suggest removal if all tuple fields are at the end.
1050                    // Otherwise suggest removal or changing to unit type
1051                    if dead_codes.iter().all(|dc| trailing_tuple_fields.contains(&dc.def_id)) {
1052                        ChangeFields::Remove { num }
1053                    } else {
1054                        ChangeFields::ChangeToUnitTypeOrRemove { num, spans: spans.clone() }
1055                    };
1056
1057                MultipleDeadCodes::UnusedTupleStructFields {
1058                    multiple,
1059                    num,
1060                    descr,
1061                    participle,
1062                    name_list,
1063                    change_fields_suggestion: fields_suggestion,
1064                    parent_info,
1065                    ignored_derived_impls,
1066                }
1067            }
1068            ReportOn::NamedField => {
1069                let enum_variants_with_same_name = dead_codes
1070                    .iter()
1071                    .filter_map(|dead_item| {
1072                        if let DefKind::AssocFn | DefKind::AssocConst =
1073                            tcx.def_kind(dead_item.def_id)
1074                            && let impl_did = tcx.local_parent(dead_item.def_id)
1075                            && let DefKind::Impl { of_trait: false } = tcx.def_kind(impl_did)
1076                            && let ty::Adt(maybe_enum, _) =
1077                                tcx.type_of(impl_did).instantiate_identity().kind()
1078                            && maybe_enum.is_enum()
1079                            && let Some(variant) =
1080                                maybe_enum.variants().iter().find(|i| i.name == dead_item.name)
1081                        {
1082                            Some(crate::errors::EnumVariantSameName {
1083                                dead_descr: tcx.def_descr(dead_item.def_id.to_def_id()),
1084                                dead_name: dead_item.name,
1085                                variant_span: tcx.def_span(variant.def_id),
1086                            })
1087                        } else {
1088                            None
1089                        }
1090                    })
1091                    .collect();
1092
1093                MultipleDeadCodes::DeadCodes {
1094                    multiple,
1095                    num,
1096                    descr,
1097                    participle,
1098                    name_list,
1099                    parent_info,
1100                    ignored_derived_impls,
1101                    enum_variants_with_same_name,
1102                }
1103            }
1104        };
1105
1106        let hir_id = tcx.local_def_id_to_hir_id(first_item.def_id);
1107        self.tcx.emit_node_span_lint(DEAD_CODE, hir_id, MultiSpan::from_spans(spans), diag);
1108    }
1109
1110    fn warn_multiple(
1111        &self,
1112        def_id: LocalDefId,
1113        participle: &str,
1114        dead_codes: Vec<DeadItem>,
1115        report_on: ReportOn,
1116    ) {
1117        let mut dead_codes = dead_codes
1118            .iter()
1119            .filter(|v| !v.name.as_str().starts_with('_'))
1120            .collect::<Vec<&DeadItem>>();
1121        if dead_codes.is_empty() {
1122            return;
1123        }
1124        // FIXME: `dead_codes` should probably be morally equivalent to `IndexMap<(Level, LintExpectationId), (DefId, Symbol)>`
1125        dead_codes.sort_by_key(|v| v.level.0);
1126        for group in dead_codes.chunk_by(|a, b| a.level == b.level) {
1127            self.lint_at_single_level(&group, participle, Some(def_id), report_on);
1128        }
1129    }
1130
1131    fn warn_dead_code(&mut self, id: LocalDefId, participle: &str) {
1132        let item = DeadItem {
1133            def_id: id,
1134            name: self.tcx.item_name(id.to_def_id()),
1135            level: self.def_lint_level(id),
1136        };
1137        self.lint_at_single_level(&[&item], participle, None, ReportOn::NamedField);
1138    }
1139
1140    fn check_definition(&mut self, def_id: LocalDefId) {
1141        if self.is_live_code(def_id) {
1142            return;
1143        }
1144        match self.tcx.def_kind(def_id) {
1145            DefKind::AssocConst
1146            | DefKind::AssocTy
1147            | DefKind::AssocFn
1148            | DefKind::Fn
1149            | DefKind::Static { .. }
1150            | DefKind::Const
1151            | DefKind::TyAlias
1152            | DefKind::Enum
1153            | DefKind::Union
1154            | DefKind::ForeignTy
1155            | DefKind::Trait => self.warn_dead_code(def_id, "used"),
1156            DefKind::Struct => self.warn_dead_code(def_id, "constructed"),
1157            DefKind::Variant | DefKind::Field => ::rustc_middle::util::bug::bug_fmt(format_args!("should be handled specially"))bug!("should be handled specially"),
1158            _ => {}
1159        }
1160    }
1161
1162    fn is_live_code(&self, def_id: LocalDefId) -> bool {
1163        // if we cannot get a name for the item, then we just assume that it is
1164        // live. I mean, we can't really emit a lint.
1165        let Some(name) = self.tcx.opt_item_name(def_id.to_def_id()) else {
1166            return true;
1167        };
1168
1169        self.live_symbols.contains(&def_id) || name.as_str().starts_with('_')
1170    }
1171}
1172
1173fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalModDefId) {
1174    let Ok((live_symbols, ignored_derived_traits)) =
1175        tcx.live_symbols_and_ignored_derived_traits(()).as_ref()
1176    else {
1177        return;
1178    };
1179
1180    let mut visitor = DeadVisitor { tcx, live_symbols, ignored_derived_traits };
1181
1182    let module_items = tcx.hir_module_items(module);
1183
1184    for item in module_items.free_items() {
1185        let def_kind = tcx.def_kind(item.owner_id);
1186
1187        let mut dead_codes = Vec::new();
1188        // Only diagnose unused assoc items in inherent impl and used trait,
1189        // for unused assoc items in impls of trait,
1190        // we have diagnosed them in the trait if they are unused,
1191        // for unused assoc items in unused trait,
1192        // we have diagnosed the unused trait.
1193        if def_kind == (DefKind::Impl { of_trait: false })
1194            || (def_kind == DefKind::Trait && live_symbols.contains(&item.owner_id.def_id))
1195        {
1196            for &def_id in tcx.associated_item_def_ids(item.owner_id.def_id) {
1197                if let Some(local_def_id) = def_id.as_local()
1198                    && !visitor.is_live_code(local_def_id)
1199                {
1200                    let name = tcx.item_name(def_id);
1201                    let level = visitor.def_lint_level(local_def_id);
1202                    dead_codes.push(DeadItem { def_id: local_def_id, name, level });
1203                }
1204            }
1205        }
1206        if !dead_codes.is_empty() {
1207            visitor.warn_multiple(item.owner_id.def_id, "used", dead_codes, ReportOn::NamedField);
1208        }
1209
1210        if !live_symbols.contains(&item.owner_id.def_id) {
1211            let parent = tcx.local_parent(item.owner_id.def_id);
1212            if parent != module.to_local_def_id() && !live_symbols.contains(&parent) {
1213                // We already have diagnosed something.
1214                continue;
1215            }
1216            visitor.check_definition(item.owner_id.def_id);
1217            continue;
1218        }
1219
1220        if let DefKind::Struct | DefKind::Union | DefKind::Enum = def_kind {
1221            let adt = tcx.adt_def(item.owner_id);
1222            let mut dead_variants = Vec::new();
1223
1224            for variant in adt.variants() {
1225                let def_id = variant.def_id.expect_local();
1226                if !live_symbols.contains(&def_id) {
1227                    // Record to group diagnostics.
1228                    let level = visitor.def_lint_level(def_id);
1229                    dead_variants.push(DeadItem { def_id, name: variant.name, level });
1230                    continue;
1231                }
1232
1233                let is_positional = variant.fields.raw.first().is_some_and(|field| {
1234                    field.name.as_str().starts_with(|c: char| c.is_ascii_digit())
1235                });
1236                let report_on =
1237                    if is_positional { ReportOn::TupleField } else { ReportOn::NamedField };
1238                let dead_fields = variant
1239                    .fields
1240                    .iter()
1241                    .filter_map(|field| {
1242                        let def_id = field.did.expect_local();
1243                        if let ShouldWarnAboutField::Yes = visitor.should_warn_about_field(field) {
1244                            let level = visitor.def_lint_level(def_id);
1245                            Some(DeadItem { def_id, name: field.name, level })
1246                        } else {
1247                            None
1248                        }
1249                    })
1250                    .collect();
1251                visitor.warn_multiple(def_id, "read", dead_fields, report_on);
1252            }
1253
1254            visitor.warn_multiple(
1255                item.owner_id.def_id,
1256                "constructed",
1257                dead_variants,
1258                ReportOn::NamedField,
1259            );
1260        }
1261    }
1262
1263    for foreign_item in module_items.foreign_items() {
1264        visitor.check_definition(foreign_item.owner_id.def_id);
1265    }
1266}
1267
1268pub(crate) fn provide(providers: &mut Providers) {
1269    *providers =
1270        Providers { live_symbols_and_ignored_derived_traits, check_mod_deathness, ..*providers };
1271}