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