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;
8use std::sync::atomic::Ordering;
9
10use hir::def_id::LocalDefIdSet;
11use rustc_abi::FieldIdx;
12use rustc_attr_ir::find_attr;
13use rustc_data_structures::fx::{FxHashMap, FxHashSet};
14use rustc_errors::{ErrorGuaranteed, MultiSpan};
15use rustc_hir::def::{CtorOf, DefKind, Res};
16use rustc_hir::def_id::{DefId, LocalDefId, LocalDefIdMap, LocalModId};
17use rustc_hir::intravisit::{self, Visitor};
18use rustc_hir::{self as hir, ForeignItemId, ItemId, Node, PatKind, QPath};
19use rustc_lint_defs::builtin::{DEAD_CODE, DEAD_CODE_PUB_IN_BINARY};
20use rustc_lint_defs::{self as lint, Lint, StableLintExpectationId};
21use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
22use rustc_middle::middle::dead_code::{DeadCodeLivenessSnapshot, DeadCodeLivenessSummary};
23use rustc_middle::middle::privacy::Level;
24use rustc_middle::query::Providers;
25use rustc_middle::ty::{self, AssocTag, TyCtxt};
26use rustc_span::{ExpnKind, MacroKind, Span, Symbol, bug, kw, span_bug};
27use rustc_structures::CrateType;
28
29use crate::diagnostics::{
30    ChangeFields, DeadCodePubInBinaryNote, MultipleDeadCodes, ParentInfo, UselessAssignment,
31};
32
33/// Any local definition that may call something in its body block should be explored. For example,
34/// if it's a live function, then we should explore its block to check for codes that may need to
35/// be marked as live.
36fn should_explore(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
37    match tcx.def_kind(def_id) {
38        DefKind::Mod
39        | DefKind::Struct
40        | DefKind::Union
41        | DefKind::Enum
42        | DefKind::Variant
43        | DefKind::Trait
44        | DefKind::TyAlias
45        | DefKind::ForeignTy
46        | DefKind::TraitAlias
47        | DefKind::AssocTy
48        | DefKind::Fn
49        | DefKind::Const
50        | DefKind::Static { .. }
51        | DefKind::AssocFn
52        | DefKind::AssocConst
53        | DefKind::Macro(_)
54        | DefKind::GlobalAsm
55        | DefKind::Impl { .. }
56        | DefKind::OpaqueTy
57        | DefKind::AnonConst
58        | DefKind::ExternCrate
59        | DefKind::Use
60        | DefKind::Ctor(..)
61        | DefKind::ForeignMod => true,
62
63        DefKind::TyParam
64        | DefKind::ConstParam
65        | DefKind::Field
66        | DefKind::LifetimeParam
67        | DefKind::Closure
68        | DefKind::SyntheticCoroutineBody
69        | DefKind::TestBinderConstraints => false,
70    }
71}
72
73/// Determine if a work from the worklist is coming from a `#[allow]`
74/// or a `#[expect]` of `dead_code`
75#[derive(#[automatically_derived]impl ::core::fmt::Debug for ComesFromAllowExpect {
    #[inline]
    #[rustc_trivial_field_reads]
    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]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for ComesFromAllowExpect {
}
#[automatically_derived]impl ::core::clone::Clone for ComesFromAllowExpect {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::cmp::Eq for ComesFromAllowExpect { }Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    ComesFromAllowExpect {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ComesFromAllowExpect {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::hash::Hash for ComesFromAllowExpect {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            state)
    }
}Hash)]
76enum ComesFromAllowExpect {
77    Yes,
78    No,
79}
80
81/// Carries both the propagated `allow/expect` context and the current item's
82/// own `allow/expect` status.
83///
84/// For example:
85///
86/// ```rust
87/// #[expect(dead_code)]
88/// fn root() { middle() }
89///
90/// fn middle() { leaf() }
91///
92/// #[expect(dead_code)]
93/// fn leaf() {}
94/// ```
95///
96/// The seed for `root` starts as `propagated = Yes, own = Yes`.
97///
98/// When `root` reaches `middle`, the propagated context stays `Yes`, but
99/// `middle` itself does not have `#[allow(dead_code)]` or `#[expect(dead_code)]`,
100/// so its work item becomes `propagated = Yes, own = No`.
101///
102/// When `middle` reaches `leaf`, that same propagated `Yes` context is preserved,
103/// and since `leaf` itself has `#[expect(dead_code)]`, its work item becomes
104/// `propagated = Yes, own = Yes`.
105///
106/// In general, `propagated` controls whether descendants are still explored
107/// under an `allow/expect` context, while `own` controls whether the current
108/// item itself should be excluded from `live_symbols`.
109#[derive(#[automatically_derived]impl ::core::fmt::Debug for WorkItem {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "WorkItem id propagated own propagated_trivial_usage_site",
            &self.id, &self.propagated, &self.own,
            &&self.propagated_trivial_usage_site)
    }
}Debug, #[automatically_derived]impl ::core::marker::Copy for WorkItem { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for WorkItem {
}
#[automatically_derived]impl ::core::clone::Clone for WorkItem {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<LocalDefId>;
        let _: ::core::clone::AssertParamIsClone<ComesFromAllowExpect>;
        let _: ::core::clone::AssertParamIsClone<Option<LocalDefId>>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::cmp::Eq for WorkItem {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<LocalDefId>;
        let _: ::core::cmp::AssertParamIsEq<ComesFromAllowExpect>;
        let _: ::core::cmp::AssertParamIsEq<Option<LocalDefId>>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for WorkItem
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for WorkItem {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id && self.propagated == other.propagated &&
                self.own == other.own &&
            self.propagated_trivial_usage_site ==
                other.propagated_trivial_usage_site
    }
}PartialEq, #[automatically_derived]impl ::core::hash::Hash for WorkItem {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.id, state);
        ::core::hash::Hash::hash(&self.propagated, state);
        ::core::hash::Hash::hash(&self.own, state);
        ::core::hash::Hash::hash(&self.propagated_trivial_usage_site, state)
    }
}Hash)]
110struct WorkItem {
111    id: LocalDefId,
112    propagated: ComesFromAllowExpect,
113    own: ComesFromAllowExpect,
114    propagated_trivial_usage_site: Option<LocalDefId>,
115}
116
117enum ImplItemCheckResult {
118    Live(ComesFromAllowExpect),
119    Dead { require: LocalDefId },
120}
121
122#[derive(#[automatically_derived]impl ::core::cmp::Eq for ScannedItem {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<LocalDefId>;
        let _: ::core::cmp::AssertParamIsEq<ComesFromAllowExpect>;
        let _: ::core::cmp::AssertParamIsEq<Option<LocalDefId>>;
    }
}Eq, #[automatically_derived]impl ::core::hash::Hash for ScannedItem {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.id, state);
        ::core::hash::Hash::hash(&self.propagated, state);
        ::core::hash::Hash::hash(&self.trivial_usage_site, state)
    }
}Hash, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    ScannedItem {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ScannedItem {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id && self.propagated == other.propagated &&
            self.trivial_usage_site == other.trivial_usage_site
    }
}PartialEq, #[automatically_derived]impl ::core::fmt::Debug for ScannedItem {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "ScannedItem id propagated trivial_usage_site", &self.id,
            &self.propagated, &&self.trivial_usage_site)
    }
}Debug)]
123struct ScannedItem {
124    id: LocalDefId,
125    propagated: ComesFromAllowExpect,
126    trivial_usage_site: Option<LocalDefId>,
127}
128
129#[derive(#[automatically_derived]impl ::core::default::Default for LiveSymbols {
    #[inline]
    fn default() -> Self {
        LiveSymbols {
            live: ::core::default::Default::default(),
            sites_by_defid: ::core::default::Default::default(),
            sites: ::core::default::Default::default(),
        }
    }
}Default, #[automatically_derived]impl ::core::clone::Clone for LiveSymbols {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        LiveSymbols {
            live: ::core::clone::Clone::clone(&self.live),
            sites_by_defid: ::core::clone::Clone::clone(&self.sites_by_defid),
            sites: ::core::clone::Clone::clone(&self.sites),
        }
    }
}Clone)]
130struct LiveSymbols {
131    live: LocalDefIdSet,
132    sites_by_defid: LocalDefIdMap<FxHashSet<LocalDefId>>,
133    sites: LocalDefIdMap<Span>,
134}
135
136impl LiveSymbols {
137    fn insert(&mut self, def_id: LocalDefId, trivial_usage_site: Option<LocalDefId>) {
138        match trivial_usage_site {
139            Some(site) => {
140                // Only remember the trivial usage of the field
141                // if it it is dead or has only used trivially before
142                if !self.live.contains(&def_id) {
143                    self.sites_by_defid.entry(def_id).or_default().insert(site);
144                }
145            }
146            None => {
147                self.live.insert(def_id);
148                self.sites_by_defid.remove(&def_id);
149            }
150        }
151    }
152
153    fn add_trivial_usage_site(&mut self, id: LocalDefId, attr_span: Span) {
154        self.sites.insert(id, attr_span);
155    }
156
157    fn make_snapshot(self, tcx: TyCtxt<'_>) -> DeadCodeLivenessSnapshot {
158        let sites_by_defid = self
159            .sites_by_defid
160            .items()
161            .map(|(def_id, site_ids)| {
162                #[expect(rustc::potential_query_instability)]
163                let mut site_ids = site_ids.iter().copied().collect::<Vec<_>>();
164                site_ids.sort_unstable_by_key(|id| tcx.def_path_hash(id.to_def_id()));
165                (*def_id, site_ids)
166            })
167            .collect();
168        DeadCodeLivenessSnapshot { live: self.live, sites_by_defid, sites: self.sites }
169    }
170}
171
172struct MarkSymbolVisitor<'tcx> {
173    worklist: Vec<WorkItem>,
174    tcx: TyCtxt<'tcx>,
175    maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
176    scanned: FxHashSet<ScannedItem>,
177    live_symbols: LiveSymbols,
178    repr_unconditionally_treats_fields_as_live: bool,
179    repr_has_repr_simd_or_scalable: bool,
180    trivial_usage_sites: Vec<LocalDefId>,
181    in_pat: bool,
182    ignore_variant_stack: Vec<DefId>,
183    propagated_comes_from_allow_expect: ComesFromAllowExpect,
184    unsolved_items: Vec<LocalDefId>,
185}
186
187impl<'tcx> MarkSymbolVisitor<'tcx> {
188    /// Gets the type-checking results for the current body.
189    /// As this will ICE if called outside bodies, only call when working with
190    /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
191    #[track_caller]
192    fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
193        self.maybe_typeck_results
194            .expect("`MarkSymbolVisitor::typeck_results` called outside of body")
195    }
196
197    /// Returns whether `def_id` itself should be treated as coming from
198    /// `#[allow(dead_code)]` or `#[expect(dead_code)]` in the current
199    /// propagated work-item context.
200    fn own_comes_from_allow_expect(&self, def_id: LocalDefId) -> ComesFromAllowExpect {
201        if self.propagated_comes_from_allow_expect == ComesFromAllowExpect::Yes
202            && let Some(ComesFromAllowExpect::Yes) =
203                has_allow_dead_code_or_lang_attr(self.tcx, def_id)
204        {
205            ComesFromAllowExpect::Yes
206        } else {
207            ComesFromAllowExpect::No
208        }
209    }
210
211    fn check_def_id(&mut self, def_id: DefId) {
212        if let Some(def_id) = def_id.as_local() {
213            let own_comes_from_allow_expect = self.own_comes_from_allow_expect(def_id);
214
215            if should_explore(self.tcx, def_id) {
216                self.worklist.push(WorkItem {
217                    id: def_id,
218                    propagated: self.propagated_comes_from_allow_expect,
219                    own: own_comes_from_allow_expect,
220                    propagated_trivial_usage_site: self.trivial_usage_sites.last().copied(),
221                });
222            }
223
224            if own_comes_from_allow_expect == ComesFromAllowExpect::No {
225                self.mark_live_symbol(def_id);
226            }
227        }
228    }
229
230    fn insert_def_id(&mut self, def_id: DefId) {
231        if let Some(def_id) = def_id.as_local() {
232            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));
233
234            if self.own_comes_from_allow_expect(def_id) == ComesFromAllowExpect::No {
235                self.mark_live_symbol(def_id);
236            }
237        }
238    }
239
240    fn handle_res(&mut self, res: Res) {
241        match res {
242            Res::PrimTy(..) | Res::SelfCtor(..) | Res::Local(..) => {}
243            Res::Def(DefKind::Ctor(CtorOf::Variant, ..), ctor_def_id) => {
244                // Using a variant in patterns should not make the variant live,
245                // since we can just remove the match arm that matches the pattern
246                if self.in_pat {
247                    return;
248                }
249                let variant_id = self.tcx.parent(ctor_def_id);
250                let enum_id = self.tcx.parent(variant_id);
251                self.check_def_id(enum_id);
252                if !self.ignore_variant_stack.contains(&ctor_def_id) {
253                    self.check_def_id(variant_id);
254                }
255            }
256            Res::Def(DefKind::Variant, variant_id) => {
257                // Using a variant in patterns should not make the variant live,
258                // since we can just remove the match arm that matches the pattern
259                if self.in_pat {
260                    return;
261                }
262                let enum_id = self.tcx.parent(variant_id);
263                self.check_def_id(enum_id);
264                if !self.ignore_variant_stack.contains(&variant_id) {
265                    self.check_def_id(variant_id);
266                }
267            }
268            Res::Def(_, def_id) => self.check_def_id(def_id),
269            Res::SelfTyParam { trait_: t } => self.check_def_id(t),
270            Res::SelfTyAlias { alias_to: i, .. } => self.check_def_id(i),
271            Res::ToolMod | Res::NonMacroAttr(..) | Res::OpenMod(..) | Res::Err => {}
272        }
273    }
274
275    fn lookup_and_handle_method(&mut self, id: hir::HirId) {
276        if let Some(def_id) = self.typeck_results().type_dependent_def_id(id) {
277            self.check_def_id(def_id);
278        } else {
279            if !self.typeck_results().tainted_by_errors.is_some() {
    {
        ::core::panicking::panic_fmt(format_args!("no type-dependent def for method"));
    }
};assert!(
280                self.typeck_results().tainted_by_errors.is_some(),
281                "no type-dependent def for method"
282            );
283        }
284    }
285
286    fn handle_field_access(&mut self, lhs: &hir::Expr<'_>, hir_id: hir::HirId) {
287        match self.typeck_results().expr_ty_adjusted(lhs).kind() {
288            ty::Adt(def, _) => {
289                let index = self.typeck_results().field_index(hir_id);
290                self.insert_def_id(def.non_enum_variant().fields[index].did);
291            }
292            ty::Tuple(..) => {}
293            ty::Error(_) => {}
294            kind => ::rustc_span::macros::bug_impl(Some(lhs.span),
    format_args!("named field access on non-ADT: {0:?}", kind),
    Location::caller())span_bug!(lhs.span, "named field access on non-ADT: {kind:?}"),
295        }
296    }
297
298    fn handle_assign(&mut self, expr: &'tcx hir::Expr<'tcx>) {
299        if self
300            .typeck_results()
301            .expr_adjustments(expr)
302            .iter()
303            .any(|adj| #[allow(non_exhaustive_omitted_patterns)] match adj.kind {
    ty::adjustment::Adjust::Deref(_) => true,
    _ => false,
}matches!(adj.kind, ty::adjustment::Adjust::Deref(_)))
304        {
305            let _ = self.visit_expr(expr);
306        } else if let hir::ExprKind::Field(base, ..) = expr.kind {
307            // Ignore write to field
308            self.handle_assign(base);
309        } else {
310            let _ = self.visit_expr(expr);
311        }
312    }
313
314    fn check_for_self_assign(&mut self, assign: &'tcx hir::Expr<'tcx>) {
315        fn check_for_self_assign_helper<'tcx>(
316            typeck_results: &'tcx ty::TypeckResults<'tcx>,
317            lhs: &'tcx hir::Expr<'tcx>,
318            rhs: &'tcx hir::Expr<'tcx>,
319        ) -> bool {
320            match (&lhs.kind, &rhs.kind) {
321                (hir::ExprKind::Path(qpath_l), hir::ExprKind::Path(qpath_r)) => {
322                    if let (Res::Local(id_l), Res::Local(id_r)) = (
323                        typeck_results.qpath_res(qpath_l, lhs.hir_id),
324                        typeck_results.qpath_res(qpath_r, rhs.hir_id),
325                    ) {
326                        if id_l == id_r {
327                            return true;
328                        }
329                    }
330                    return false;
331                }
332                (hir::ExprKind::Field(lhs_l, ident_l), hir::ExprKind::Field(lhs_r, ident_r)) => {
333                    if ident_l == ident_r {
334                        return check_for_self_assign_helper(typeck_results, lhs_l, lhs_r);
335                    }
336                    return false;
337                }
338                _ => {
339                    return false;
340                }
341            }
342        }
343
344        if let hir::ExprKind::Assign(lhs, rhs, _) = assign.kind
345            && check_for_self_assign_helper(self.typeck_results(), lhs, rhs)
346            && !assign.span.from_expansion()
347        {
348            let is_field_assign = #[allow(non_exhaustive_omitted_patterns)] match lhs.kind {
    hir::ExprKind::Field(..) => true,
    _ => false,
}matches!(lhs.kind, hir::ExprKind::Field(..));
349            self.tcx.emit_node_span_lint(
350                DEAD_CODE,
351                assign.hir_id,
352                assign.span,
353                UselessAssignment { is_field_assign, ty: self.typeck_results().expr_ty(lhs) },
354            )
355        }
356    }
357
358    fn handle_field_pattern_match(
359        &mut self,
360        lhs: &hir::Pat<'_>,
361        res: Res,
362        pats: &[hir::PatField<'_>],
363    ) {
364        let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
365            ty::Adt(adt, _) => {
366                // Marks the ADT live if its variant appears as the pattern,
367                // considering cases when we have `let T(x) = foo()` and `fn foo<T>() -> T;`,
368                // we will lose the liveness info of `T` cause we cannot mark it live when visiting `foo`.
369                // Related issue: https://github.com/rust-lang/rust/issues/120770
370                self.check_def_id(adt.did());
371                adt.variant_of_res(res)
372            }
373            _ => ::rustc_span::macros::bug_impl(Some(lhs.span),
    format_args!("non-ADT in struct pattern"), Location::caller())span_bug!(lhs.span, "non-ADT in struct pattern"),
374        };
375        for pat in pats {
376            if let PatKind::Wild = pat.pat.kind {
377                continue;
378            }
379            let index = self.typeck_results().field_index(pat.hir_id);
380            self.insert_def_id(variant.fields[index].did);
381        }
382    }
383
384    fn handle_tuple_field_pattern_match(
385        &mut self,
386        lhs: &hir::Pat<'_>,
387        res: Res,
388        pats: &[hir::Pat<'_>],
389        dotdot: hir::DotDotPos,
390    ) {
391        let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
392            ty::Adt(adt, _) => {
393                // Marks the ADT live if its variant appears as the pattern
394                self.check_def_id(adt.did());
395                adt.variant_of_res(res)
396            }
397            _ => {
398                self.tcx.dcx().span_delayed_bug(lhs.span, "non-ADT in tuple struct pattern");
399                return;
400            }
401        };
402        let dotdot = dotdot.as_opt_usize().unwrap_or(pats.len());
403        let first_n = pats.iter().enumerate().take(dotdot);
404        let missing = variant.fields.len() - pats.len();
405        let last_n = pats.iter().enumerate().skip(dotdot).map(|(idx, pat)| (idx + missing, pat));
406        for (idx, pat) in first_n.chain(last_n) {
407            if let PatKind::Wild = pat.kind {
408                continue;
409            }
410            self.insert_def_id(variant.fields[FieldIdx::from_usize(idx)].did);
411        }
412    }
413
414    fn handle_offset_of(&mut self, expr: &'tcx hir::Expr<'tcx>) {
415        let indices = self
416            .typeck_results()
417            .offset_of_data()
418            .get(expr.hir_id)
419            .expect("no offset_of_data for offset_of");
420
421        for &(current_ty, variant, field) in indices {
422            match current_ty.kind() {
423                ty::Adt(def, _) => {
424                    let field = &def.variant(variant).fields[field];
425                    self.insert_def_id(field.did);
426                }
427                // we don't need to mark tuple fields as live,
428                // but we may need to mark subfields
429                ty::Tuple(_) => {}
430                _ => ::rustc_span::macros::bug_impl(Some(expr.span),
    format_args!("named field access on non-ADT"), Location::caller())span_bug!(expr.span, "named field access on non-ADT"),
431            }
432        }
433    }
434
435    fn mark_live_symbols(&mut self) -> <MarkSymbolVisitor<'tcx> as Visitor<'tcx>>::Result {
436        while let Some(work) = self.worklist.pop() {
437            let WorkItem { mut id, propagated, own, propagated_trivial_usage_site } = work;
438            self.propagated_comes_from_allow_expect = propagated;
439            self.trivial_usage_sites.clear();
440            self.trivial_usage_sites.extend(propagated_trivial_usage_site.into_iter());
441
442            // in the case of tuple struct constructors we want to check the item,
443            // not the generated tuple struct constructor function
444            if let DefKind::Ctor(..) = self.tcx.def_kind(id) {
445                id = self.tcx.local_parent(id);
446            }
447
448            // When using `#[allow]` or `#[expect]` of `dead_code`, we do a QOL improvement
449            // by declaring fn calls, statics, ... within said items as live, as well as
450            // the item itself, although technically this is not the case.
451            //
452            // This means that the lint for said items will never be fired.
453            //
454            // This doesn't make any difference for the item declared with `#[allow]`, as
455            // the lint firing will be a nop, as it will be silenced by the `#[allow]` of
456            // the item.
457            //
458            // However, for `#[expect]`, the presence or absence of the lint is relevant,
459            // so we don't add it to the list of live symbols when it comes from a
460            // `#[expect]`. This means that we will correctly report an item as live or not
461            // for the `#[expect]` case.
462            //
463            // Note that an item can and will be duplicated on the worklist with different
464            // `ComesFromAllowExpect`, particularly if it was added from the
465            // `effective_visibilities` query or from the `#[allow]`/`#[expect]` checks,
466            // this "duplication" is essential as otherwise a function with `#[expect]`
467            // called from a `pub fn` may be falsely reported as not live, falsely
468            // triggering the `unfulfilled_lint_expectations` lint.
469            match own {
470                ComesFromAllowExpect::Yes => {}
471                ComesFromAllowExpect::No => {
472                    self.mark_live_symbol(id);
473                }
474            }
475
476            if self.should_skip_scanning_id(
477                id,
478                propagated,
479                self.trivial_usage_sites.last().copied(),
480            ) {
481                continue;
482            }
483
484            // Avoid accessing the HIR for the synthesized associated type generated for RPITITs.
485            if self.tcx.is_impl_trait_in_trait(id.to_def_id()) {
486                self.mark_live_symbol(id);
487                continue;
488            }
489
490            self.visit_node(id)?;
491        }
492
493        ControlFlow::Continue(())
494    }
495
496    fn should_skip_scanning_id(
497        &mut self,
498        id: LocalDefId,
499        propagated: ComesFromAllowExpect,
500        trivial_usage_site: Option<LocalDefId>,
501    ) -> bool {
502        // If the item was previously scanned from a normal live seed,
503        // we don't need to scan it again.
504        if self.scanned.contains(&ScannedItem {
505            id,
506            propagated: ComesFromAllowExpect::No,
507            trivial_usage_site: None,
508        }) {
509            return true;
510        }
511        // If the item was scanned from the same allow/expect context and the same
512        // trivial usage site, we don't need to scan it again
513        if !self.scanned.insert(ScannedItem { id, propagated, trivial_usage_site }) {
514            return true;
515        }
516        // If the item is not coming from an `#[allow]` or `#[expect]`,
517        // we also mark it as scanned with `ComesFromAllowExpect::Yes`
518        // to avoid re-scanning it in the future.
519        if propagated == ComesFromAllowExpect::No {
520            self.scanned.insert(ScannedItem {
521                id,
522                propagated: ComesFromAllowExpect::Yes,
523                trivial_usage_site,
524            });
525        }
526        false
527    }
528
529    fn get_trivial_field_reads_attr(&mut self, id: LocalDefId, node: &Node<'_>) -> Option<Span> {
530        // This needs to be kept compatible with the allowed
531        // attribute positions in `RustcTrivialFieldReadsParser`
532        if !#[allow(non_exhaustive_omitted_patterns)] match node {
    Node::Item(hir::Item { kind: rustc_hir::ItemKind::Fn { .. }, .. }) |
        Node::ImplItem(hir::ImplItem {
        kind: rustc_hir::ImplItemKind::Fn { .. }, .. }) => true,
    _ => false,
}matches!(
533            node,
534            Node::Item(hir::Item { kind: rustc_hir::ItemKind::Fn { .. }, .. })
535                | Node::ImplItem(hir::ImplItem { kind: rustc_hir::ImplItemKind::Fn { .. }, .. })
536        ) {
537            return None;
538        }
539        {
    {
        'done:
            {
            for i in ::rustc_attr_ir::HasAttrs::get_attrs(id, &self.tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(RustcTrivialFieldReads(span))
                        => {
                        break 'done Some(*span);
                    }
                    ::rustc_attr_ir::Attribute::Tool(..) |
                        ::rustc_attr_ir::Attribute::DeriveHelper(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(self.tcx, id, RustcTrivialFieldReads(span) => *span)
540    }
541
542    fn visit_node(&mut self, id: LocalDefId) -> <MarkSymbolVisitor<'tcx> as Visitor<'tcx>>::Result {
543        let node = self.tcx.hir_node(self.tcx.local_def_id_to_hir_id(id));
544        let unconditionally_treated_fields_as_live =
545            self.repr_unconditionally_treats_fields_as_live;
546        let had_repr_simd_or_scalable = self.repr_has_repr_simd_or_scalable;
547        let has_trivial_attr = if let Some(attr_span) = self.get_trivial_field_reads_attr(id, &node)
548        {
549            self.live_symbols.add_trivial_usage_site(id, attr_span);
550            self.trivial_usage_sites.push(id);
551            true
552        } else {
553            false
554        };
555        self.repr_unconditionally_treats_fields_as_live = false;
556        self.repr_has_repr_simd_or_scalable = false;
557        let walk_result = match node {
558            Node::Item(item) => match item.kind {
559                hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
560                    let def = self.tcx.adt_def(item.owner_id);
561                    self.repr_unconditionally_treats_fields_as_live =
562                        def.repr().c() || def.repr().transparent();
563                    self.repr_has_repr_simd_or_scalable =
564                        def.repr().simd() || def.repr().scalable();
565
566                    intravisit::walk_item(self, item)
567                }
568                hir::ItemKind::ForeignMod { .. } => ControlFlow::Continue(()),
569                hir::ItemKind::Trait { items: trait_item_refs, .. } => {
570                    // mark assoc ty live if the trait is live
571                    for trait_item in trait_item_refs {
572                        if self.tcx.def_kind(trait_item.owner_id) == DefKind::AssocTy {
573                            self.check_def_id(trait_item.owner_id.to_def_id());
574                        }
575                    }
576                    intravisit::walk_item(self, item)
577                }
578                _ => intravisit::walk_item(self, item),
579            },
580            Node::TraitItem(trait_item) => {
581                // mark the trait live
582                let trait_item_id = trait_item.owner_id.to_def_id();
583                if let Some(trait_id) = self.tcx.trait_of_assoc(trait_item_id) {
584                    self.check_def_id(trait_id);
585                }
586                intravisit::walk_trait_item(self, trait_item)
587            }
588            Node::ImplItem(impl_item) => {
589                let item = self.tcx.local_parent(impl_item.owner_id.def_id);
590                if let hir::ImplItemImplKind::Inherent { .. } = impl_item.impl_kind {
591                    //// If it's a type whose items are live, then it's live, too.
592                    //// This is done to handle the case where, for example, the static
593                    //// method of a private type is used, but the type itself is never
594                    //// called directly.
595                    let self_ty = self.tcx.type_of(item).instantiate_identity().skip_norm_wip();
596                    match *self_ty.kind() {
597                        ty::Adt(def, _) => self.check_def_id(def.did()),
598                        ty::Foreign(did) => self.check_def_id(did),
599                        ty::Dynamic(data, ..) => {
600                            if let Some(def_id) = data.principal_def_id() {
601                                self.check_def_id(def_id)
602                            }
603                        }
604                        _ => {}
605                    }
606                }
607                intravisit::walk_impl_item(self, impl_item)
608            }
609            Node::ForeignItem(foreign_item) => intravisit::walk_foreign_item(self, foreign_item),
610            Node::OpaqueTy(opaq) => intravisit::walk_opaque_ty(self, opaq),
611            _ => ControlFlow::Continue(()),
612        };
613        self.repr_has_repr_simd_or_scalable = had_repr_simd_or_scalable;
614        self.repr_unconditionally_treats_fields_as_live = unconditionally_treated_fields_as_live;
615        if has_trivial_attr {
616            self.trivial_usage_sites.pop();
617        }
618
619        walk_result
620    }
621
622    fn mark_as_used_if_union(&mut self, adt: ty::AdtDef<'tcx>, fields: &[hir::ExprField<'_>]) {
623        if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did().is_local() {
624            for field in fields {
625                let index = self.typeck_results().field_index(field.hir_id);
626                self.insert_def_id(adt.non_enum_variant().fields[index].did);
627            }
628        }
629    }
630
631    /// Returns whether `local_def_id` is potentially alive or not.
632    /// `local_def_id` points to an impl or an impl item,
633    /// both impl and impl item that may be passed to this function are of a trait,
634    /// and added into the unsolved_items during `create_and_seed_worklist`
635    fn check_impl_or_impl_item_live(
636        &self,
637        local_def_id: LocalDefId,
638        defer_seeds_come_from_allow: bool,
639    ) -> ImplItemCheckResult {
640        let (impl_block_id, trait_def_id) = match self.tcx.def_kind(local_def_id) {
641            // assoc impl items of traits are live if the corresponding trait items are live
642            DefKind::AssocConst | DefKind::AssocTy | DefKind::AssocFn => {
643                let trait_def_id =
644                    self.tcx.trait_item_of(local_def_id).and_then(|def_id| def_id.as_local());
645                (self.tcx.local_parent(local_def_id), trait_def_id)
646            }
647            // impl items are live if the corresponding traits are live
648            DefKind::Impl { of_trait: true } => {
649                (local_def_id, self.tcx.impl_trait_id(local_def_id).as_local())
650            }
651            _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
652        };
653
654        let mut trait_comes_from_allow = None;
655        if let Some(trait_def_id) = trait_def_id {
656            if defer_seeds_come_from_allow {
657                if !self.live_symbols.live.contains(&trait_def_id) {
658                    return ImplItemCheckResult::Dead { require: trait_def_id };
659                }
660            } else {
661                trait_comes_from_allow = has_allow_dead_code_or_lang_attr(self.tcx, trait_def_id);
662
663                if !self.live_symbols.live.contains(&trait_def_id) {
664                    return match trait_comes_from_allow {
665                        Some(comes_from_allow) => ImplItemCheckResult::Live(comes_from_allow),
666                        None => ImplItemCheckResult::Dead { require: trait_def_id },
667                    };
668                }
669            }
670        }
671
672        // The impl or impl item is used if the corresponding trait or trait item is used and the ty is used.
673        if let ty::Adt(adt, _) =
674            self.tcx.type_of(impl_block_id).instantiate_identity().skip_norm_wip().kind()
675            && let Some(adt_def_id) = adt.did().as_local()
676            && !self.live_symbols.live.contains(&adt_def_id)
677        {
678            if defer_seeds_come_from_allow {
679                return ImplItemCheckResult::Dead { require: adt_def_id };
680            }
681
682            return match trait_comes_from_allow {
683                Some(comes_from_allow) => ImplItemCheckResult::Live(comes_from_allow),
684                None => ImplItemCheckResult::Dead { require: adt_def_id },
685            };
686        }
687
688        ImplItemCheckResult::Live(ComesFromAllowExpect::No)
689    }
690
691    fn collect_live_items_from_unsolved_items(
692        &mut self,
693        defer_seeds_come_from_allow: bool,
694        unsolved_items: Vec<LocalDefId>,
695        unsolved_map: &mut FxHashMap<LocalDefId, Vec<LocalDefId>>,
696    ) -> Vec<(LocalDefId, ComesFromAllowExpect)> {
697        let mut items_to_check = ::alloc::vec::Vec::new()vec![];
698
699        for def_id in unsolved_items {
700            match self.check_impl_or_impl_item_live(def_id, defer_seeds_come_from_allow) {
701                ImplItemCheckResult::Live(comes_from_allow) => {
702                    items_to_check.push((def_id, comes_from_allow));
703                }
704                ImplItemCheckResult::Dead { require } => {
705                    unsolved_map.entry(require).or_default().push(def_id);
706                }
707            }
708        }
709        items_to_check
710    }
711
712    #[expect(
713        rustc::potential_query_instability,
714        reason = "The order of the unsolved items is not important, so we can just collect them into a vector."
715    )]
716    fn mark_live_symbols_and_trivial_usage_sites(
717        &mut self,
718        defer_seeds_come_from_allow: bool,
719    ) -> Result<(), ErrorGuaranteed> {
720        if let ControlFlow::Break(guar) = self.mark_live_symbols() {
721            return Err(guar);
722        }
723
724        // We have marked the primary seeds as live. We now need to process unsolved items from traits
725        // and trait impls: add them to the work list if the trait or the implemented type is live.
726        let unsolved_items = std::mem::take(&mut self.unsolved_items);
727        let mut unsolved_map = FxHashMap::default();
728        let mut items_to_check = self.collect_live_items_from_unsolved_items(
729            defer_seeds_come_from_allow,
730            unsolved_items,
731            &mut unsolved_map,
732        );
733
734        while !items_to_check.is_empty() {
735            self.worklist.extend(items_to_check.into_iter().map(|(id, comes_from_allow)| {
736                let own = if defer_seeds_come_from_allow {
737                    ComesFromAllowExpect::No
738                } else {
739                    has_allow_dead_code_or_lang_attr(self.tcx, id)
740                        .unwrap_or(ComesFromAllowExpect::No)
741                };
742
743                WorkItem {
744                    id,
745                    propagated: comes_from_allow,
746                    own,
747                    propagated_trivial_usage_site: None,
748                }
749            }));
750            if let ControlFlow::Break(guar) = self.mark_live_symbols() {
751                return Err(guar);
752            }
753
754            let unsolved_items = unsolved_map
755                .extract_if(|require, _| self.live_symbols.live.contains(require))
756                .flat_map(|(_, items)| items)
757                .collect();
758
759            items_to_check = self.collect_live_items_from_unsolved_items(
760                defer_seeds_come_from_allow,
761                unsolved_items,
762                &mut unsolved_map,
763            );
764        }
765
766        self.unsolved_items = unsolved_map.into_values().flatten().collect();
767
768        Ok(())
769    }
770
771    fn mark_live_symbol(&mut self, def_id: LocalDefId) {
772        self.live_symbols.insert(def_id, self.trivial_usage_sites.last().copied());
773    }
774}
775
776impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
777    type Result = ControlFlow<ErrorGuaranteed>;
778
779    fn visit_nested_body(&mut self, body: hir::BodyId) -> Self::Result {
780        let typeck_results = self.tcx.typeck_body(body);
781
782        // The result shouldn't be tainted, otherwise it will cause ICE.
783        if let Some(guar) = typeck_results.tainted_by_errors {
784            return ControlFlow::Break(guar);
785        }
786
787        let old_maybe_typeck_results = self.maybe_typeck_results.replace(typeck_results);
788        let body = self.tcx.hir_body(body);
789        let result = self.visit_body(body);
790        self.maybe_typeck_results = old_maybe_typeck_results;
791
792        result
793    }
794
795    fn visit_variant_data(&mut self, def: &'tcx hir::VariantData<'tcx>) -> Self::Result {
796        let tcx = self.tcx;
797        let unconditionally_treat_fields_as_live = self.repr_unconditionally_treats_fields_as_live;
798        let has_repr_simd_or_scalable = self.repr_has_repr_simd_or_scalable;
799        let effective_visibilities = &tcx.effective_visibilities(());
800        let live_fields = def.fields().iter().filter_map(|f| {
801            let def_id = f.def_id;
802            if unconditionally_treat_fields_as_live
803                || (f.is_positional() && has_repr_simd_or_scalable)
804            {
805                return Some(def_id);
806            }
807            if !effective_visibilities.is_reachable(f.hir_id.owner.def_id) {
808                return None;
809            }
810            if effective_visibilities.is_reachable(def_id) { Some(def_id) } else { None }
811        });
812        for def_id in live_fields {
813            self.mark_live_symbol(def_id);
814        }
815
816        intravisit::walk_struct_def(self, def)
817    }
818
819    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) -> Self::Result {
820        match expr.kind {
821            hir::ExprKind::Path(ref qpath @ QPath::TypeRelative(..)) => {
822                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
823                self.handle_res(res);
824            }
825            hir::ExprKind::MethodCall(..) => {
826                self.lookup_and_handle_method(expr.hir_id);
827            }
828            hir::ExprKind::Field(ref lhs, ..) => {
829                if self.typeck_results().opt_field_index(expr.hir_id).is_some() {
830                    self.handle_field_access(lhs, expr.hir_id);
831                } else {
832                    self.tcx.dcx().span_delayed_bug(expr.span, "couldn't resolve index for field");
833                }
834            }
835            hir::ExprKind::Struct(qpath, fields, _) => {
836                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
837                self.handle_res(res);
838                if let ty::Adt(adt, _) = self.typeck_results().expr_ty(expr).kind() {
839                    self.mark_as_used_if_union(*adt, fields);
840                }
841            }
842            hir::ExprKind::Closure(cls) => {
843                self.insert_def_id(cls.def_id.to_def_id());
844            }
845            hir::ExprKind::OffsetOf(..) => {
846                self.handle_offset_of(expr);
847            }
848            hir::ExprKind::Assign(ref lhs, ..) => {
849                self.handle_assign(lhs);
850                self.check_for_self_assign(expr);
851            }
852            _ => (),
853        }
854
855        intravisit::walk_expr(self, expr)
856    }
857
858    fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) -> Self::Result {
859        // Inside the body, ignore constructions of variants
860        // necessary for the pattern to match. Those construction sites
861        // can't be reached unless the variant is constructed elsewhere.
862        let len = self.ignore_variant_stack.len();
863        self.ignore_variant_stack.extend(arm.pat.necessary_variants());
864        let result = intravisit::walk_arm(self, arm);
865        self.ignore_variant_stack.truncate(len);
866
867        result
868    }
869
870    fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Self::Result {
871        self.in_pat = true;
872        match pat.kind {
873            PatKind::Struct(ref path, fields, _) => {
874                let res = self.typeck_results().qpath_res(path, pat.hir_id);
875                self.handle_field_pattern_match(pat, res, fields);
876            }
877            PatKind::TupleStruct(ref qpath, fields, dotdot) => {
878                let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
879                self.handle_tuple_field_pattern_match(pat, res, fields, dotdot);
880            }
881            _ => (),
882        }
883
884        let result = intravisit::walk_pat(self, pat);
885        self.in_pat = false;
886
887        result
888    }
889
890    fn visit_pat_expr(&mut self, expr: &'tcx rustc_hir::PatExpr<'tcx>) -> Self::Result {
891        match &expr.kind {
892            rustc_hir::PatExprKind::Path(qpath) => {
893                // mark the type of variant live when meeting E::V in expr
894                if let ty::Adt(adt, _) = self.typeck_results().node_type(expr.hir_id).kind() {
895                    self.check_def_id(adt.did());
896                }
897
898                let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
899                self.handle_res(res);
900            }
901            _ => {}
902        }
903        intravisit::walk_pat_expr(self, expr)
904    }
905
906    fn visit_path(&mut self, path: &hir::Path<'tcx>, _: hir::HirId) -> Self::Result {
907        self.handle_res(path.res);
908        intravisit::walk_path(self, path)
909    }
910
911    fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) -> Self::Result {
912        // When inline const blocks are used in pattern position, paths
913        // referenced by it should be considered as used.
914        let in_pat = mem::replace(&mut self.in_pat, false);
915
916        self.mark_live_symbol(c.def_id);
917        let result = intravisit::walk_anon_const(self, c);
918
919        self.in_pat = in_pat;
920
921        result
922    }
923
924    fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) -> Self::Result {
925        // When inline const blocks are used in pattern position, paths
926        // referenced by it should be considered as used.
927        let in_pat = mem::replace(&mut self.in_pat, false);
928
929        self.mark_live_symbol(c.def_id);
930        let result = intravisit::walk_inline_const(self, c);
931
932        self.in_pat = in_pat;
933
934        result
935    }
936
937    fn visit_trait_ref(&mut self, t: &'tcx hir::TraitRef<'tcx>) -> Self::Result {
938        if let Some(trait_def_id) = t.path.res.opt_def_id()
939            && let Some(segment) = t.path.segments.last()
940            && let Some(args) = segment.args
941        {
942            for constraint in args.constraints {
943                if let Some(local_def_id) = self
944                    .tcx
945                    .associated_items(trait_def_id)
946                    .find_by_ident_and_kind(
947                        self.tcx,
948                        constraint.ident,
949                        AssocTag::Const,
950                        trait_def_id,
951                    )
952                    .and_then(|item| item.def_id.as_local())
953                {
954                    self.worklist.push(WorkItem {
955                        id: local_def_id,
956                        propagated: ComesFromAllowExpect::No,
957                        own: ComesFromAllowExpect::No,
958                        propagated_trivial_usage_site: self.trivial_usage_sites.last().copied(),
959                    });
960                }
961            }
962        }
963
964        intravisit::walk_trait_ref(self, t)
965    }
966}
967
968fn has_allow_dead_code_or_lang_attr(
969    tcx: TyCtxt<'_>,
970    def_id: LocalDefId,
971) -> Option<ComesFromAllowExpect> {
972    fn has_allow_expect_dead_code(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
973        let hir_id = tcx.local_def_id_to_hir_id(def_id);
974        let lint_level = tcx.lint_level_spec_at_node(DEAD_CODE, hir_id).level();
975        #[allow(non_exhaustive_omitted_patterns)] match lint_level {
    lint::Allow | lint::Expect => true,
    _ => false,
}matches!(lint_level, lint::Allow | lint::Expect)
976    }
977
978    fn has_used_like_attr(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
979        tcx.def_kind(def_id).has_codegen_attrs() && {
980            let cg_attrs = tcx.codegen_fn_attrs(def_id);
981
982            // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
983            // forcefully, e.g., for placing it in a specific section.
984            cg_attrs.contains_extern_indicator()
985                || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)
986                || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)
987        }
988    }
989
990    if has_allow_expect_dead_code(tcx, def_id) {
991        Some(ComesFromAllowExpect::Yes)
992    } else if has_used_like_attr(tcx, def_id)
993        || {
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(Lang(..) |
                            RustcCanonicalSymbol) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Tool(..) |
                            ::rustc_attr_ir::Attribute::DeriveHelper(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(tcx, def_id, Lang(..) | RustcCanonicalSymbol)
994    {
995        Some(ComesFromAllowExpect::No)
996    } else {
997        None
998    }
999}
1000
1001/// Examine the given definition and record it in the worklist if it should be considered live.
1002///
1003/// We want to explicitly consider as live:
1004/// * Item annotated with #[allow(dead_code)]
1005///       This is done so that if we want to suppress warnings for a
1006///       group of dead functions, we only have to annotate the "root".
1007///       For example, if both `f` and `g` are dead and `f` calls `g`,
1008///       then annotating `f` with `#[allow(dead_code)]` will suppress
1009///       warning for both `f` and `g`.
1010///
1011/// * Item annotated with #[lang=".."]
1012///       Lang items are always callable from elsewhere.
1013///
1014/// For trait methods and implementations of traits, we are not certain that the definitions are
1015/// live at this stage. We record them in `unsolved_items` for later examination.
1016fn maybe_record_as_seed<'tcx>(
1017    tcx: TyCtxt<'tcx>,
1018    owner_id: hir::OwnerId,
1019    push_into_worklist: &mut impl FnMut(WorkItem),
1020    unsolved_items: &mut Vec<LocalDefId>,
1021) {
1022    let allow_dead_code = has_allow_dead_code_or_lang_attr(tcx, owner_id.def_id);
1023    if let Some(comes_from_allow) = allow_dead_code {
1024        push_into_worklist(WorkItem {
1025            id: owner_id.def_id,
1026            propagated: comes_from_allow,
1027            own: comes_from_allow,
1028            propagated_trivial_usage_site: None,
1029        });
1030    }
1031
1032    match tcx.def_kind(owner_id) {
1033        DefKind::Enum => {
1034            if let Some(comes_from_allow) = allow_dead_code {
1035                let adt = tcx.adt_def(owner_id);
1036                for variant in adt.variants().iter() {
1037                    push_into_worklist(WorkItem {
1038                        id: variant.def_id.expect_local(),
1039                        propagated: comes_from_allow,
1040                        own: comes_from_allow,
1041                        propagated_trivial_usage_site: None,
1042                    });
1043                }
1044            }
1045        }
1046        DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy => {
1047            // As with free constants named `_`, associated constants named `_` are always live.
1048            if let hir::Node::ImplItem(impl_item) = tcx.hir_node_by_def_id(owner_id.def_id)
1049                && impl_item.is_anon_const()
1050            {
1051                push_into_worklist(WorkItem {
1052                    id: owner_id.def_id,
1053                    propagated: ComesFromAllowExpect::No,
1054                    own: ComesFromAllowExpect::No,
1055                    propagated_trivial_usage_site: None,
1056                });
1057            }
1058
1059            if allow_dead_code.is_none() {
1060                let parent = tcx.local_parent(owner_id.def_id);
1061                match tcx.def_kind(parent) {
1062                    DefKind::Impl { of_trait: false } | DefKind::Trait => {}
1063                    DefKind::Impl { of_trait: true } => {
1064                        // We only care about associated items of traits,
1065                        // because they cannot be visited directly,
1066                        // so we later mark them as live if their corresponding traits
1067                        // or trait items and self types are both live,
1068                        // but inherent associated items can be visited and marked directly.
1069                        unsolved_items.push(owner_id.def_id);
1070                    }
1071                    _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
1072                }
1073            }
1074        }
1075        DefKind::Impl { of_trait: true } if allow_dead_code.is_none() => {
1076            unsolved_items.push(owner_id.def_id);
1077        }
1078        DefKind::GlobalAsm => {
1079            // global_asm! is always live.
1080            push_into_worklist(WorkItem {
1081                id: owner_id.def_id,
1082                propagated: ComesFromAllowExpect::No,
1083                own: ComesFromAllowExpect::No,
1084                propagated_trivial_usage_site: None,
1085            });
1086        }
1087        DefKind::Const => {
1088            if tcx.item_name(owner_id.def_id) == kw::Underscore {
1089                // `const _` is always live, as that syntax only exists for the side effects
1090                // of type checking and evaluating the constant expression, and marking them
1091                // as dead code would defeat that purpose.
1092                push_into_worklist(WorkItem {
1093                    id: owner_id.def_id,
1094                    propagated: ComesFromAllowExpect::No,
1095                    own: ComesFromAllowExpect::No,
1096                    propagated_trivial_usage_site: None,
1097                });
1098            }
1099        }
1100        _ => {}
1101    }
1102}
1103
1104#[derive(#[automatically_derived]impl ::core::default::Default for DeferredSeeds {
    #[inline]
    fn default() -> Self {
        DeferredSeeds {
            pub_reachables: ::core::default::Default::default(),
            come_from_allow: ::core::default::Default::default(),
        }
    }
}Default)]
1105struct DeferredSeeds {
1106    pub_reachables: Vec<WorkItem>,
1107    come_from_allow: Vec<WorkItem>,
1108}
1109
1110struct SeedWorklists {
1111    worklist: Vec<WorkItem>,
1112    deferred_seeds: DeferredSeeds,
1113    unsolved_items: Vec<LocalDefId>,
1114}
1115
1116fn create_and_seed_worklist(tcx: TyCtxt<'_>) -> SeedWorklists {
1117    let mut unsolved_items = Vec::new();
1118    let mut deferred_seeds = DeferredSeeds::default();
1119    let mut worklist = Vec::new();
1120
1121    if let Some((def_id, _)) = tcx.entry_fn(())
1122        && let Some(local_def_id) = def_id.as_local()
1123    {
1124        worklist.push(WorkItem {
1125            id: local_def_id,
1126            propagated: ComesFromAllowExpect::No,
1127            own: ComesFromAllowExpect::No,
1128            propagated_trivial_usage_site: None,
1129        });
1130    }
1131
1132    // Under `--test`, what `main` resolves to is the would-be entry point of a normal build,
1133    // so keep it live, unless a stripped user `#[rustc_main]` would have been the entry instead.
1134    if tcx.sess.is_test_crate()
1135        && !tcx.sess.removed_rustc_main_attr.load(Ordering::Relaxed)
1136        && let Some(main_def) = tcx.resolutions(()).main_def
1137        && let Some(def_id) = main_def.opt_fn_def_id()
1138        && let Some(local_def_id) = def_id.as_local()
1139    {
1140        worklist.push(WorkItem {
1141            id: local_def_id,
1142            propagated: ComesFromAllowExpect::No,
1143            own: ComesFromAllowExpect::No,
1144            propagated_trivial_usage_site: None,
1145        });
1146    }
1147
1148    for (id, effective_vis) in tcx.effective_visibilities(()).iter() {
1149        if effective_vis.is_public_at_level(Level::Reachable) {
1150            deferred_seeds.pub_reachables.push(WorkItem {
1151                id: *id,
1152                propagated: ComesFromAllowExpect::No,
1153                own: ComesFromAllowExpect::No,
1154                propagated_trivial_usage_site: None,
1155            });
1156        }
1157    }
1158
1159    let mut push_into_worklist = |work_item: WorkItem| match work_item.own {
1160        ComesFromAllowExpect::Yes => deferred_seeds.come_from_allow.push(work_item),
1161        ComesFromAllowExpect::No => worklist.push(work_item),
1162    };
1163    let crate_items = tcx.hir_crate_items(());
1164    for id in crate_items.owners() {
1165        maybe_record_as_seed(tcx, id, &mut push_into_worklist, &mut unsolved_items);
1166    }
1167
1168    SeedWorklists { worklist, deferred_seeds, unsolved_items }
1169}
1170
1171fn live_symbols_and_trivial_usage_sites(
1172    tcx: TyCtxt<'_>,
1173    (): (),
1174) -> Result<DeadCodeLivenessSummary, ErrorGuaranteed> {
1175    let SeedWorklists { worklist, deferred_seeds, unsolved_items } = create_and_seed_worklist(tcx);
1176    let mut symbol_visitor = MarkSymbolVisitor {
1177        worklist,
1178        tcx,
1179        maybe_typeck_results: None,
1180        scanned: Default::default(),
1181        live_symbols: Default::default(),
1182        repr_unconditionally_treats_fields_as_live: false,
1183        repr_has_repr_simd_or_scalable: false,
1184        trivial_usage_sites: ::alloc::vec::Vec::new()vec![],
1185        in_pat: false,
1186        ignore_variant_stack: ::alloc::vec::Vec::new()vec![],
1187        propagated_comes_from_allow_expect: ComesFromAllowExpect::No,
1188        unsolved_items,
1189    };
1190    symbol_visitor.mark_live_symbols_and_trivial_usage_sites(true)?;
1191    let pre_deferred_seeding = symbol_visitor.live_symbols.clone().make_snapshot(tcx);
1192
1193    if !deferred_seeds.pub_reachables.is_empty() {
1194        symbol_visitor.worklist.extend(deferred_seeds.pub_reachables);
1195        symbol_visitor.mark_live_symbols_and_trivial_usage_sites(true)?;
1196    }
1197
1198    if !deferred_seeds.come_from_allow.is_empty() {
1199        symbol_visitor.worklist.extend(deferred_seeds.come_from_allow);
1200        symbol_visitor.mark_live_symbols_and_trivial_usage_sites(false)?;
1201    }
1202
1203    Ok(DeadCodeLivenessSummary {
1204        pre_deferred_seeding,
1205        final_result: symbol_visitor.live_symbols.make_snapshot(tcx),
1206    })
1207}
1208
1209struct DeadItem {
1210    def_id: LocalDefId,
1211    name: Symbol,
1212    level_plus: (lint::Level, Option<StableLintExpectationId>),
1213}
1214
1215struct DeadVisitor<'tcx> {
1216    tcx: TyCtxt<'tcx>,
1217    target_lint: &'static Lint,
1218    live_symbols: &'tcx DeadCodeLivenessSnapshot,
1219}
1220
1221enum ShouldWarnAboutField {
1222    Yes,
1223    No,
1224}
1225
1226#[derive(#[automatically_derived]impl ::core::fmt::Debug for ReportOn {
    #[inline]
    #[rustc_trivial_field_reads]
    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]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for ReportOn {
}
#[automatically_derived]impl ::core::clone::Clone for ReportOn {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for ReportOn
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ReportOn {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for ReportOn { }Eq)]
1227enum ReportOn {
1228    /// Report on something that hasn't got a proper name to refer to
1229    TupleField,
1230    /// Report on something that has got a name, which could be a field but also a method
1231    NamedField,
1232}
1233
1234impl<'tcx> DeadVisitor<'tcx> {
1235    fn should_warn_about_field(&mut self, field: &ty::FieldDef) -> ShouldWarnAboutField {
1236        if self.live_symbols.is_live(&field.did.expect_local()) {
1237            return ShouldWarnAboutField::No;
1238        }
1239        let field_type = self.tcx.type_of(field.did).instantiate_identity().skip_norm_wip();
1240        if field_type.is_phantom_data() {
1241            return ShouldWarnAboutField::No;
1242        }
1243        let is_positional = field.name.as_str().starts_with(|c: char| c.is_ascii_digit());
1244        if is_positional
1245            && self
1246                .tcx
1247                .layout_of(
1248                    ty::TypingEnv::non_body_analysis(self.tcx, field.did)
1249                        .as_query_input(field_type),
1250                )
1251                .map_or(true, |layout| layout.is_zst())
1252        {
1253            return ShouldWarnAboutField::No;
1254        }
1255        ShouldWarnAboutField::Yes
1256    }
1257
1258    fn def_lint_level_plus(
1259        &self,
1260        id: LocalDefId,
1261    ) -> (lint::Level, Option<StableLintExpectationId>) {
1262        let hir_id = self.tcx.local_def_id_to_hir_id(id);
1263        let level_spec = self.tcx.lint_level_spec_at_node(self.target_lint, hir_id);
1264        (level_spec.level(), level_spec.lint_id())
1265    }
1266
1267    fn fulfill_dead_code_expectations(&self, def_id: LocalDefId, include: bool) {
1268        let fulfill_if_expected = |node: DefId| {
1269            // Only consider local, dead symbols where lint level carries an expectation
1270            if let Some(node) = node.as_local()
1271                && !self.live_symbols.is_live(&node)
1272                && let (_, Some(expectation)) = self.def_lint_level_plus(node)
1273            {
1274                // Same mechanism as LintContext::fulfill_expectation.
1275                self.tcx.dcx().fulfill_expectation(expectation);
1276            }
1277        };
1278
1279        if include {
1280            fulfill_if_expected(def_id.to_def_id());
1281        }
1282
1283        match self.tcx.def_kind(def_id) {
1284            DefKind::Struct | DefKind::Union | DefKind::Enum => {
1285                let adt = self.tcx.adt_def(def_id);
1286                for variant in adt.variants() {
1287                    if variant.def_id != def_id.to_def_id() {
1288                        fulfill_if_expected(variant.def_id);
1289                    }
1290                    for field in &variant.fields {
1291                        fulfill_if_expected(field.did);
1292                    }
1293                }
1294            }
1295            DefKind::Variant => {
1296                let parent_enum = self.tcx.local_parent(def_id);
1297                let variant = self.tcx.adt_def(parent_enum).variant_with_id(def_id.to_def_id());
1298                //Check to see if fields carry expectation
1299                for field in &variant.fields {
1300                    fulfill_if_expected(field.did);
1301                }
1302            }
1303            DefKind::Trait => {
1304                for &assoc_def_id in self.tcx.associated_item_def_ids(def_id) {
1305                    fulfill_if_expected(assoc_def_id);
1306                }
1307            }
1308            _ => {}
1309        }
1310    }
1311
1312    fn dead_code_pub_in_binary_note(&self) -> Option<DeadCodePubInBinaryNote> {
1313        self.target_lint.name.eq(DEAD_CODE_PUB_IN_BINARY.name).then_some(DeadCodePubInBinaryNote)
1314    }
1315
1316    // # Panics
1317    // All `dead_codes` must have the same lint level, otherwise we will intentionally ICE.
1318    // This is because we emit a multi-spanned lint using the lint level of the `dead_codes`'s
1319    // first local def id.
1320    // Prefer calling `Self.warn_dead_code` or `Self.warn_dead_code_grouped_by_lint_level`
1321    // since those methods group by lint level before calling this method.
1322    fn lint_at_single_level(
1323        &self,
1324        dead_codes: &[&DeadItem],
1325        participle: &str,
1326        parent_item: Option<LocalDefId>,
1327        report_on: ReportOn,
1328    ) {
1329        let Some(&first_item) = dead_codes.first() else { return };
1330        let tcx = self.tcx;
1331
1332        let first_lint_level_plus = first_item.level_plus;
1333        if !dead_codes.iter().skip(1).all(|item|
                item.level_plus == first_lint_level_plus) {
    ::core::panicking::panic("assertion failed: dead_codes.iter().skip(1).all(|item| item.level_plus == first_lint_level_plus)")
};assert!(dead_codes.iter().skip(1).all(|item| item.level_plus == first_lint_level_plus));
1334
1335        let names: Vec<_> = dead_codes.iter().map(|item| item.name).collect();
1336        let spans: Vec<_> = dead_codes
1337            .iter()
1338            .map(|item| {
1339                let span = tcx.def_span(item.def_id);
1340                let ident_span = tcx.def_ident_span(item.def_id);
1341                // FIXME(cjgillot) this SyntaxContext manipulation does not make any sense.
1342                ident_span.map(|s| s.with_ctxt(span.ctxt())).unwrap_or(span)
1343            })
1344            .collect();
1345
1346        let mut descr = tcx.def_descr(first_item.def_id.to_def_id());
1347        // `impl` blocks are "batched" and (unlike other batching) might
1348        // contain different kinds of associated items.
1349        if dead_codes.iter().any(|item| tcx.def_descr(item.def_id.to_def_id()) != descr) {
1350            descr = "associated item"
1351        }
1352
1353        let num = dead_codes.len();
1354        let multiple = num > 6;
1355        let name_list = names.into();
1356
1357        let parent_info = parent_item.map(|parent_item| {
1358            let parent_descr = tcx.def_descr(parent_item.to_def_id());
1359            let span = if let DefKind::Impl { .. } = tcx.def_kind(parent_item) {
1360                tcx.def_span(parent_item)
1361            } else {
1362                tcx.def_ident_span(parent_item).unwrap()
1363            };
1364            ParentInfo { num, descr, parent_descr, span }
1365        });
1366
1367        let trivial_usage_sites = self.trivial_usage_sites(dead_codes);
1368
1369        let diag = match report_on {
1370            ReportOn::TupleField => {
1371                let tuple_fields = if let Some(parent_id) = parent_item
1372                    && let node = tcx.hir_node_by_def_id(parent_id)
1373                    && let hir::Node::Item(hir::Item {
1374                        kind: hir::ItemKind::Struct(_, _, hir::VariantData::Tuple(fields, _, _)),
1375                        ..
1376                    }) = node
1377                {
1378                    *fields
1379                } else {
1380                    &[]
1381                };
1382
1383                let trailing_tuple_fields = if tuple_fields.len() >= dead_codes.len() {
1384                    LocalDefIdSet::from_iter(
1385                        tuple_fields
1386                            .iter()
1387                            .skip(tuple_fields.len() - dead_codes.len())
1388                            .map(|f| f.def_id),
1389                    )
1390                } else {
1391                    LocalDefIdSet::default()
1392                };
1393
1394                let fields_suggestion =
1395                    // Suggest removal if all tuple fields are at the end.
1396                    // Otherwise suggest removal or changing to unit type
1397                    if dead_codes.iter().all(|dc| trailing_tuple_fields.contains(&dc.def_id)) {
1398                        ChangeFields::Remove { num }
1399                    } else {
1400                        ChangeFields::ChangeToUnitTypeOrRemove { num, spans: spans.clone() }
1401                    };
1402
1403                MultipleDeadCodes::UnusedTupleStructFields {
1404                    multiple,
1405                    num,
1406                    descr,
1407                    participle,
1408                    name_list,
1409                    dead_code_pub_in_binary_note: self.dead_code_pub_in_binary_note(),
1410                    change_fields_suggestion: fields_suggestion,
1411                    parent_info,
1412                    trivial_usage_sites,
1413                }
1414            }
1415            ReportOn::NamedField => {
1416                let enum_variants_with_same_name = dead_codes
1417                    .iter()
1418                    .filter_map(|dead_item| {
1419                        if let DefKind::AssocFn | DefKind::AssocConst =
1420                            tcx.def_kind(dead_item.def_id)
1421                            && let impl_did = tcx.local_parent(dead_item.def_id)
1422                            && let DefKind::Impl { of_trait: false } = tcx.def_kind(impl_did)
1423                            && let ty::Adt(maybe_enum, _) =
1424                                tcx.type_of(impl_did).instantiate_identity().skip_norm_wip().kind()
1425                            && maybe_enum.is_enum()
1426                            && let Some(variant) =
1427                                maybe_enum.variants().iter().find(|i| i.name == dead_item.name)
1428                        {
1429                            Some(crate::diagnostics::EnumVariantSameName {
1430                                dead_descr: tcx.def_descr(dead_item.def_id.to_def_id()),
1431                                dead_name: dead_item.name,
1432                                variant_span: tcx.def_span(variant.def_id),
1433                            })
1434                        } else {
1435                            None
1436                        }
1437                    })
1438                    .collect();
1439
1440                MultipleDeadCodes::DeadCodes {
1441                    multiple,
1442                    num,
1443                    descr,
1444                    participle,
1445                    name_list,
1446                    dead_code_pub_in_binary_note: self.dead_code_pub_in_binary_note(),
1447                    parent_info,
1448                    trivial_usage_sites,
1449                    enum_variants_with_same_name,
1450                }
1451            }
1452        };
1453
1454        let hir_id = tcx.local_def_id_to_hir_id(first_item.def_id);
1455        self.tcx.emit_node_span_lint(self.target_lint, hir_id, MultiSpan::from_spans(spans), diag);
1456    }
1457
1458    fn trivial_usage_sites(
1459        &self,
1460        dead_items: &[&DeadItem],
1461    ) -> Vec<crate::diagnostics::TrivialUsageSite> {
1462        // For grouped diagnostics, we emit one note per usage site
1463        // wherein we point to all the items which are ignored due to the site.
1464        // Here, we invert the mapping from DefId -> [SiteId] to SiteId -> [DefId]
1465        let mut sites: FxHashMap<LocalDefId, Vec<LocalDefId>> = FxHashMap::default();
1466        for item in dead_items {
1467            for site_id in self.live_symbols.trivial_usage_sites(&item.def_id) {
1468                sites.entry(site_id).or_default().push(item.def_id);
1469            }
1470        }
1471        // We immediately sort these by span afterwards, so
1472        // the instability does not matter
1473        #[expect(rustc::potential_query_instability)]
1474        let mut notes: Vec<_> = sites
1475            .into_iter()
1476            .map(|(usage_site_id, def_ids)| {
1477                let usage_site_hir_id = self.tcx.local_def_id_to_hir_id(usage_site_id);
1478                let attr_span = self.live_symbols.trivial_usage_site_span_by_id(usage_site_id);
1479                let names: Vec<_> =
1480                    def_ids.iter().map(|def_id| self.tcx.item_name(*def_id)).collect();
1481                let multiple = names.len() > 1;
1482                let names = names.into();
1483                let (span, usage_msg) = match attr_span.ctxt().outer_expn_data().kind {
1484                    ExpnKind::Macro(MacroKind::Derive, name) => {
1485                        (attr_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("in the expansion of the derive macro `{0}`",
                name))
    })format!("in the expansion of the derive macro `{name}`"))
1486                    }
1487                    ExpnKind::Macro(_, name) => {
1488                        let span = if attr_span.in_external_macro(self.tcx.sess.source_map()) {
1489                            attr_span
1490                        } else {
1491                            // For local macros, point to the item, not the attr
1492                            self.tcx.hir_span(usage_site_hir_id)
1493                        };
1494                        (span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("in the expansion of the macro `{0}`",
                name))
    })format!("in the expansion of the macro `{name}`"))
