Skip to main content

rustc_passes/
dead.rs

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