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