1 // This implements the dead-code warning pass. It follows middle::reachable
2 // closely. The idea is that all reachable symbols are live, codes called
3 // from live codes are live, and everything else is dead.
5 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
6 use rustc_errors::pluralize;
8 use rustc_hir::def::{CtorOf, DefKind, Res};
9 use rustc_hir::def_id::{DefId, LocalDefId};
10 use rustc_hir::intravisit::{self, Visitor};
11 use rustc_hir::{Node, PatKind, TyKind};
12 use rustc_middle::hir::nested_filter;
13 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
14 use rustc_middle::middle::privacy;
15 use rustc_middle::ty::query::Providers;
16 use rustc_middle::ty::{self, DefIdTree, TyCtxt};
17 use rustc_session::lint;
18 use rustc_span::symbol::{sym, Symbol};
22 // Any local node that may call something in its body block should be
23 // explored. For example, if it's a live Node::Item that is a
24 // function, then we should explore its block to check for codes that
25 // may need to be marked as live.
26 fn should_explore(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
28 tcx.hir().find_by_def_id(def_id),
32 | Node::ForeignItem(..)
40 struct MarkSymbolVisitor<'tcx> {
41 worklist: Vec<LocalDefId>,
43 maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
44 live_symbols: FxHashSet<LocalDefId>,
45 repr_has_repr_c: bool,
47 ignore_variant_stack: Vec<DefId>,
48 // maps from tuple struct constructors to tuple struct items
49 struct_constructors: FxHashMap<LocalDefId, LocalDefId>,
50 // maps from ADTs to ignored derived traits (e.g. Debug and Clone)
51 // and the span of their respective impl (i.e., part of the derive
53 ignored_derived_traits: FxHashMap<LocalDefId, Vec<(DefId, DefId)>>,
56 impl<'tcx> MarkSymbolVisitor<'tcx> {
57 /// Gets the type-checking results for the current body.
58 /// As this will ICE if called outside bodies, only call when working with
59 /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
61 fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
62 self.maybe_typeck_results
63 .expect("`MarkSymbolVisitor::typeck_results` called outside of body")
66 fn check_def_id(&mut self, def_id: DefId) {
67 if let Some(def_id) = def_id.as_local() {
68 if should_explore(self.tcx, def_id) || self.struct_constructors.contains_key(&def_id) {
69 self.worklist.push(def_id);
71 self.live_symbols.insert(def_id);
75 fn insert_def_id(&mut self, def_id: DefId) {
76 if let Some(def_id) = def_id.as_local() {
77 debug_assert!(!should_explore(self.tcx, def_id));
78 self.live_symbols.insert(def_id);
82 fn handle_res(&mut self, res: Res) {
84 Res::Def(DefKind::Const | DefKind::AssocConst | DefKind::TyAlias, _) => {
85 self.check_def_id(res.def_id());
87 _ if self.in_pat => {}
88 Res::PrimTy(..) | Res::SelfCtor(..) | Res::Local(..) => {}
89 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), ctor_def_id) => {
90 let variant_id = self.tcx.parent(ctor_def_id);
91 let enum_id = self.tcx.parent(variant_id);
92 self.check_def_id(enum_id);
93 if !self.ignore_variant_stack.contains(&ctor_def_id) {
94 self.check_def_id(variant_id);
97 Res::Def(DefKind::Variant, variant_id) => {
98 let enum_id = self.tcx.parent(variant_id);
99 self.check_def_id(enum_id);
100 if !self.ignore_variant_stack.contains(&variant_id) {
101 self.check_def_id(variant_id);
104 Res::SelfTy { trait_: t, alias_to: i } => {
106 self.check_def_id(t);
108 if let Some((i, _)) = i {
109 self.check_def_id(i);
112 Res::ToolMod | Res::NonMacroAttr(..) | Res::Err => {}
114 self.check_def_id(res.def_id());
119 fn lookup_and_handle_method(&mut self, id: hir::HirId) {
120 if let Some(def_id) = self.typeck_results().type_dependent_def_id(id) {
121 self.check_def_id(def_id);
123 bug!("no type-dependent def for method");
127 fn handle_field_access(&mut self, lhs: &hir::Expr<'_>, hir_id: hir::HirId) {
128 match self.typeck_results().expr_ty_adjusted(lhs).kind() {
130 let index = self.tcx.field_index(hir_id, self.typeck_results());
131 self.insert_def_id(def.non_enum_variant().fields[index].did);
134 _ => span_bug!(lhs.span, "named field access on non-ADT"),
138 #[allow(dead_code)] // FIXME(81658): should be used + lint reinstated after #83171 relands.
139 fn handle_assign(&mut self, expr: &'tcx hir::Expr<'tcx>) {
142 .expr_adjustments(expr)
144 .any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(_)))
146 self.visit_expr(expr);
147 } else if let hir::ExprKind::Field(base, ..) = expr.kind {
148 // Ignore write to field
149 self.handle_assign(base);
151 self.visit_expr(expr);
155 #[allow(dead_code)] // FIXME(81658): should be used + lint reinstated after #83171 relands.
156 fn check_for_self_assign(&mut self, assign: &'tcx hir::Expr<'tcx>) {
157 fn check_for_self_assign_helper<'tcx>(
158 typeck_results: &'tcx ty::TypeckResults<'tcx>,
159 lhs: &'tcx hir::Expr<'tcx>,
160 rhs: &'tcx hir::Expr<'tcx>,
162 match (&lhs.kind, &rhs.kind) {
163 (hir::ExprKind::Path(ref qpath_l), hir::ExprKind::Path(ref qpath_r)) => {
164 if let (Res::Local(id_l), Res::Local(id_r)) = (
165 typeck_results.qpath_res(qpath_l, lhs.hir_id),
166 typeck_results.qpath_res(qpath_r, rhs.hir_id),
174 (hir::ExprKind::Field(lhs_l, ident_l), hir::ExprKind::Field(lhs_r, ident_r)) => {
175 if ident_l == ident_r {
176 return check_for_self_assign_helper(typeck_results, lhs_l, lhs_r);
186 if let hir::ExprKind::Assign(lhs, rhs, _) = assign.kind {
187 if check_for_self_assign_helper(self.typeck_results(), lhs, rhs)
188 && !assign.span.from_expansion()
190 let is_field_assign = matches!(lhs.kind, hir::ExprKind::Field(..));
191 self.tcx.struct_span_lint_hir(
192 lint::builtin::DEAD_CODE,
197 "useless assignment of {} of type `{}` to itself",
198 if is_field_assign { "field" } else { "variable" },
199 self.typeck_results().expr_ty(lhs),
208 fn handle_field_pattern_match(
212 pats: &[hir::PatField<'_>],
214 let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
215 ty::Adt(adt, _) => adt.variant_of_res(res),
216 _ => span_bug!(lhs.span, "non-ADT in struct pattern"),
219 if let PatKind::Wild = pat.pat.kind {
222 let index = self.tcx.field_index(pat.hir_id, self.typeck_results());
223 self.insert_def_id(variant.fields[index].did);
227 fn mark_live_symbols(&mut self) {
228 let mut scanned = FxHashSet::default();
229 while let Some(id) = self.worklist.pop() {
230 if !scanned.insert(id) {
234 // in the case of tuple struct constructors we want to check the item, not the generated
235 // tuple struct constructor function
236 let id = self.struct_constructors.get(&id).copied().unwrap_or(id);
238 if let Some(node) = self.tcx.hir().find_by_def_id(id) {
239 self.live_symbols.insert(id);
240 self.visit_node(node);
245 /// Automatically generated items marked with `rustc_trivial_field_reads`
246 /// will be ignored for the purposes of dead code analysis (see PR #85200
248 fn should_ignore_item(&mut self, def_id: DefId) -> bool {
249 if let Some(impl_of) = self.tcx.impl_of_method(def_id) {
250 if !self.tcx.has_attr(impl_of, sym::automatically_derived) {
254 if let Some(trait_of) = self.tcx.trait_id_of_impl(impl_of) {
255 if self.tcx.has_attr(trait_of, sym::rustc_trivial_field_reads) {
256 let trait_ref = self.tcx.impl_trait_ref(impl_of).unwrap();
257 if let ty::Adt(adt_def, _) = trait_ref.self_ty().kind() {
258 if let Some(adt_def_id) = adt_def.did().as_local() {
259 self.ignored_derived_traits
262 .push((trait_of, impl_of));
273 fn visit_node(&mut self, node: Node<'tcx>) {
274 if let Some(item_def_id) = match node {
275 Node::ImplItem(hir::ImplItem { def_id, .. }) => Some(def_id.to_def_id()),
278 if self.should_ignore_item(item_def_id) {
283 let had_repr_c = self.repr_has_repr_c;
284 self.repr_has_repr_c = false;
286 Node::Item(item) => match item.kind {
287 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
288 let def = self.tcx.adt_def(item.def_id);
289 self.repr_has_repr_c = def.repr().c();
291 intravisit::walk_item(self, &item);
293 hir::ItemKind::Enum(..) => {
294 intravisit::walk_item(self, &item);
296 hir::ItemKind::ForeignMod { .. } => {}
298 intravisit::walk_item(self, &item);
301 Node::TraitItem(trait_item) => {
302 intravisit::walk_trait_item(self, trait_item);
304 Node::ImplItem(impl_item) => {
305 intravisit::walk_impl_item(self, impl_item);
307 Node::ForeignItem(foreign_item) => {
308 intravisit::walk_foreign_item(self, &foreign_item);
312 self.repr_has_repr_c = had_repr_c;
315 fn mark_as_used_if_union(&mut self, adt: ty::AdtDef<'tcx>, fields: &[hir::ExprField<'_>]) {
316 if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did().is_local() {
317 for field in fields {
318 let index = self.tcx.field_index(field.hir_id, self.typeck_results());
319 self.insert_def_id(adt.non_enum_variant().fields[index].did);
325 impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
326 fn visit_nested_body(&mut self, body: hir::BodyId) {
327 let old_maybe_typeck_results =
328 self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
329 let body = self.tcx.hir().body(body);
330 self.visit_body(body);
331 self.maybe_typeck_results = old_maybe_typeck_results;
334 fn visit_variant_data(
336 def: &'tcx hir::VariantData<'tcx>,
338 _: &hir::Generics<'_>,
343 let has_repr_c = self.repr_has_repr_c;
344 let live_fields = def.fields().iter().filter_map(|f| {
345 let def_id = tcx.hir().local_def_id(f.hir_id);
349 if !tcx.visibility(f.hir_id.owner).is_public() {
352 if tcx.visibility(def_id).is_public() { Some(def_id) } else { None }
354 self.live_symbols.extend(live_fields);
356 intravisit::walk_struct_def(self, def);
359 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
361 hir::ExprKind::Path(ref qpath @ hir::QPath::TypeRelative(..)) => {
362 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
363 self.handle_res(res);
365 hir::ExprKind::MethodCall(..) => {
366 self.lookup_and_handle_method(expr.hir_id);
368 hir::ExprKind::Field(ref lhs, ..) => {
369 self.handle_field_access(&lhs, expr.hir_id);
371 hir::ExprKind::Struct(ref qpath, ref fields, _) => {
372 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
373 self.handle_res(res);
374 if let ty::Adt(adt, _) = self.typeck_results().expr_ty(expr).kind() {
375 self.mark_as_used_if_union(*adt, fields);
381 intravisit::walk_expr(self, expr);
384 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
385 // Inside the body, ignore constructions of variants
386 // necessary for the pattern to match. Those construction sites
387 // can't be reached unless the variant is constructed elsewhere.
388 let len = self.ignore_variant_stack.len();
389 self.ignore_variant_stack.extend(arm.pat.necessary_variants());
390 intravisit::walk_arm(self, arm);
391 self.ignore_variant_stack.truncate(len);
394 fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
397 PatKind::Struct(ref path, ref fields, _) => {
398 let res = self.typeck_results().qpath_res(path, pat.hir_id);
399 self.handle_field_pattern_match(pat, res, fields);
401 PatKind::Path(ref qpath) => {
402 let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
403 self.handle_res(res);
408 intravisit::walk_pat(self, pat);
412 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
413 self.handle_res(path.res);
414 intravisit::walk_path(self, path);
417 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
418 if let TyKind::OpaqueDef(item_id, _) = ty.kind {
419 let item = self.tcx.hir().item(item_id);
420 intravisit::walk_item(self, item);
422 intravisit::walk_ty(self, ty);
425 fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
426 // When inline const blocks are used in pattern position, paths
427 // referenced by it should be considered as used.
428 let in_pat = mem::replace(&mut self.in_pat, false);
430 self.live_symbols.insert(self.tcx.hir().local_def_id(c.hir_id));
431 intravisit::walk_anon_const(self, c);
433 self.in_pat = in_pat;
437 fn has_allow_dead_code_or_lang_attr(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {
438 let attrs = tcx.hir().attrs(id);
439 if tcx.sess.contains_name(attrs, sym::lang) {
443 // Stable attribute for #[lang = "panic_impl"]
444 if tcx.sess.contains_name(attrs, sym::panic_handler) {
448 // (To be) stable attribute for #[lang = "oom"]
449 if tcx.sess.contains_name(attrs, sym::alloc_error_handler) {
453 let def_id = tcx.hir().local_def_id(id);
454 if tcx.def_kind(def_id).has_codegen_attrs() {
455 let cg_attrs = tcx.codegen_fn_attrs(def_id);
457 // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
458 // forcefully, e.g., for placing it in a specific section.
459 if cg_attrs.contains_extern_indicator()
460 || cg_attrs.flags.contains(CodegenFnAttrFlags::USED)
461 || cg_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)
467 tcx.lint_level_at_node(lint::builtin::DEAD_CODE, id).0 == lint::Allow
470 // These check_* functions seeds items that
471 // 1) We want to explicitly consider as live:
472 // * Item annotated with #[allow(dead_code)]
473 // - This is done so that if we want to suppress warnings for a
474 // group of dead functions, we only have to annotate the "root".
475 // For example, if both `f` and `g` are dead and `f` calls `g`,
476 // then annotating `f` with `#[allow(dead_code)]` will suppress
477 // warning for both `f` and `g`.
478 // * Item annotated with #[lang=".."]
479 // - This is because lang items are always callable from elsewhere.
481 // 2) We are not sure to be live or not
482 // * Implementations of traits and trait methods
485 worklist: &mut Vec<LocalDefId>,
486 struct_constructors: &mut FxHashMap<LocalDefId, LocalDefId>,
489 let allow_dead_code = has_allow_dead_code_or_lang_attr(tcx, id.hir_id());
491 worklist.push(id.def_id);
494 match tcx.hir().def_kind(id.def_id) {
496 let item = tcx.hir().item(id);
497 if let hir::ItemKind::Enum(ref enum_def, _) = item.kind {
501 enum_def.variants.iter().map(|variant| hir.local_def_id(variant.id)),
505 for variant in enum_def.variants {
506 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
508 .insert(hir.local_def_id(ctor_hir_id), hir.local_def_id(variant.id));
514 let item = tcx.hir().item(id);
515 if let hir::ItemKind::Impl(hir::Impl { ref of_trait, items, .. }) = item.kind {
516 if of_trait.is_some() {
517 worklist.push(item.def_id);
519 for impl_item_ref in *items {
520 let impl_item = tcx.hir().impl_item(impl_item_ref.id);
521 if of_trait.is_some()
522 || has_allow_dead_code_or_lang_attr(tcx, impl_item.hir_id())
524 worklist.push(impl_item_ref.id.def_id);
530 let item = tcx.hir().item(id);
531 if let hir::ItemKind::Struct(ref variant_data, _) = item.kind {
532 if let Some(ctor_hir_id) = variant_data.ctor_hir_id() {
533 struct_constructors.insert(tcx.hir().local_def_id(ctor_hir_id), item.def_id);
537 DefKind::GlobalAsm => {
538 // global_asm! is always live.
539 worklist.push(id.def_id);
545 fn check_trait_item<'tcx>(tcx: TyCtxt<'tcx>, worklist: &mut Vec<LocalDefId>, id: hir::TraitItemId) {
546 use hir::TraitItemKind::{Const, Fn};
547 if matches!(tcx.hir().def_kind(id.def_id), DefKind::AssocConst | DefKind::AssocFn) {
548 let trait_item = tcx.hir().trait_item(id);
549 if matches!(trait_item.kind, Const(_, Some(_)) | Fn(_, hir::TraitFn::Provided(_)))
550 && has_allow_dead_code_or_lang_attr(tcx, trait_item.hir_id())
552 worklist.push(trait_item.def_id);
557 fn check_foreign_item<'tcx>(
559 worklist: &mut Vec<LocalDefId>,
560 id: hir::ForeignItemId,
562 if matches!(tcx.hir().def_kind(id.def_id), DefKind::Static(_) | DefKind::Fn)
563 && has_allow_dead_code_or_lang_attr(tcx, id.hir_id())
565 worklist.push(id.def_id);
569 fn create_and_seed_worklist<'tcx>(
571 ) -> (Vec<LocalDefId>, FxHashMap<LocalDefId, LocalDefId>) {
572 let access_levels = &tcx.privacy_access_levels(());
573 // see `MarkSymbolVisitor::struct_constructors`
574 let mut struct_constructors = Default::default();
575 let mut worklist = access_levels
580 if level >= privacy::AccessLevel::Reachable { Some(id) } else { None }
584 .chain(tcx.entry_fn(()).and_then(|(def_id, _)| def_id.as_local()))
585 .collect::<Vec<_>>();
587 let crate_items = tcx.hir_crate_items(());
588 for id in crate_items.items() {
589 check_item(tcx, &mut worklist, &mut struct_constructors, id);
592 for id in crate_items.trait_items() {
593 check_trait_item(tcx, &mut worklist, id);
596 for id in crate_items.foreign_items() {
597 check_foreign_item(tcx, &mut worklist, id);
600 (worklist, struct_constructors)
603 fn live_symbols_and_ignored_derived_traits<'tcx>(
606 ) -> (FxHashSet<LocalDefId>, FxHashMap<LocalDefId, Vec<(DefId, DefId)>>) {
607 let (worklist, struct_constructors) = create_and_seed_worklist(tcx);
608 let mut symbol_visitor = MarkSymbolVisitor {
611 maybe_typeck_results: None,
612 live_symbols: Default::default(),
613 repr_has_repr_c: false,
615 ignore_variant_stack: vec![],
617 ignored_derived_traits: FxHashMap::default(),
619 symbol_visitor.mark_live_symbols();
620 (symbol_visitor.live_symbols, symbol_visitor.ignored_derived_traits)
623 struct DeadVisitor<'tcx> {
625 live_symbols: &'tcx FxHashSet<LocalDefId>,
626 ignored_derived_traits: &'tcx FxHashMap<LocalDefId, Vec<(DefId, DefId)>>,
629 impl<'tcx> DeadVisitor<'tcx> {
630 fn should_warn_about_item(&mut self, item: &hir::Item<'_>) -> bool {
631 let should_warn = matches!(
633 hir::ItemKind::Static(..)
634 | hir::ItemKind::Const(..)
635 | hir::ItemKind::Fn(..)
636 | hir::ItemKind::TyAlias(..)
637 | hir::ItemKind::Enum(..)
638 | hir::ItemKind::Struct(..)
639 | hir::ItemKind::Union(..)
641 should_warn && !self.symbol_is_live(item.def_id)
644 fn should_warn_about_field(&mut self, field: &hir::FieldDef<'_>) -> bool {
645 let def_id = self.tcx.hir().local_def_id(field.hir_id);
646 let field_type = self.tcx.type_of(def_id);
647 !field.is_positional()
648 && !self.symbol_is_live(def_id)
649 && !field_type.is_phantom_data()
650 && !has_allow_dead_code_or_lang_attr(self.tcx, field.hir_id)
653 fn should_warn_about_variant(&mut self, variant: &hir::Variant<'_>) -> bool {
654 let def_id = self.tcx.hir().local_def_id(variant.id);
655 !self.symbol_is_live(def_id) && !has_allow_dead_code_or_lang_attr(self.tcx, variant.id)
658 fn should_warn_about_foreign_item(&mut self, fi: &hir::ForeignItem<'_>) -> bool {
659 !self.symbol_is_live(fi.def_id) && !has_allow_dead_code_or_lang_attr(self.tcx, fi.hir_id())
662 // id := HIR id of an item's definition.
663 fn symbol_is_live(&mut self, def_id: LocalDefId) -> bool {
664 if self.live_symbols.contains(&def_id) {
667 // If it's a type whose items are live, then it's live, too.
668 // This is done to handle the case where, for example, the static
669 // method of a private type is used, but the type itself is never
671 let inherent_impls = self.tcx.inherent_impls(def_id);
672 for &impl_did in inherent_impls.iter() {
673 for item_did in self.tcx.associated_item_def_ids(impl_did) {
674 if let Some(def_id) = item_did.as_local() {
675 if self.live_symbols.contains(&def_id) {
687 span: rustc_span::Span,
691 if !name.as_str().starts_with('_') {
692 self.tcx.struct_span_lint_hir(lint::builtin::DEAD_CODE, id, span, |lint| {
693 let def_id = self.tcx.hir().local_def_id(id);
694 let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id());
695 let mut err = lint.build(&format!("{} is never {}: `{}`", descr, participle, name));
696 let hir = self.tcx.hir();
697 if let Some(encl_scope) = hir.get_enclosing_scope(id)
698 && let Some(encl_def_id) = hir.opt_local_def_id(encl_scope)
699 && let Some(ign_traits) = self.ignored_derived_traits.get(&encl_def_id)
701 let traits_str = ign_traits
703 .map(|(trait_id, _)| format!("`{}`", self.tcx.item_name(*trait_id)))
706 let plural_s = pluralize!(ign_traits.len());
707 let article = if ign_traits.len() > 1 { "" } else { "a " };
708 let is_are = if ign_traits.len() > 1 { "these are" } else { "this is" };
710 "`{}` has {}derived impl{} for the trait{} {}, but {} \
711 intentionally ignored during dead code analysis",
712 self.tcx.item_name(encl_def_id.to_def_id()),
719 let multispan = ign_traits
721 .map(|(_, impl_id)| self.tcx.def_span(*impl_id))
722 .collect::<Vec<_>>();
723 err.span_note(multispan, &msg);
731 impl<'tcx> Visitor<'tcx> for DeadVisitor<'tcx> {
732 type NestedFilter = nested_filter::All;
734 /// Walk nested items in place so that we don't report dead-code
735 /// on inner functions when the outer function is already getting
736 /// an error. We could do this also by checking the parents, but
737 /// this is how the code is setup and it seems harmless enough.
738 fn nested_visit_map(&mut self) -> Self::Map {
742 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
743 if self.should_warn_about_item(item) {
744 // For most items, we want to highlight its identifier
745 let span = match item.kind {
746 hir::ItemKind::Fn(..)
747 | hir::ItemKind::Mod(..)
748 | hir::ItemKind::Enum(..)
749 | hir::ItemKind::Struct(..)
750 | hir::ItemKind::Union(..)
751 | hir::ItemKind::Trait(..)
752 | hir::ItemKind::Impl { .. } => {
753 // FIXME(66095): Because item.span is annotated with things
754 // like expansion data, and ident.span isn't, we use the
755 // def_span method if it's part of a macro invocation
756 // (and thus has a source_callee set).
757 // We should probably annotate ident.span with the macro
758 // context, but that's a larger change.
759 if item.span.source_callee().is_some() {
760 self.tcx.sess.source_map().guess_head_span(item.span)
767 let participle = match item.kind {
768 hir::ItemKind::Struct(..) => "constructed", // Issue #52325
771 self.warn_dead_code(item.hir_id(), span, item.ident.name, participle);
773 // Only continue if we didn't warn
774 intravisit::walk_item(self, item);
778 // This visitor should only visit a single module at a time.
779 fn visit_mod(&mut self, _: &'tcx hir::Mod<'tcx>, _: Span, _: hir::HirId) {}
783 variant: &'tcx hir::Variant<'tcx>,
784 g: &'tcx hir::Generics<'tcx>,
787 if self.should_warn_about_variant(&variant) {
788 self.warn_dead_code(variant.id, variant.span, variant.ident.name, "constructed");
790 intravisit::walk_variant(self, variant, g, id);
794 fn visit_foreign_item(&mut self, fi: &'tcx hir::ForeignItem<'tcx>) {
795 if self.should_warn_about_foreign_item(fi) {
796 self.warn_dead_code(fi.hir_id(), fi.span, fi.ident.name, "used");
798 intravisit::walk_foreign_item(self, fi);
801 fn visit_field_def(&mut self, field: &'tcx hir::FieldDef<'tcx>) {
802 if self.should_warn_about_field(&field) {
803 self.warn_dead_code(field.hir_id, field.span, field.ident.name, "read");
805 intravisit::walk_field_def(self, field);
808 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
809 match impl_item.kind {
810 hir::ImplItemKind::Const(_, body_id) => {
811 if !self.symbol_is_live(impl_item.def_id) {
815 impl_item.ident.name,
819 self.visit_nested_body(body_id)
821 hir::ImplItemKind::Fn(_, body_id) => {
822 if !self.symbol_is_live(impl_item.def_id) {
823 // FIXME(66095): Because impl_item.span is annotated with things
824 // like expansion data, and ident.span isn't, we use the
825 // def_span method if it's part of a macro invocation
826 // (and thus has a source_callee set).
827 // We should probably annotate ident.span with the macro
828 // context, but that's a larger change.
829 let span = if impl_item.span.source_callee().is_some() {
830 self.tcx.sess.source_map().guess_head_span(impl_item.span)
834 self.warn_dead_code(impl_item.hir_id(), span, impl_item.ident.name, "used");
836 self.visit_nested_body(body_id)
838 hir::ImplItemKind::TyAlias(..) => {}
842 // Overwrite so that we don't warn the trait item itself.
843 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
844 match trait_item.kind {
845 hir::TraitItemKind::Const(_, Some(body_id))
846 | hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(body_id)) => {
847 self.visit_nested_body(body_id)
849 hir::TraitItemKind::Const(_, None)
850 | hir::TraitItemKind::Fn(_, hir::TraitFn::Required(_))
851 | hir::TraitItemKind::Type(..) => {}
856 fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalDefId) {
857 let (live_symbols, ignored_derived_traits) = tcx.live_symbols_and_ignored_derived_traits(());
858 let mut visitor = DeadVisitor { tcx, live_symbols, ignored_derived_traits };
859 let (module, _, module_id) = tcx.hir().get_module(module);
860 // Do not use an ItemLikeVisitor since we may want to skip visiting some items
861 // when a surrounding one is warned against or `_`.
862 intravisit::walk_mod(&mut visitor, module, module_id);
865 pub(crate) fn provide(providers: &mut Providers) {
867 Providers { live_symbols_and_ignored_derived_traits, check_mod_deathness, ..*providers };