1use std::mem;
7use std::ops::ControlFlow;
8
9use hir::def_id::{LocalDefIdMap, LocalDefIdSet};
10use rustc_abi::FieldIdx;
11use rustc_data_structures::fx::FxIndexSet;
12use rustc_errors::{ErrorGuaranteed, MultiSpan};
13use rustc_hir::attrs::AttributeKind;
14use rustc_hir::def::{CtorOf, DefKind, Res};
15use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId};
16use rustc_hir::intravisit::{self, Visitor};
17use rustc_hir::{self as hir, Node, PatKind, QPath, find_attr};
18use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
19use rustc_middle::middle::privacy::Level;
20use rustc_middle::query::Providers;
21use rustc_middle::ty::{self, AssocTag, TyCtxt};
22use rustc_middle::{bug, span_bug};
23use rustc_session::lint::builtin::DEAD_CODE;
24use rustc_session::lint::{self, LintExpectationId};
25use rustc_span::{Symbol, kw, sym};
26
27use crate::errors::{
28 ChangeFields, IgnoredDerivedImpls, MultipleDeadCodes, ParentInfo, UselessAssignment,
29};
30
31fn should_explore(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
35 match tcx.def_kind(def_id) {
36 DefKind::Mod
37 | DefKind::Struct
38 | DefKind::Union
39 | DefKind::Enum
40 | DefKind::Variant
41 | DefKind::Trait
42 | DefKind::TyAlias
43 | DefKind::ForeignTy
44 | DefKind::TraitAlias
45 | DefKind::AssocTy
46 | DefKind::Fn
47 | DefKind::Const
48 | DefKind::Static { .. }
49 | DefKind::AssocFn
50 | DefKind::AssocConst
51 | DefKind::Macro(_)
52 | DefKind::GlobalAsm
53 | DefKind::Impl { .. }
54 | DefKind::OpaqueTy
55 | DefKind::AnonConst
56 | DefKind::InlineConst
57 | DefKind::ExternCrate
58 | DefKind::Use
59 | DefKind::Ctor(..)
60 | DefKind::ForeignMod => true,
61
62 DefKind::TyParam
63 | DefKind::ConstParam
64 | DefKind::Field
65 | DefKind::LifetimeParam
66 | DefKind::Closure
67 | DefKind::SyntheticCoroutineBody => false,
68 }
69}
70
71#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ComesFromAllowExpect {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ComesFromAllowExpect::Yes => "Yes",
ComesFromAllowExpect::No => "No",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for ComesFromAllowExpect { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ComesFromAllowExpect {
#[inline]
fn clone(&self) -> ComesFromAllowExpect { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::Eq for ComesFromAllowExpect {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for ComesFromAllowExpect {
#[inline]
fn eq(&self, other: &ComesFromAllowExpect) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::hash::Hash for ComesFromAllowExpect {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state)
}
}Hash)]
74enum ComesFromAllowExpect {
75 Yes,
76 No,
77}
78
79struct MarkSymbolVisitor<'tcx> {
80 worklist: Vec<(LocalDefId, ComesFromAllowExpect)>,
81 tcx: TyCtxt<'tcx>,
82 maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
83 scanned: LocalDefIdSet,
84 live_symbols: LocalDefIdSet,
85 repr_unconditionally_treats_fields_as_live: bool,
86 repr_has_repr_simd: bool,
87 in_pat: bool,
88 ignore_variant_stack: Vec<DefId>,
89 ignored_derived_traits: LocalDefIdMap<FxIndexSet<DefId>>,
93}
94
95impl<'tcx> MarkSymbolVisitor<'tcx> {
96 #[track_caller]
100 fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
101 self.maybe_typeck_results
102 .expect("`MarkSymbolVisitor::typeck_results` called outside of body")
103 }
104
105 fn check_def_id(&mut self, def_id: DefId) {
106 if let Some(def_id) = def_id.as_local() {
107 if should_explore(self.tcx, def_id) {
108 self.worklist.push((def_id, ComesFromAllowExpect::No));
109 }
110 self.live_symbols.insert(def_id);
111 }
112 }
113
114 fn insert_def_id(&mut self, def_id: DefId) {
115 if let Some(def_id) = def_id.as_local() {
116 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));
117 self.live_symbols.insert(def_id);
118 }
119 }
120
121 fn handle_res(&mut self, res: Res) {
122 match res {
123 Res::Def(
124 DefKind::Const | DefKind::AssocConst | DefKind::AssocTy | DefKind::TyAlias,
125 def_id,
126 ) => {
127 self.check_def_id(def_id);
128 }
129 Res::PrimTy(..) | Res::SelfCtor(..) | Res::Local(..) => {}
130 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), ctor_def_id) => {
131 if self.in_pat {
134 return;
135 }
136 let variant_id = self.tcx.parent(ctor_def_id);
137 let enum_id = self.tcx.parent(variant_id);
138 self.check_def_id(enum_id);
139 if !self.ignore_variant_stack.contains(&ctor_def_id) {
140 self.check_def_id(variant_id);
141 }
142 }
143 Res::Def(DefKind::Variant, variant_id) => {
144 if self.in_pat {
147 return;
148 }
149 let enum_id = self.tcx.parent(variant_id);
150 self.check_def_id(enum_id);
151 if !self.ignore_variant_stack.contains(&variant_id) {
152 self.check_def_id(variant_id);
153 }
154 }
155 Res::Def(_, def_id) => self.check_def_id(def_id),
156 Res::SelfTyParam { trait_: t } => self.check_def_id(t),
157 Res::SelfTyAlias { alias_to: i, .. } => self.check_def_id(i),
158 Res::ToolMod | Res::NonMacroAttr(..) | Res::Err => {}
159 }
160 }
161
162 fn lookup_and_handle_method(&mut self, id: hir::HirId) {
163 if let Some(def_id) = self.typeck_results().type_dependent_def_id(id) {
164 self.check_def_id(def_id);
165 } else {
166 if !self.typeck_results().tainted_by_errors.is_some() {
{
::core::panicking::panic_fmt(format_args!("no type-dependent def for method"));
}
};assert!(
167 self.typeck_results().tainted_by_errors.is_some(),
168 "no type-dependent def for method"
169 );
170 }
171 }
172
173 fn handle_field_access(&mut self, lhs: &hir::Expr<'_>, hir_id: hir::HirId) {
174 match self.typeck_results().expr_ty_adjusted(lhs).kind() {
175 ty::Adt(def, _) => {
176 let index = self.typeck_results().field_index(hir_id);
177 self.insert_def_id(def.non_enum_variant().fields[index].did);
178 }
179 ty::Tuple(..) => {}
180 ty::Error(_) => {}
181 kind => ::rustc_middle::util::bug::span_bug_fmt(lhs.span,
format_args!("named field access on non-ADT: {0:?}", kind))span_bug!(lhs.span, "named field access on non-ADT: {kind:?}"),
182 }
183 }
184
185 fn handle_assign(&mut self, expr: &'tcx hir::Expr<'tcx>) {
186 if self
187 .typeck_results()
188 .expr_adjustments(expr)
189 .iter()
190 .any(|adj| #[allow(non_exhaustive_omitted_patterns)] match adj.kind {
ty::adjustment::Adjust::Deref(_) => true,
_ => false,
}matches!(adj.kind, ty::adjustment::Adjust::Deref(_)))
191 {
192 let _ = self.visit_expr(expr);
193 } else if let hir::ExprKind::Field(base, ..) = expr.kind {
194 self.handle_assign(base);
196 } else {
197 let _ = self.visit_expr(expr);
198 }
199 }
200
201 fn check_for_self_assign(&mut self, assign: &'tcx hir::Expr<'tcx>) {
202 fn check_for_self_assign_helper<'tcx>(
203 typeck_results: &'tcx ty::TypeckResults<'tcx>,
204 lhs: &'tcx hir::Expr<'tcx>,
205 rhs: &'tcx hir::Expr<'tcx>,
206 ) -> bool {
207 match (&lhs.kind, &rhs.kind) {
208 (hir::ExprKind::Path(qpath_l), hir::ExprKind::Path(qpath_r)) => {
209 if let (Res::Local(id_l), Res::Local(id_r)) = (
210 typeck_results.qpath_res(qpath_l, lhs.hir_id),
211 typeck_results.qpath_res(qpath_r, rhs.hir_id),
212 ) {
213 if id_l == id_r {
214 return true;
215 }
216 }
217 return false;
218 }
219 (hir::ExprKind::Field(lhs_l, ident_l), hir::ExprKind::Field(lhs_r, ident_r)) => {
220 if ident_l == ident_r {
221 return check_for_self_assign_helper(typeck_results, lhs_l, lhs_r);
222 }
223 return false;
224 }
225 _ => {
226 return false;
227 }
228 }
229 }
230
231 if let hir::ExprKind::Assign(lhs, rhs, _) = assign.kind
232 && check_for_self_assign_helper(self.typeck_results(), lhs, rhs)
233 && !assign.span.from_expansion()
234 {
235 let is_field_assign = #[allow(non_exhaustive_omitted_patterns)] match lhs.kind {
hir::ExprKind::Field(..) => true,
_ => false,
}matches!(lhs.kind, hir::ExprKind::Field(..));
236 self.tcx.emit_node_span_lint(
237 lint::builtin::DEAD_CODE,
238 assign.hir_id,
239 assign.span,
240 UselessAssignment { is_field_assign, ty: self.typeck_results().expr_ty(lhs) },
241 )
242 }
243 }
244
245 fn handle_field_pattern_match(
246 &mut self,
247 lhs: &hir::Pat<'_>,
248 res: Res,
249 pats: &[hir::PatField<'_>],
250 ) {
251 let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
252 ty::Adt(adt, _) => {
253 self.check_def_id(adt.did());
258 adt.variant_of_res(res)
259 }
260 _ => ::rustc_middle::util::bug::span_bug_fmt(lhs.span,
format_args!("non-ADT in struct pattern"))span_bug!(lhs.span, "non-ADT in struct pattern"),
261 };
262 for pat in pats {
263 if let PatKind::Wild = pat.pat.kind {
264 continue;
265 }
266 let index = self.typeck_results().field_index(pat.hir_id);
267 self.insert_def_id(variant.fields[index].did);
268 }
269 }
270
271 fn handle_tuple_field_pattern_match(
272 &mut self,
273 lhs: &hir::Pat<'_>,
274 res: Res,
275 pats: &[hir::Pat<'_>],
276 dotdot: hir::DotDotPos,
277 ) {
278 let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
279 ty::Adt(adt, _) => {
280 self.check_def_id(adt.did());
282 adt.variant_of_res(res)
283 }
284 _ => {
285 self.tcx.dcx().span_delayed_bug(lhs.span, "non-ADT in tuple struct pattern");
286 return;
287 }
288 };
289 let dotdot = dotdot.as_opt_usize().unwrap_or(pats.len());
290 let first_n = pats.iter().enumerate().take(dotdot);
291 let missing = variant.fields.len() - pats.len();
292 let last_n = pats.iter().enumerate().skip(dotdot).map(|(idx, pat)| (idx + missing, pat));
293 for (idx, pat) in first_n.chain(last_n) {
294 if let PatKind::Wild = pat.kind {
295 continue;
296 }
297 self.insert_def_id(variant.fields[FieldIdx::from_usize(idx)].did);
298 }
299 }
300
301 fn handle_offset_of(&mut self, expr: &'tcx hir::Expr<'tcx>) {
302 let indices = self
303 .typeck_results()
304 .offset_of_data()
305 .get(expr.hir_id)
306 .expect("no offset_of_data for offset_of");
307
308 for &(current_ty, variant, field) in indices {
309 match current_ty.kind() {
310 ty::Adt(def, _) => {
311 let field = &def.variant(variant).fields[field];
312 self.insert_def_id(field.did);
313 }
314 ty::Tuple(_) => {}
317 _ => ::rustc_middle::util::bug::span_bug_fmt(expr.span,
format_args!("named field access on non-ADT"))span_bug!(expr.span, "named field access on non-ADT"),
318 }
319 }
320 }
321
322 fn mark_live_symbols(&mut self) -> <MarkSymbolVisitor<'tcx> as Visitor<'tcx>>::Result {
323 while let Some(work) = self.worklist.pop() {
324 let (mut id, comes_from_allow_expect) = work;
325
326 if let DefKind::Ctor(..) = self.tcx.def_kind(id) {
329 id = self.tcx.local_parent(id);
330 }
331
332 match comes_from_allow_expect {
354 ComesFromAllowExpect::Yes => {}
355 ComesFromAllowExpect::No => {
356 self.live_symbols.insert(id);
357 }
358 }
359
360 if !self.scanned.insert(id) {
361 continue;
362 }
363
364 if self.tcx.is_impl_trait_in_trait(id.to_def_id()) {
366 self.live_symbols.insert(id);
367 continue;
368 }
369
370 self.visit_node(self.tcx.hir_node_by_def_id(id))?;
371 }
372
373 ControlFlow::Continue(())
374 }
375
376 fn should_ignore_impl_item(&mut self, impl_item: &hir::ImplItem<'_>) -> bool {
380 if let hir::ImplItemImplKind::Trait { .. } = impl_item.impl_kind
381 && let impl_of = self.tcx.parent(impl_item.owner_id.to_def_id())
382 && self.tcx.is_automatically_derived(impl_of)
383 && let trait_ref = self.tcx.impl_trait_ref(impl_of).instantiate_identity()
384 && {
{
'done:
{
for i in self.tcx.get_all_attrs(trait_ref.def_id) {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::RustcTrivialFieldReads)
=> {
break 'done Some(());
}
_ => {}
}
}
None
}
}.is_some()
}find_attr!(
385 self.tcx.get_all_attrs(trait_ref.def_id),
386 AttributeKind::RustcTrivialFieldReads
387 )
388 {
389 if let ty::Adt(adt_def, _) = trait_ref.self_ty().kind()
390 && let Some(adt_def_id) = adt_def.did().as_local()
391 {
392 self.ignored_derived_traits.entry(adt_def_id).or_default().insert(trait_ref.def_id);
393 }
394 return true;
395 }
396
397 false
398 }
399
400 fn visit_node(
401 &mut self,
402 node: Node<'tcx>,
403 ) -> <MarkSymbolVisitor<'tcx> as Visitor<'tcx>>::Result {
404 if let Node::ImplItem(impl_item) = node
405 && self.should_ignore_impl_item(impl_item)
406 {
407 return ControlFlow::Continue(());
408 }
409
410 let unconditionally_treated_fields_as_live =
411 self.repr_unconditionally_treats_fields_as_live;
412 let had_repr_simd = self.repr_has_repr_simd;
413 self.repr_unconditionally_treats_fields_as_live = false;
414 self.repr_has_repr_simd = false;
415 let walk_result = match node {
416 Node::Item(item) => match item.kind {
417 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
418 let def = self.tcx.adt_def(item.owner_id);
419 self.repr_unconditionally_treats_fields_as_live =
420 def.repr().c() || def.repr().transparent();
421 self.repr_has_repr_simd = def.repr().simd();
422
423 intravisit::walk_item(self, item)
424 }
425 hir::ItemKind::ForeignMod { .. } => ControlFlow::Continue(()),
426 hir::ItemKind::Trait(.., trait_item_refs) => {
427 for trait_item in trait_item_refs {
429 if self.tcx.def_kind(trait_item.owner_id) == DefKind::AssocTy {
430 self.check_def_id(trait_item.owner_id.to_def_id());
431 }
432 }
433 intravisit::walk_item(self, item)
434 }
435 _ => intravisit::walk_item(self, item),
436 },
437 Node::TraitItem(trait_item) => {
438 let trait_item_id = trait_item.owner_id.to_def_id();
440 if let Some(trait_id) = self.tcx.trait_of_assoc(trait_item_id) {
441 self.check_def_id(trait_id);
442 }
443 intravisit::walk_trait_item(self, trait_item)
444 }
445 Node::ImplItem(impl_item) => {
446 let item = self.tcx.local_parent(impl_item.owner_id.def_id);
447 if let hir::ImplItemImplKind::Inherent { .. } = impl_item.impl_kind {
448 let self_ty = self.tcx.type_of(item).instantiate_identity();
453 match *self_ty.kind() {
454 ty::Adt(def, _) => self.check_def_id(def.did()),
455 ty::Foreign(did) => self.check_def_id(did),
456 ty::Dynamic(data, ..) => {
457 if let Some(def_id) = data.principal_def_id() {
458 self.check_def_id(def_id)
459 }
460 }
461 _ => {}
462 }
463 }
464 intravisit::walk_impl_item(self, impl_item)
465 }
466 Node::ForeignItem(foreign_item) => intravisit::walk_foreign_item(self, foreign_item),
467 Node::OpaqueTy(opaq) => intravisit::walk_opaque_ty(self, opaq),
468 _ => ControlFlow::Continue(()),
469 };
470 self.repr_has_repr_simd = had_repr_simd;
471 self.repr_unconditionally_treats_fields_as_live = unconditionally_treated_fields_as_live;
472
473 walk_result
474 }
475
476 fn mark_as_used_if_union(&mut self, adt: ty::AdtDef<'tcx>, fields: &[hir::ExprField<'_>]) {
477 if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did().is_local() {
478 for field in fields {
479 let index = self.typeck_results().field_index(field.hir_id);
480 self.insert_def_id(adt.non_enum_variant().fields[index].did);
481 }
482 }
483 }
484
485 fn check_impl_or_impl_item_live(&mut self, local_def_id: LocalDefId) -> bool {
490 let (impl_block_id, trait_def_id) = match self.tcx.def_kind(local_def_id) {
491 DefKind::AssocConst | DefKind::AssocTy | DefKind::AssocFn => {
493 let trait_item_id =
494 self.tcx.trait_item_of(local_def_id).and_then(|def_id| def_id.as_local());
495 (self.tcx.local_parent(local_def_id), trait_item_id)
496 }
497 DefKind::Impl { of_trait: true } => {
499 (local_def_id, self.tcx.impl_trait_id(local_def_id).as_local())
500 }
501 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
502 };
503
504 if let Some(trait_def_id) = trait_def_id
505 && !self.live_symbols.contains(&trait_def_id)
506 {
507 return false;
508 }
509
510 if let ty::Adt(adt, _) = self.tcx.type_of(impl_block_id).instantiate_identity().kind()
512 && let Some(adt_def_id) = adt.did().as_local()
513 && !self.live_symbols.contains(&adt_def_id)
514 {
515 return false;
516 }
517
518 true
519 }
520}
521
522impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
523 type Result = ControlFlow<ErrorGuaranteed>;
524
525 fn visit_nested_body(&mut self, body: hir::BodyId) -> Self::Result {
526 let typeck_results = self.tcx.typeck_body(body);
527
528 if let Some(guar) = typeck_results.tainted_by_errors {
530 return ControlFlow::Break(guar);
531 }
532
533 let old_maybe_typeck_results = self.maybe_typeck_results.replace(typeck_results);
534 let body = self.tcx.hir_body(body);
535 let result = self.visit_body(body);
536 self.maybe_typeck_results = old_maybe_typeck_results;
537
538 result
539 }
540
541 fn visit_variant_data(&mut self, def: &'tcx hir::VariantData<'tcx>) -> Self::Result {
542 let tcx = self.tcx;
543 let unconditionally_treat_fields_as_live = self.repr_unconditionally_treats_fields_as_live;
544 let has_repr_simd = self.repr_has_repr_simd;
545 let effective_visibilities = &tcx.effective_visibilities(());
546 let live_fields = def.fields().iter().filter_map(|f| {
547 let def_id = f.def_id;
548 if unconditionally_treat_fields_as_live || (f.is_positional() && has_repr_simd) {
549 return Some(def_id);
550 }
551 if !effective_visibilities.is_reachable(f.hir_id.owner.def_id) {
552 return None;
553 }
554 if effective_visibilities.is_reachable(def_id) { Some(def_id) } else { None }
555 });
556 self.live_symbols.extend(live_fields);
557
558 intravisit::walk_struct_def(self, def)
559 }
560
561 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) -> Self::Result {
562 match expr.kind {
563 hir::ExprKind::Path(ref qpath @ QPath::TypeRelative(..)) => {
564 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
565 self.handle_res(res);
566 }
567 hir::ExprKind::MethodCall(..) => {
568 self.lookup_and_handle_method(expr.hir_id);
569 }
570 hir::ExprKind::Field(ref lhs, ..) => {
571 if self.typeck_results().opt_field_index(expr.hir_id).is_some() {
572 self.handle_field_access(lhs, expr.hir_id);
573 } else {
574 self.tcx.dcx().span_delayed_bug(expr.span, "couldn't resolve index for field");
575 }
576 }
577 hir::ExprKind::Struct(qpath, fields, _) => {
578 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
579 self.handle_res(res);
580 if let ty::Adt(adt, _) = self.typeck_results().expr_ty(expr).kind() {
581 self.mark_as_used_if_union(*adt, fields);
582 }
583 }
584 hir::ExprKind::Closure(cls) => {
585 self.insert_def_id(cls.def_id.to_def_id());
586 }
587 hir::ExprKind::OffsetOf(..) => {
588 self.handle_offset_of(expr);
589 }
590 hir::ExprKind::Assign(ref lhs, ..) => {
591 self.handle_assign(lhs);
592 self.check_for_self_assign(expr);
593 }
594 _ => (),
595 }
596
597 intravisit::walk_expr(self, expr)
598 }
599
600 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) -> Self::Result {
601 let len = self.ignore_variant_stack.len();
605 self.ignore_variant_stack.extend(arm.pat.necessary_variants());
606 let result = intravisit::walk_arm(self, arm);
607 self.ignore_variant_stack.truncate(len);
608
609 result
610 }
611
612 fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Self::Result {
613 self.in_pat = true;
614 match pat.kind {
615 PatKind::Struct(ref path, fields, _) => {
616 let res = self.typeck_results().qpath_res(path, pat.hir_id);
617 self.handle_field_pattern_match(pat, res, fields);
618 }
619 PatKind::TupleStruct(ref qpath, fields, dotdot) => {
620 let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
621 self.handle_tuple_field_pattern_match(pat, res, fields, dotdot);
622 }
623 _ => (),
624 }
625
626 let result = intravisit::walk_pat(self, pat);
627 self.in_pat = false;
628
629 result
630 }
631
632 fn visit_pat_expr(&mut self, expr: &'tcx rustc_hir::PatExpr<'tcx>) -> Self::Result {
633 match &expr.kind {
634 rustc_hir::PatExprKind::Path(qpath) => {
635 if let ty::Adt(adt, _) = self.typeck_results().node_type(expr.hir_id).kind() {
637 self.check_def_id(adt.did());
638 }
639
640 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
641 self.handle_res(res);
642 }
643 _ => {}
644 }
645 intravisit::walk_pat_expr(self, expr)
646 }
647
648 fn visit_path(&mut self, path: &hir::Path<'tcx>, _: hir::HirId) -> Self::Result {
649 self.handle_res(path.res);
650 intravisit::walk_path(self, path)
651 }
652
653 fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) -> Self::Result {
654 let in_pat = mem::replace(&mut self.in_pat, false);
657
658 self.live_symbols.insert(c.def_id);
659 let result = intravisit::walk_anon_const(self, c);
660
661 self.in_pat = in_pat;
662
663 result
664 }
665
666 fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) -> Self::Result {
667 let in_pat = mem::replace(&mut self.in_pat, false);
670
671 self.live_symbols.insert(c.def_id);
672 let result = intravisit::walk_inline_const(self, c);
673
674 self.in_pat = in_pat;
675
676 result
677 }
678
679 fn visit_trait_ref(&mut self, t: &'tcx hir::TraitRef<'tcx>) -> Self::Result {
680 if let Some(trait_def_id) = t.path.res.opt_def_id()
681 && let Some(segment) = t.path.segments.last()
682 && let Some(args) = segment.args
683 {
684 for constraint in args.constraints {
685 if let Some(local_def_id) = self
686 .tcx
687 .associated_items(trait_def_id)
688 .find_by_ident_and_kind(
689 self.tcx,
690 constraint.ident,
691 AssocTag::Const,
692 trait_def_id,
693 )
694 .and_then(|item| item.def_id.as_local())
695 {
696 self.worklist.push((local_def_id, ComesFromAllowExpect::No));
697 }
698 }
699 }
700
701 intravisit::walk_trait_ref(self, t)
702 }
703}
704
705fn has_allow_dead_code_or_lang_attr(
706 tcx: TyCtxt<'_>,
707 def_id: LocalDefId,
708) -> Option<ComesFromAllowExpect> {
709 fn has_lang_attr(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
710 tcx.has_attr(def_id, sym::lang)
711 || tcx.has_attr(def_id, sym::panic_handler)
713 }
714
715 fn has_allow_expect_dead_code(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
716 let hir_id = tcx.local_def_id_to_hir_id(def_id);
717 let lint_level = tcx.lint_level_at_node(lint::builtin::DEAD_CODE, hir_id).level;
718 #[allow(non_exhaustive_omitted_patterns)] match lint_level {
lint::Allow | lint::Expect => true,
_ => false,
}matches!(lint_level, lint::Allow | lint::Expect)
719 }
720
721 fn has_used_like_attr(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
722 tcx.def_kind(def_id).has_codegen_attrs() && {
723 let cg_attrs = tcx.codegen_fn_attrs(def_id);
724
725 cg_attrs.contains_extern_indicator()
728 || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)
729 || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)
730 }
731 }
732
733 if has_allow_expect_dead_code(tcx, def_id) {
734 Some(ComesFromAllowExpect::Yes)
735 } else if has_used_like_attr(tcx, def_id) || has_lang_attr(tcx, def_id) {
736 Some(ComesFromAllowExpect::No)
737 } else {
738 None
739 }
740}
741
742fn maybe_record_as_seed<'tcx>(
758 tcx: TyCtxt<'tcx>,
759 owner_id: hir::OwnerId,
760 worklist: &mut Vec<(LocalDefId, ComesFromAllowExpect)>,
761 unsolved_items: &mut Vec<LocalDefId>,
762) {
763 let allow_dead_code = has_allow_dead_code_or_lang_attr(tcx, owner_id.def_id);
764 if let Some(comes_from_allow) = allow_dead_code {
765 worklist.push((owner_id.def_id, comes_from_allow));
766 }
767
768 match tcx.def_kind(owner_id) {
769 DefKind::Enum => {
770 if let Some(comes_from_allow) = allow_dead_code {
771 let adt = tcx.adt_def(owner_id);
772 worklist.extend(
773 adt.variants()
774 .iter()
775 .map(|variant| (variant.def_id.expect_local(), comes_from_allow)),
776 );
777 }
778 }
779 DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy => {
780 if allow_dead_code.is_none() {
781 let parent = tcx.local_parent(owner_id.def_id);
782 match tcx.def_kind(parent) {
783 DefKind::Impl { of_trait: false } | DefKind::Trait => {}
784 DefKind::Impl { of_trait: true } => {
785 if let Some(trait_item_def_id) =
786 tcx.associated_item(owner_id.def_id).trait_item_def_id()
787 && let Some(trait_item_local_def_id) = trait_item_def_id.as_local()
788 && let Some(comes_from_allow) =
789 has_allow_dead_code_or_lang_attr(tcx, trait_item_local_def_id)
790 {
791 worklist.push((owner_id.def_id, comes_from_allow));
792 }
793
794 unsolved_items.push(owner_id.def_id);
800 }
801 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
802 }
803 }
804 }
805 DefKind::Impl { of_trait: true } => {
806 if allow_dead_code.is_none() {
807 if let Some(trait_def_id) =
808 tcx.impl_trait_ref(owner_id.def_id).skip_binder().def_id.as_local()
809 && let Some(comes_from_allow) =
810 has_allow_dead_code_or_lang_attr(tcx, trait_def_id)
811 {
812 worklist.push((owner_id.def_id, comes_from_allow));
813 }
814
815 unsolved_items.push(owner_id.def_id);
816 }
817 }
818 DefKind::GlobalAsm => {
819 worklist.push((owner_id.def_id, ComesFromAllowExpect::No));
821 }
822 DefKind::Const => {
823 if tcx.item_name(owner_id.def_id) == kw::Underscore {
824 worklist.push((owner_id.def_id, ComesFromAllowExpect::No));
828 }
829 }
830 _ => {}
831 }
832}
833
834fn create_and_seed_worklist(
835 tcx: TyCtxt<'_>,
836) -> (Vec<(LocalDefId, ComesFromAllowExpect)>, Vec<LocalDefId>) {
837 let effective_visibilities = &tcx.effective_visibilities(());
838 let mut unsolved_impl_item = Vec::new();
839 let mut worklist = effective_visibilities
840 .iter()
841 .filter_map(|(&id, effective_vis)| {
842 effective_vis
843 .is_public_at_level(Level::Reachable)
844 .then_some(id)
845 .map(|id| (id, ComesFromAllowExpect::No))
846 })
847 .chain(
849 tcx.entry_fn(())
850 .and_then(|(def_id, _)| def_id.as_local().map(|id| (id, ComesFromAllowExpect::No))),
851 )
852 .collect::<Vec<_>>();
853
854 let crate_items = tcx.hir_crate_items(());
855 for id in crate_items.owners() {
856 maybe_record_as_seed(tcx, id, &mut worklist, &mut unsolved_impl_item);
857 }
858
859 (worklist, unsolved_impl_item)
860}
861
862fn live_symbols_and_ignored_derived_traits(
863 tcx: TyCtxt<'_>,
864 (): (),
865) -> Result<(LocalDefIdSet, LocalDefIdMap<FxIndexSet<DefId>>), ErrorGuaranteed> {
866 let (worklist, mut unsolved_items) = create_and_seed_worklist(tcx);
867 let mut symbol_visitor = MarkSymbolVisitor {
868 worklist,
869 tcx,
870 maybe_typeck_results: None,
871 scanned: Default::default(),
872 live_symbols: Default::default(),
873 repr_unconditionally_treats_fields_as_live: false,
874 repr_has_repr_simd: false,
875 in_pat: false,
876 ignore_variant_stack: ::alloc::vec::Vec::new()vec![],
877 ignored_derived_traits: Default::default(),
878 };
879 if let ControlFlow::Break(guar) = symbol_visitor.mark_live_symbols() {
880 return Err(guar);
881 }
882
883 let mut items_to_check: Vec<_> = unsolved_items
886 .extract_if(.., |&mut local_def_id| {
887 symbol_visitor.check_impl_or_impl_item_live(local_def_id)
888 })
889 .collect();
890
891 while !items_to_check.is_empty() {
892 symbol_visitor
893 .worklist
894 .extend(items_to_check.drain(..).map(|id| (id, ComesFromAllowExpect::No)));
895 if let ControlFlow::Break(guar) = symbol_visitor.mark_live_symbols() {
896 return Err(guar);
897 }
898
899 items_to_check.extend(unsolved_items.extract_if(.., |&mut local_def_id| {
900 symbol_visitor.check_impl_or_impl_item_live(local_def_id)
901 }));
902 }
903
904 Ok((symbol_visitor.live_symbols, symbol_visitor.ignored_derived_traits))
905}
906
907struct DeadItem {
908 def_id: LocalDefId,
909 name: Symbol,
910 level: (lint::Level, Option<LintExpectationId>),
911}
912
913struct DeadVisitor<'tcx> {
914 tcx: TyCtxt<'tcx>,
915 live_symbols: &'tcx LocalDefIdSet,
916 ignored_derived_traits: &'tcx LocalDefIdMap<FxIndexSet<DefId>>,
917}
918
919enum ShouldWarnAboutField {
920 Yes,
921 No,
922}
923
924#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ReportOn {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ReportOn::TupleField => "TupleField",
ReportOn::NamedField => "NamedField",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for ReportOn { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ReportOn {
#[inline]
fn clone(&self) -> ReportOn { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ReportOn {
#[inline]
fn eq(&self, other: &ReportOn) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ReportOn {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {}
}Eq)]
925enum ReportOn {
926 TupleField,
928 NamedField,
930}
931
932impl<'tcx> DeadVisitor<'tcx> {
933 fn should_warn_about_field(&mut self, field: &ty::FieldDef) -> ShouldWarnAboutField {
934 if self.live_symbols.contains(&field.did.expect_local()) {
935 return ShouldWarnAboutField::No;
936 }
937 let field_type = self.tcx.type_of(field.did).instantiate_identity();
938 if field_type.is_phantom_data() {
939 return ShouldWarnAboutField::No;
940 }
941 let is_positional = field.name.as_str().starts_with(|c: char| c.is_ascii_digit());
942 if is_positional
943 && self
944 .tcx
945 .layout_of(
946 ty::TypingEnv::non_body_analysis(self.tcx, field.did)
947 .as_query_input(field_type),
948 )
949 .map_or(true, |layout| layout.is_zst())
950 {
951 return ShouldWarnAboutField::No;
952 }
953 ShouldWarnAboutField::Yes
954 }
955
956 fn def_lint_level(&self, id: LocalDefId) -> (lint::Level, Option<LintExpectationId>) {
957 let hir_id = self.tcx.local_def_id_to_hir_id(id);
958 let level = self.tcx.lint_level_at_node(DEAD_CODE, hir_id);
959 (level.level, level.lint_id)
960 }
961
962 fn lint_at_single_level(
969 &self,
970 dead_codes: &[&DeadItem],
971 participle: &str,
972 parent_item: Option<LocalDefId>,
973 report_on: ReportOn,
974 ) {
975 let Some(&first_item) = dead_codes.first() else { return };
976 let tcx = self.tcx;
977
978 let first_lint_level = first_item.level;
979 if !dead_codes.iter().skip(1).all(|item| item.level == first_lint_level) {
::core::panicking::panic("assertion failed: dead_codes.iter().skip(1).all(|item| item.level == first_lint_level)")
};assert!(dead_codes.iter().skip(1).all(|item| item.level == first_lint_level));
980
981 let names: Vec<_> = dead_codes.iter().map(|item| item.name).collect();
982 let spans: Vec<_> = dead_codes
983 .iter()
984 .map(|item| {
985 let span = tcx.def_span(item.def_id);
986 let ident_span = tcx.def_ident_span(item.def_id);
987 ident_span.map(|s| s.with_ctxt(span.ctxt())).unwrap_or(span)
989 })
990 .collect();
991
992 let mut descr = tcx.def_descr(first_item.def_id.to_def_id());
993 if dead_codes.iter().any(|item| tcx.def_descr(item.def_id.to_def_id()) != descr) {
996 descr = "associated item"
997 }
998
999 let num = dead_codes.len();
1000 let multiple = num > 6;
1001 let name_list = names.into();
1002
1003 let parent_info = parent_item.map(|parent_item| {
1004 let parent_descr = tcx.def_descr(parent_item.to_def_id());
1005 let span = if let DefKind::Impl { .. } = tcx.def_kind(parent_item) {
1006 tcx.def_span(parent_item)
1007 } else {
1008 tcx.def_ident_span(parent_item).unwrap()
1009 };
1010 ParentInfo { num, descr, parent_descr, span }
1011 });
1012
1013 let mut encl_def_id = parent_item.unwrap_or(first_item.def_id);
1014 if let DefKind::Variant = tcx.def_kind(encl_def_id) {
1016 encl_def_id = tcx.local_parent(encl_def_id);
1017 }
1018
1019 let ignored_derived_impls =
1020 self.ignored_derived_traits.get(&encl_def_id).map(|ign_traits| {
1021 let trait_list = ign_traits
1022 .iter()
1023 .map(|trait_id| self.tcx.item_name(*trait_id))
1024 .collect::<Vec<_>>();
1025 let trait_list_len = trait_list.len();
1026 IgnoredDerivedImpls {
1027 name: self.tcx.item_name(encl_def_id.to_def_id()),
1028 trait_list: trait_list.into(),
1029 trait_list_len,
1030 }
1031 });
1032
1033 let diag = match report_on {
1034 ReportOn::TupleField => {
1035 let tuple_fields = if let Some(parent_id) = parent_item
1036 && let node = tcx.hir_node_by_def_id(parent_id)
1037 && let hir::Node::Item(hir::Item {
1038 kind: hir::ItemKind::Struct(_, _, hir::VariantData::Tuple(fields, _, _)),
1039 ..
1040 }) = node
1041 {
1042 *fields
1043 } else {
1044 &[]
1045 };
1046
1047 let trailing_tuple_fields = if tuple_fields.len() >= dead_codes.len() {
1048 LocalDefIdSet::from_iter(
1049 tuple_fields
1050 .iter()
1051 .skip(tuple_fields.len() - dead_codes.len())
1052 .map(|f| f.def_id),
1053 )
1054 } else {
1055 LocalDefIdSet::default()
1056 };
1057
1058 let fields_suggestion =
1059 if dead_codes.iter().all(|dc| trailing_tuple_fields.contains(&dc.def_id)) {
1062 ChangeFields::Remove { num }
1063 } else {
1064 ChangeFields::ChangeToUnitTypeOrRemove { num, spans: spans.clone() }
1065 };
1066
1067 MultipleDeadCodes::UnusedTupleStructFields {
1068 multiple,
1069 num,
1070 descr,
1071 participle,
1072 name_list,
1073 change_fields_suggestion: fields_suggestion,
1074 parent_info,
1075 ignored_derived_impls,
1076 }
1077 }
1078 ReportOn::NamedField => {
1079 let enum_variants_with_same_name = dead_codes
1080 .iter()
1081 .filter_map(|dead_item| {
1082 if let DefKind::AssocFn | DefKind::AssocConst =
1083 tcx.def_kind(dead_item.def_id)
1084 && let impl_did = tcx.local_parent(dead_item.def_id)
1085 && let DefKind::Impl { of_trait: false } = tcx.def_kind(impl_did)
1086 && let ty::Adt(maybe_enum, _) =
1087 tcx.type_of(impl_did).instantiate_identity().kind()
1088 && maybe_enum.is_enum()
1089 && let Some(variant) =
1090 maybe_enum.variants().iter().find(|i| i.name == dead_item.name)
1091 {
1092 Some(crate::errors::EnumVariantSameName {
1093 dead_descr: tcx.def_descr(dead_item.def_id.to_def_id()),
1094 dead_name: dead_item.name,
1095 variant_span: tcx.def_span(variant.def_id),
1096 })
1097 } else {
1098 None
1099 }
1100 })
1101 .collect();
1102
1103 MultipleDeadCodes::DeadCodes {
1104 multiple,
1105 num,
1106 descr,
1107 participle,
1108 name_list,
1109 parent_info,
1110 ignored_derived_impls,
1111 enum_variants_with_same_name,
1112 }
1113 }
1114 };
1115
1116 let hir_id = tcx.local_def_id_to_hir_id(first_item.def_id);
1117 self.tcx.emit_node_span_lint(DEAD_CODE, hir_id, MultiSpan::from_spans(spans), diag);
1118 }
1119
1120 fn warn_multiple(
1121 &self,
1122 def_id: LocalDefId,
1123 participle: &str,
1124 dead_codes: Vec<DeadItem>,
1125 report_on: ReportOn,
1126 ) {
1127 let mut dead_codes = dead_codes
1128 .iter()
1129 .filter(|v| !v.name.as_str().starts_with('_'))
1130 .collect::<Vec<&DeadItem>>();
1131 if dead_codes.is_empty() {
1132 return;
1133 }
1134 dead_codes.sort_by_key(|v| v.level.0);
1136 for group in dead_codes.chunk_by(|a, b| a.level == b.level) {
1137 self.lint_at_single_level(&group, participle, Some(def_id), report_on);
1138 }
1139 }
1140
1141 fn warn_dead_code(&mut self, id: LocalDefId, participle: &str) {
1142 let item = DeadItem {
1143 def_id: id,
1144 name: self.tcx.item_name(id.to_def_id()),
1145 level: self.def_lint_level(id),
1146 };
1147 self.lint_at_single_level(&[&item], participle, None, ReportOn::NamedField);
1148 }
1149
1150 fn check_definition(&mut self, def_id: LocalDefId) {
1151 if self.is_live_code(def_id) {
1152 return;
1153 }
1154 match self.tcx.def_kind(def_id) {
1155 DefKind::AssocConst
1156 | DefKind::AssocTy
1157 | DefKind::AssocFn
1158 | DefKind::Fn
1159 | DefKind::Static { .. }
1160 | DefKind::Const
1161 | DefKind::TyAlias
1162 | DefKind::Enum
1163 | DefKind::Union
1164 | DefKind::ForeignTy
1165 | DefKind::Trait => self.warn_dead_code(def_id, "used"),
1166 DefKind::Struct => self.warn_dead_code(def_id, "constructed"),
1167 DefKind::Variant | DefKind::Field => ::rustc_middle::util::bug::bug_fmt(format_args!("should be handled specially"))bug!("should be handled specially"),
1168 _ => {}
1169 }
1170 }
1171
1172 fn is_live_code(&self, def_id: LocalDefId) -> bool {
1173 let Some(name) = self.tcx.opt_item_name(def_id.to_def_id()) else {
1176 return true;
1177 };
1178
1179 self.live_symbols.contains(&def_id) || name.as_str().starts_with('_')
1180 }
1181}
1182
1183fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalModDefId) {
1184 let Ok((live_symbols, ignored_derived_traits)) =
1185 tcx.live_symbols_and_ignored_derived_traits(()).as_ref()
1186 else {
1187 return;
1188 };
1189
1190 let mut visitor = DeadVisitor { tcx, live_symbols, ignored_derived_traits };
1191
1192 let module_items = tcx.hir_module_items(module);
1193
1194 for item in module_items.free_items() {
1195 let def_kind = tcx.def_kind(item.owner_id);
1196
1197 let mut dead_codes = Vec::new();
1198 if def_kind == (DefKind::Impl { of_trait: false })
1204 || (def_kind == DefKind::Trait && live_symbols.contains(&item.owner_id.def_id))
1205 {
1206 for &def_id in tcx.associated_item_def_ids(item.owner_id.def_id) {
1207 if let Some(local_def_id) = def_id.as_local()
1208 && !visitor.is_live_code(local_def_id)
1209 {
1210 let name = tcx.item_name(def_id);
1211 let level = visitor.def_lint_level(local_def_id);
1212 dead_codes.push(DeadItem { def_id: local_def_id, name, level });
1213 }
1214 }
1215 }
1216 if !dead_codes.is_empty() {
1217 visitor.warn_multiple(item.owner_id.def_id, "used", dead_codes, ReportOn::NamedField);
1218 }
1219
1220 if !live_symbols.contains(&item.owner_id.def_id) {
1221 let parent = tcx.local_parent(item.owner_id.def_id);
1222 if parent != module.to_local_def_id() && !live_symbols.contains(&parent) {
1223 continue;
1225 }
1226 visitor.check_definition(item.owner_id.def_id);
1227 continue;
1228 }
1229
1230 if let DefKind::Struct | DefKind::Union | DefKind::Enum = def_kind {
1231 let adt = tcx.adt_def(item.owner_id);
1232 let mut dead_variants = Vec::new();
1233
1234 for variant in adt.variants() {
1235 let def_id = variant.def_id.expect_local();
1236 if !live_symbols.contains(&def_id) {
1237 let level = visitor.def_lint_level(def_id);
1239 dead_variants.push(DeadItem { def_id, name: variant.name, level });
1240 continue;
1241 }
1242
1243 let is_positional = variant.fields.raw.first().is_some_and(|field| {
1244 field.name.as_str().starts_with(|c: char| c.is_ascii_digit())
1245 });
1246 let report_on =
1247 if is_positional { ReportOn::TupleField } else { ReportOn::NamedField };
1248 let dead_fields = variant
1249 .fields
1250 .iter()
1251 .filter_map(|field| {
1252 let def_id = field.did.expect_local();
1253 if let ShouldWarnAboutField::Yes = visitor.should_warn_about_field(field) {
1254 let level = visitor.def_lint_level(def_id);
1255 Some(DeadItem { def_id, name: field.name, level })
1256 } else {
1257 None
1258 }
1259 })
1260 .collect();
1261 visitor.warn_multiple(def_id, "read", dead_fields, report_on);
1262 }
1263
1264 visitor.warn_multiple(
1265 item.owner_id.def_id,
1266 "constructed",
1267 dead_variants,
1268 ReportOn::NamedField,
1269 );
1270 }
1271 }
1272
1273 for foreign_item in module_items.foreign_items() {
1274 visitor.check_definition(foreign_item.owner_id.def_id);
1275 }
1276}
1277
1278pub(crate) fn provide(providers: &mut Providers) {
1279 *providers =
1280 Providers { live_symbols_and_ignored_derived_traits, check_mod_deathness, ..*providers };
1281}