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