1495                    }
1496                    _ => {
1497                        // The hir node always has a name, since `rustc_trivial_field_reads`
1498                        // can only be on functions and methods.
1499                        let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("in `{0}`",
                self.tcx.hir_name(usage_site_hir_id)))
    })format!("in `{}`", self.tcx.hir_name(usage_site_hir_id));
1500                        (self.tcx.hir_span(usage_site_hir_id), msg)
1501                    }
1502                };
1503                crate::diagnostics::TrivialUsageSite { names, span, usage_msg, multiple }
1504            })
1505            .collect();
1506        notes.sort_unstable_by_key(|note| note.span.lo_hi());
1507        notes
1508    }
1509
1510    fn warn_multiple(
1511        &self,
1512        def_id: LocalDefId,
1513        participle: &str,
1514        dead_codes: Vec<DeadItem>,
1515        report_on: ReportOn,
1516    ) {
1517        let mut dead_codes = dead_codes
1518            .iter()
1519            .filter(|v| !v.name.as_str().starts_with('_'))
1520            .collect::<Vec<&DeadItem>>();
1521        if dead_codes.is_empty() {
1522            return;
1523        }
1524        // FIXME: `dead_codes` should probably be morally equivalent to
1525        // `IndexMap<(Level, StableLintExpectationId), (DefId, Symbol)>`
1526        dead_codes.sort_by_key(|v| v.level_plus.0);
1527        for group in dead_codes.chunk_by(|a, b| a.level_plus == b.level_plus) {
1528            self.lint_at_single_level(&group, participle, Some(def_id), report_on);
1529        }
1530    }
1531
1532    fn warn_dead_code(&mut self, id: LocalDefId, participle: &str) {
1533        let item = DeadItem {
1534            def_id: id,
1535            name: self.tcx.item_name(id.to_def_id()),
1536            level_plus: self.def_lint_level_plus(id),
1537        };
1538        self.lint_at_single_level(&[&item], participle, None, ReportOn::NamedField);
1539    }
1540
1541    fn check_definition(&mut self, def_id: LocalDefId) {
1542        if self.is_live_code(def_id) {
1543            return;
1544        }
1545        match self.tcx.def_kind(def_id) {
1546            DefKind::AssocConst
1547            | DefKind::AssocTy
1548            | DefKind::AssocFn
1549            | DefKind::Fn
1550            | DefKind::Static { .. }
1551            | DefKind::Const
1552            | DefKind::TyAlias
1553            | DefKind::Enum
1554            | DefKind::Union
1555            | DefKind::ForeignTy
1556            | DefKind::Trait => self.warn_dead_code(def_id, "used"),
1557            DefKind::Struct => self.warn_dead_code(def_id, "constructed"),
1558            DefKind::Variant | DefKind::Field => ::rustc_span::macros::bug_impl(None,
    format_args!("should be handled specially"), Location::caller())bug!("should be handled specially"),
1559            _ => {}
1560        }
1561    }
1562
1563    fn is_live_code(&self, def_id: LocalDefId) -> bool {
1564        // if we cannot get a name for the item, then we just assume that it is
1565        // live. I mean, we can't really emit a lint.
1566        let Some(name) = self.tcx.opt_item_name(def_id.to_def_id()) else {
1567            return true;
1568        };
1569
1570        self.live_symbols.is_live(&def_id) || name.as_str().starts_with('_')
1571    }
1572}
1573
1574fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalModId) {
1575    let Ok(DeadCodeLivenessSummary { pre_deferred_seeding, final_result }) =
1576        tcx.live_symbols_and_trivial_usage_sites(()).as_ref()
1577    else {
1578        return;
1579    };
1580
1581    let module_items = tcx.hir_module_items(module);
1582
1583    if tcx.crate_types().contains(&CrateType::Executable) {
1584        let is_unused_pub = |def_id: LocalDefId| {
1585            tcx.effective_visibilities(()).is_public_at_level(def_id, Level::Reachable)
1586                && !pre_deferred_seeding.is_live(&def_id)
1587        };
1588
1589        lint_dead_codes(
1590            tcx,
1591            DEAD_CODE_PUB_IN_BINARY,
1592            module,
1593            &pre_deferred_seeding,
1594            module_items.free_items().filter(|free_item| is_unused_pub(free_item.owner_id.def_id)),
1595            module_items
1596                .foreign_items()
1597                .filter(|foreign_item| is_unused_pub(foreign_item.owner_id.def_id)),
1598        );
1599    }
1600
1601    lint_dead_codes(
1602        tcx,
1603        DEAD_CODE,
1604        module,
1605        &final_result,
1606        module_items.free_items(),
1607        module_items.foreign_items(),
1608    );
1609}
1610
1611fn lint_dead_codes<'tcx>(
1612    tcx: TyCtxt<'tcx>,
1613    target_lint: &'static Lint,
1614    module: LocalModId,
1615    live_symbols: &'tcx DeadCodeLivenessSnapshot,
1616    free_items: impl Iterator<Item = ItemId>,
1617    foreign_items: impl Iterator<Item = ForeignItemId>,
1618) {
1619    let mut visitor = DeadVisitor { tcx, target_lint, live_symbols };
1620    for item in free_items {
1621        let def_kind = tcx.def_kind(item.owner_id);
1622
1623        let mut dead_codes = Vec::new();
1624        // Only diagnose unused assoc items in inherent impl and used trait,
1625        // for unused assoc items in impls of trait,
1626        // we have diagnosed them in the trait if they are unused,
1627        // for unused assoc items in unused trait,
1628        // we have diagnosed the unused trait.
1629        if def_kind == (DefKind::Impl { of_trait: false })
1630            || (def_kind == DefKind::Trait && live_symbols.is_live(&item.owner_id.def_id))
1631        {
1632            for &def_id in tcx.associated_item_def_ids(item.owner_id.def_id) {
1633                if let Some(local_def_id) = def_id.as_local()
1634                    && !visitor.is_live_code(local_def_id)
1635                {
1636                    let name = tcx.item_name(def_id);
1637                    let level_plus = visitor.def_lint_level_plus(local_def_id);
1638                    dead_codes.push(DeadItem { def_id: local_def_id, name, level_plus });
1639                }
1640            }
1641        }
1642        if !dead_codes.is_empty() {
1643            visitor.warn_multiple(item.owner_id.def_id, "used", dead_codes, ReportOn::NamedField);
1644        }
1645
1646        if !live_symbols.is_live(&item.owner_id.def_id) {
1647            let parent = tcx.local_parent(item.owner_id.def_id);
1648            if parent != module.to_local_def_id() && !live_symbols.is_live(&parent) {
1649                // We already have diagnosed something, but check parent's field for #[expect]
1650                visitor.fulfill_dead_code_expectations(item.owner_id.def_id, true);
1651                continue;
1652            }
1653            visitor.check_definition(item.owner_id.def_id);
1654            visitor.fulfill_dead_code_expectations(item.owner_id.def_id, false);
1655            continue;
1656        }
1657
1658        if let DefKind::Struct | DefKind::Union | DefKind::Enum = def_kind {
1659            let adt = tcx.adt_def(item.owner_id);
1660            let mut dead_variants = Vec::new();
1661
1662            for variant in adt.variants() {
1663                let def_id = variant.def_id.expect_local();
1664                if !live_symbols.is_live(&def_id) {
1665                    // Record to group diagnostics.
1666                    let level_plus = visitor.def_lint_level_plus(def_id);
1667                    dead_variants.push(DeadItem { def_id, name: variant.name, level_plus });
1668                    visitor.fulfill_dead_code_expectations(def_id, false);
1669                    continue;
1670                }
1671
1672                let is_positional = variant.fields.raw.first().is_some_and(|field| {
1673                    field.name.as_str().starts_with(|c: char| c.is_ascii_digit())
1674                });
1675                let report_on =
1676                    if is_positional { ReportOn::TupleField } else { ReportOn::NamedField };
1677                let dead_fields = variant
1678                    .fields
1679                    .iter()
1680                    .filter_map(|field| {
1681                        let def_id = field.did.expect_local();
1682                        if let ShouldWarnAboutField::Yes = visitor.should_warn_about_field(field) {
1683                            let level_plus = visitor.def_lint_level_plus(def_id);
1684                            Some(DeadItem { def_id, name: field.name, level_plus })
1685                        } else {
1686                            None
1687                        }
1688                    })
1689                    .collect();
1690                visitor.warn_multiple(def_id, "read", dead_fields, report_on);
1691            }
1692
1693            visitor.warn_multiple(
1694                item.owner_id.def_id,
1695                "constructed",
1696                dead_variants,
1697                ReportOn::NamedField,
1698            );
1699        }
1700    }
1701
1702    for foreign_item in foreign_items {
1703        visitor.check_definition(foreign_item.owner_id.def_id);
1704    }
1705}
1706
1707pub(crate) fn provide(providers: &mut Providers) {
1708    *providers =
1709        Providers { live_symbols_and_trivial_usage_sites, check_mod_deathness, ..*providers };
1710}