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