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::itemlikevisit::ItemLikeVisitor;
12 use rustc_hir::{Node, PatKind, TyKind};
13 use rustc_middle::hir::nested_filter;
14 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
15 use rustc_middle::middle::privacy;
16 use rustc_middle::ty::query::Providers;
17 use rustc_middle::ty::{self, DefIdTree, TyCtxt};
18 use rustc_session::lint;
19 use rustc_span::symbol::{sym, Symbol};
23 // Any local node that may call something in its body block should be
24 // explored. For example, if it's a live Node::Item that is a
25 // function, then we should explore its block to check for codes that
26 // may need to be marked as live.
27 fn should_explore(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
29 tcx.hir().find_by_def_id(def_id),
33 | Node::ForeignItem(..)
41 struct MarkSymbolVisitor<'tcx> {
42 worklist: Vec<LocalDefId>,
44 maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
45 live_symbols: FxHashSet<LocalDefId>,
46 repr_has_repr_c: bool,
48 inherited_pub_visibility: bool,
50 ignore_variant_stack: Vec<DefId>,
51 // maps from tuple struct constructors to tuple struct items
52 struct_constructors: FxHashMap<LocalDefId, LocalDefId>,
53 // maps from ADTs to ignored derived traits (e.g. Debug and Clone)
54 // and the span of their respective impl (i.e., part of the derive
56 ignored_derived_traits: FxHashMap<LocalDefId, Vec<(DefId, DefId)>>,
59 impl<'tcx> MarkSymbolVisitor<'tcx> {
60 /// Gets the type-checking results for the current body.
61 /// As this will ICE if called outside bodies, only call when working with
62 /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
64 fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
65 self.maybe_typeck_results
66 .expect("`MarkSymbolVisitor::typeck_results` called outside of body")
69 fn check_def_id(&mut self, def_id: DefId) {
70 if let Some(def_id) = def_id.as_local() {
71 if should_explore(self.tcx, def_id) || self.struct_constructors.contains_key(&def_id) {
72 self.worklist.push(def_id);
74 self.live_symbols.insert(def_id);
78 fn insert_def_id(&mut self, def_id: DefId) {
79 if let Some(def_id) = def_id.as_local() {
80 debug_assert!(!should_explore(self.tcx, def_id));
81 self.live_symbols.insert(def_id);
85 fn handle_res(&mut self, res: Res) {
87 Res::Def(DefKind::Const | DefKind::AssocConst | DefKind::TyAlias, _) => {
88 self.check_def_id(res.def_id());
90 _ if self.in_pat => {}
91 Res::PrimTy(..) | Res::SelfCtor(..) | Res::Local(..) => {}
92 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), ctor_def_id) => {
93 let variant_id = self.tcx.parent(ctor_def_id).unwrap();
94 let enum_id = self.tcx.parent(variant_id).unwrap();
95 self.check_def_id(enum_id);
96 if !self.ignore_variant_stack.contains(&ctor_def_id) {
97 self.check_def_id(variant_id);
100 Res::Def(DefKind::Variant, variant_id) => {
101 let enum_id = self.tcx.parent(variant_id).unwrap();
102 self.check_def_id(enum_id);
103 if !self.ignore_variant_stack.contains(&variant_id) {
104 self.check_def_id(variant_id);
107 Res::SelfTy(t, i) => {
109 self.check_def_id(t);
111 if let Some((i, _)) = i {
112 self.check_def_id(i);
115 Res::ToolMod | Res::NonMacroAttr(..) | Res::Err => {}
117 self.check_def_id(res.def_id());
122 fn lookup_and_handle_method(&mut self, id: hir::HirId) {
123 if let Some(def_id) = self.typeck_results().type_dependent_def_id(id) {
124 self.check_def_id(def_id);
126 bug!("no type-dependent def for method");
130 fn handle_field_access(&mut self, lhs: &hir::Expr<'_>, hir_id: hir::HirId) {
131 match self.typeck_results().expr_ty_adjusted(lhs).kind() {
133 let index = self.tcx.field_index(hir_id, self.typeck_results());
134 self.insert_def_id(def.non_enum_variant().fields[index].did);
137 _ => span_bug!(lhs.span, "named field access on non-ADT"),
141 #[allow(dead_code)] // FIXME(81658): should be used + lint reinstated after #83171 relands.
142 fn handle_assign(&mut self, expr: &'tcx hir::Expr<'tcx>) {
145 .expr_adjustments(expr)
147 .any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(_)))
149 self.visit_expr(expr);
150 } else if let hir::ExprKind::Field(base, ..) = expr.kind {
151 // Ignore write to field
152 self.handle_assign(base);
154 self.visit_expr(expr);
158 #[allow(dead_code)] // FIXME(81658): should be used + lint reinstated after #83171 relands.
159 fn check_for_self_assign(&mut self, assign: &'tcx hir::Expr<'tcx>) {
160 fn check_for_self_assign_helper<'tcx>(
162 typeck_results: &'tcx ty::TypeckResults<'tcx>,
163 lhs: &'tcx hir::Expr<'tcx>,
164 rhs: &'tcx hir::Expr<'tcx>,
166 match (&lhs.kind, &rhs.kind) {
167 (hir::ExprKind::Path(ref qpath_l), hir::ExprKind::Path(ref qpath_r)) => {
168 if let (Res::Local(id_l), Res::Local(id_r)) = (
169 typeck_results.qpath_res(qpath_l, lhs.hir_id),
170 typeck_results.qpath_res(qpath_r, rhs.hir_id),
178 (hir::ExprKind::Field(lhs_l, ident_l), hir::ExprKind::Field(lhs_r, ident_r)) => {
179 if ident_l == ident_r {
180 return check_for_self_assign_helper(tcx, typeck_results, lhs_l, lhs_r);
190 if let hir::ExprKind::Assign(lhs, rhs, _) = assign.kind {
191 if check_for_self_assign_helper(self.tcx, self.typeck_results(), lhs, rhs)
192 && !assign.span.from_expansion()
194 let is_field_assign = matches!(lhs.kind, hir::ExprKind::Field(..));
195 self.tcx.struct_span_lint_hir(
196 lint::builtin::DEAD_CODE,
201 "useless assignment of {} of type `{}` to itself",
202 if is_field_assign { "field" } else { "variable" },
203 self.typeck_results().expr_ty(lhs),
212 fn handle_field_pattern_match(
216 pats: &[hir::PatField<'_>],
218 let variant = match self.typeck_results().node_type(lhs.hir_id).kind() {
219 ty::Adt(adt, _) => adt.variant_of_res(res),
220 _ => span_bug!(lhs.span, "non-ADT in struct pattern"),
223 if let PatKind::Wild = pat.pat.kind {
226 let index = self.tcx.field_index(pat.hir_id, self.typeck_results());
227 self.insert_def_id(variant.fields[index].did);
231 fn mark_live_symbols(&mut self) {
232 let mut scanned = FxHashSet::default();
233 while let Some(id) = self.worklist.pop() {
234 if !scanned.insert(id) {
238 // in the case of tuple struct constructors we want to check the item, not the generated
239 // tuple struct constructor function
240 let id = self.struct_constructors.get(&id).copied().unwrap_or(id);
242 if let Some(node) = self.tcx.hir().find_by_def_id(id) {
243 self.live_symbols.insert(id);
244 self.visit_node(node);
249 /// Automatically generated items marked with `rustc_trivial_field_reads`
250 /// will be ignored for the purposes of dead code analysis (see PR #85200
252 fn should_ignore_item(&mut self, def_id: DefId) -> bool {
253 if let Some(impl_of) = self.tcx.impl_of_method(def_id) {
254 if !self.tcx.has_attr(impl_of, sym::automatically_derived) {
258 if let Some(trait_of) = self.tcx.trait_id_of_impl(impl_of) {
259 if self.tcx.has_attr(trait_of, sym::rustc_trivial_field_reads) {
260 let trait_ref = self.tcx.impl_trait_ref(impl_of).unwrap();
261 if let ty::Adt(adt_def, _) = trait_ref.self_ty().kind() {
262 if let Some(adt_def_id) = adt_def.did.as_local() {
263 self.ignored_derived_traits
266 .push((trait_of, impl_of));
277 fn visit_node(&mut self, node: Node<'tcx>) {
278 if let Some(item_def_id) = match node {
279 Node::ImplItem(hir::ImplItem { def_id, .. }) => Some(def_id.to_def_id()),
282 if self.should_ignore_item(item_def_id) {
287 let had_repr_c = self.repr_has_repr_c;
288 let had_inherited_pub_visibility = self.inherited_pub_visibility;
289 let had_pub_visibility = self.pub_visibility;
290 self.repr_has_repr_c = false;
291 self.inherited_pub_visibility = false;
292 self.pub_visibility = false;
294 Node::Item(item) => {
295 self.pub_visibility = item.vis.node.is_pub();
298 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
299 let def = self.tcx.adt_def(item.def_id);
300 self.repr_has_repr_c = def.repr.c();
302 intravisit::walk_item(self, &item);
304 hir::ItemKind::Enum(..) => {
305 self.inherited_pub_visibility = self.pub_visibility;
307 intravisit::walk_item(self, &item);
309 hir::ItemKind::ForeignMod { .. } => {}
311 intravisit::walk_item(self, &item);
315 Node::TraitItem(trait_item) => {
316 intravisit::walk_trait_item(self, trait_item);
318 Node::ImplItem(impl_item) => {
319 intravisit::walk_impl_item(self, impl_item);
321 Node::ForeignItem(foreign_item) => {
322 intravisit::walk_foreign_item(self, &foreign_item);
326 self.pub_visibility = had_pub_visibility;
327 self.inherited_pub_visibility = had_inherited_pub_visibility;
328 self.repr_has_repr_c = had_repr_c;
331 fn mark_as_used_if_union(&mut self, adt: &ty::AdtDef, fields: &[hir::ExprField<'_>]) {
332 if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did.is_local() {
333 for field in fields {
334 let index = self.tcx.field_index(field.hir_id, self.typeck_results());
335 self.insert_def_id(adt.non_enum_variant().fields[index].did);
341 impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
342 fn visit_nested_body(&mut self, body: hir::BodyId) {
343 let old_maybe_typeck_results =
344 self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
345 let body = self.tcx.hir().body(body);
346 self.visit_body(body);
347 self.maybe_typeck_results = old_maybe_typeck_results;
350 fn visit_variant_data(
352 def: &'tcx hir::VariantData<'tcx>,
354 _: &hir::Generics<'_>,
358 let has_repr_c = self.repr_has_repr_c;
359 let inherited_pub_visibility = self.inherited_pub_visibility;
360 let pub_visibility = self.pub_visibility;
361 let live_fields = def.fields().iter().filter(|f| {
362 has_repr_c || (pub_visibility && (inherited_pub_visibility || f.vis.node.is_pub()))
364 let hir = self.tcx.hir();
365 self.live_symbols.extend(live_fields.map(|f| hir.local_def_id(f.hir_id)));
367 intravisit::walk_struct_def(self, def);
370 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
372 hir::ExprKind::Path(ref qpath @ hir::QPath::TypeRelative(..)) => {
373 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
374 self.handle_res(res);
376 hir::ExprKind::MethodCall(..) => {
377 self.lookup_and_handle_method(expr.hir_id);
379 hir::ExprKind::Field(ref lhs, ..) => {
380 self.handle_field_access(&lhs, expr.hir_id);
382 hir::ExprKind::Struct(ref qpath, ref fields, _) => {
383 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
384 self.handle_res(res);
385 if let ty::Adt(ref adt, _) = self.typeck_results().expr_ty(expr).kind() {
386 self.mark_as_used_if_union(adt, fields);
392 intravisit::walk_expr(self, expr);
395 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
396 // Inside the body, ignore constructions of variants
397 // necessary for the pattern to match. Those construction sites
398 // can't be reached unless the variant is constructed elsewhere.
399 let len = self.ignore_variant_stack.len();
400 self.ignore_variant_stack.extend(arm.pat.necessary_variants());
401 intravisit::walk_arm(self, arm);
402 self.ignore_variant_stack.truncate(len);
405 fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
408 PatKind::Struct(ref path, ref fields, _) => {
409 let res = self.typeck_results().qpath_res(path, pat.hir_id);
410 self.handle_field_pattern_match(pat, res, fields);
412 PatKind::Path(ref qpath) => {
413 let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
414 self.handle_res(res);
419 intravisit::walk_pat(self, pat);
423 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
424 self.handle_res(path.res);
425 intravisit::walk_path(self, path);
428 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
429 if let TyKind::OpaqueDef(item_id, _) = ty.kind {
430 let item = self.tcx.hir().item(item_id);
431 intravisit::walk_item(self, item);
433 intravisit::walk_ty(self, ty);
436 fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
437 // When inline const blocks are used in pattern position, paths
438 // referenced by it should be considered as used.
439 let in_pat = mem::replace(&mut self.in_pat, false);
441 self.live_symbols.insert(self.tcx.hir().local_def_id(c.hir_id));
442 intravisit::walk_anon_const(self, c);
444 self.in_pat = in_pat;
448 fn has_allow_dead_code_or_lang_attr(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {
449 let attrs = tcx.hir().attrs(id);
450 if tcx.sess.contains_name(attrs, sym::lang) {
454 // Stable attribute for #[lang = "panic_impl"]
455 if tcx.sess.contains_name(attrs, sym::panic_handler) {
459 // (To be) stable attribute for #[lang = "oom"]
460 if tcx.sess.contains_name(attrs, sym::alloc_error_handler) {
464 let def_id = tcx.hir().local_def_id(id);
465 let cg_attrs = tcx.codegen_fn_attrs(def_id);
467 // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
468 // forcefully, e.g., for placing it in a specific section.
469 if cg_attrs.contains_extern_indicator() || cg_attrs.flags.contains(CodegenFnAttrFlags::USED) {
473 tcx.lint_level_at_node(lint::builtin::DEAD_CODE, id).0 == lint::Allow
476 // This visitor seeds items that
477 // 1) We want to explicitly consider as live:
478 // * Item annotated with #[allow(dead_code)]
479 // - This is done so that if we want to suppress warnings for a
480 // group of dead functions, we only have to annotate the "root".
481 // For example, if both `f` and `g` are dead and `f` calls `g`,
482 // then annotating `f` with `#[allow(dead_code)]` will suppress
483 // warning for both `f` and `g`.
484 // * Item annotated with #[lang=".."]
485 // - This is because lang items are always callable from elsewhere.
487 // 2) We are not sure to be live or not
488 // * Implementations of traits and trait methods
489 struct LifeSeeder<'tcx> {
490 worklist: Vec<LocalDefId>,
492 // see `MarkSymbolVisitor::struct_constructors`
493 struct_constructors: FxHashMap<LocalDefId, LocalDefId>,
496 impl<'v, 'tcx> ItemLikeVisitor<'v> for LifeSeeder<'tcx> {
497 fn visit_item(&mut self, item: &hir::Item<'_>) {
498 let allow_dead_code = has_allow_dead_code_or_lang_attr(self.tcx, item.hir_id());
500 self.worklist.push(item.def_id);
503 hir::ItemKind::Enum(ref enum_def, _) => {
504 let hir = self.tcx.hir();
506 self.worklist.extend(
507 enum_def.variants.iter().map(|variant| hir.local_def_id(variant.id)),
511 for variant in enum_def.variants {
512 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
513 self.struct_constructors
514 .insert(hir.local_def_id(ctor_hir_id), hir.local_def_id(variant.id));
518 hir::ItemKind::Impl(hir::Impl { ref of_trait, items, .. }) => {
519 if of_trait.is_some() {
520 self.worklist.push(item.def_id);
522 for impl_item_ref in items {
523 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
524 if of_trait.is_some()
525 || has_allow_dead_code_or_lang_attr(self.tcx, impl_item.hir_id())
527 self.worklist.push(impl_item_ref.id.def_id);
531 hir::ItemKind::Struct(ref variant_data, _) => {
532 if let Some(ctor_hir_id) = variant_data.ctor_hir_id() {
533 self.struct_constructors
534 .insert(self.tcx.hir().local_def_id(ctor_hir_id), item.def_id);
541 fn visit_trait_item(&mut self, trait_item: &hir::TraitItem<'_>) {
542 use hir::TraitItemKind::{Const, Fn};
543 if matches!(trait_item.kind, Const(_, Some(_)) | Fn(_, hir::TraitFn::Provided(_)))
544 && has_allow_dead_code_or_lang_attr(self.tcx, trait_item.hir_id())
546 self.worklist.push(trait_item.def_id);
550 fn visit_impl_item(&mut self, _item: &hir::ImplItem<'_>) {
551 // ignore: we are handling this in `visit_item` above
554 fn visit_foreign_item(&mut self, foreign_item: &hir::ForeignItem<'_>) {
555 use hir::ForeignItemKind::{Fn, Static};
556 if matches!(foreign_item.kind, Static(..) | Fn(..))
557 && has_allow_dead_code_or_lang_attr(self.tcx, foreign_item.hir_id())
559 self.worklist.push(foreign_item.def_id);
564 fn create_and_seed_worklist<'tcx>(
566 ) -> (Vec<LocalDefId>, FxHashMap<LocalDefId, LocalDefId>) {
567 let access_levels = &tcx.privacy_access_levels(());
568 let worklist = access_levels
573 if level >= privacy::AccessLevel::Reachable { Some(id) } else { None }
577 .chain(tcx.entry_fn(()).and_then(|(def_id, _)| def_id.as_local()))
578 .collect::<Vec<_>>();
580 // Seed implemented trait items
581 let mut life_seeder = LifeSeeder { worklist, tcx, struct_constructors: Default::default() };
582 tcx.hir().visit_all_item_likes(&mut life_seeder);
584 (life_seeder.worklist, life_seeder.struct_constructors)
587 fn live_symbols_and_ignored_derived_traits<'tcx>(
590 ) -> (FxHashSet<LocalDefId>, FxHashMap<LocalDefId, Vec<(DefId, DefId)>>) {
591 let (worklist, struct_constructors) = create_and_seed_worklist(tcx);
592 let mut symbol_visitor = MarkSymbolVisitor {
595 maybe_typeck_results: None,
596 live_symbols: Default::default(),
597 repr_has_repr_c: false,
599 inherited_pub_visibility: false,
600 pub_visibility: false,
601 ignore_variant_stack: vec![],
603 ignored_derived_traits: FxHashMap::default(),
605 symbol_visitor.mark_live_symbols();
606 (symbol_visitor.live_symbols, symbol_visitor.ignored_derived_traits)
609 struct DeadVisitor<'tcx> {
611 live_symbols: &'tcx FxHashSet<LocalDefId>,
612 ignored_derived_traits: &'tcx FxHashMap<LocalDefId, Vec<(DefId, DefId)>>,
615 impl<'tcx> DeadVisitor<'tcx> {
616 fn should_warn_about_item(&mut self, item: &hir::Item<'_>) -> bool {
617 let should_warn = matches!(
619 hir::ItemKind::Static(..)
620 | hir::ItemKind::Const(..)
621 | hir::ItemKind::Fn(..)
622 | hir::ItemKind::TyAlias(..)
623 | hir::ItemKind::Enum(..)
624 | hir::ItemKind::Struct(..)
625 | hir::ItemKind::Union(..)
627 should_warn && !self.symbol_is_live(item.def_id)
630 fn should_warn_about_field(&mut self, field: &hir::FieldDef<'_>) -> bool {
631 let def_id = self.tcx.hir().local_def_id(field.hir_id);
632 let field_type = self.tcx.type_of(def_id);
633 !field.is_positional()
634 && !self.symbol_is_live(def_id)
635 && !field_type.is_phantom_data()
636 && !has_allow_dead_code_or_lang_attr(self.tcx, field.hir_id)
639 fn should_warn_about_variant(&mut self, variant: &hir::Variant<'_>) -> bool {
640 let def_id = self.tcx.hir().local_def_id(variant.id);
641 !self.symbol_is_live(def_id) && !has_allow_dead_code_or_lang_attr(self.tcx, variant.id)
644 fn should_warn_about_foreign_item(&mut self, fi: &hir::ForeignItem<'_>) -> bool {
645 !self.symbol_is_live(fi.def_id) && !has_allow_dead_code_or_lang_attr(self.tcx, fi.hir_id())
648 // id := HIR id of an item's definition.
649 fn symbol_is_live(&mut self, def_id: LocalDefId) -> bool {
650 if self.live_symbols.contains(&def_id) {
653 // If it's a type whose items are live, then it's live, too.
654 // This is done to handle the case where, for example, the static
655 // method of a private type is used, but the type itself is never
657 let inherent_impls = self.tcx.inherent_impls(def_id);
658 for &impl_did in inherent_impls.iter() {
659 for item_did in self.tcx.associated_item_def_ids(impl_did) {
660 if let Some(def_id) = item_did.as_local() {
661 if self.live_symbols.contains(&def_id) {
673 span: rustc_span::Span,
677 if !name.as_str().starts_with('_') {
678 self.tcx.struct_span_lint_hir(lint::builtin::DEAD_CODE, id, span, |lint| {
679 let def_id = self.tcx.hir().local_def_id(id);
680 let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id());
681 let mut err = lint.build(&format!("{} is never {}: `{}`", descr, participle, name));
682 let hir = self.tcx.hir();
683 if let Some(encl_scope) = hir.get_enclosing_scope(id) {
684 if let Some(encl_def_id) = hir.opt_local_def_id(encl_scope) {
685 if let Some(ign_traits) = self.ignored_derived_traits.get(&encl_def_id) {
686 let traits_str = ign_traits
688 .map(|(trait_id, _)| format!("`{}`", self.tcx.item_name(*trait_id)))
691 let plural_s = pluralize!(ign_traits.len());
692 let article = if ign_traits.len() > 1 { "" } else { "a " };
693 let is_are = if ign_traits.len() > 1 { "these are" } else { "this is" };
695 "`{}` has {}derived impl{} for the trait{} {}, but {} \
696 intentionally ignored during dead code analysis",
697 self.tcx.item_name(encl_def_id.to_def_id()),
704 let multispan = ign_traits
706 .map(|(_, impl_id)| self.tcx.def_span(*impl_id))
707 .collect::<Vec<_>>();
708 err.span_note(multispan, &msg);
718 impl<'tcx> Visitor<'tcx> for DeadVisitor<'tcx> {
719 type NestedFilter = nested_filter::All;
721 /// Walk nested items in place so that we don't report dead-code
722 /// on inner functions when the outer function is already getting
723 /// an error. We could do this also by checking the parents, but
724 /// this is how the code is setup and it seems harmless enough.
725 fn nested_visit_map(&mut self) -> Self::Map {
729 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
730 if self.should_warn_about_item(item) {
731 // For most items, we want to highlight its identifier
732 let span = match item.kind {
733 hir::ItemKind::Fn(..)
734 | hir::ItemKind::Mod(..)
735 | hir::ItemKind::Enum(..)
736 | hir::ItemKind::Struct(..)
737 | hir::ItemKind::Union(..)
738 | hir::ItemKind::Trait(..)
739 | hir::ItemKind::Impl { .. } => {
740 // FIXME(66095): Because item.span is annotated with things
741 // like expansion data, and ident.span isn't, we use the
742 // def_span method if it's part of a macro invocation
743 // (and thus has a source_callee set).
744 // We should probably annotate ident.span with the macro
745 // context, but that's a larger change.
746 if item.span.source_callee().is_some() {
747 self.tcx.sess.source_map().guess_head_span(item.span)
754 let participle = match item.kind {
755 hir::ItemKind::Struct(..) => "constructed", // Issue #52325
758 self.warn_dead_code(item.hir_id(), span, item.ident.name, participle);
760 // Only continue if we didn't warn
761 intravisit::walk_item(self, item);
765 // This visitor should only visit a single module at a time.
766 fn visit_mod(&mut self, _: &'tcx hir::Mod<'tcx>, _: Span, _: hir::HirId) {}
770 variant: &'tcx hir::Variant<'tcx>,
771 g: &'tcx hir::Generics<'tcx>,
774 if self.should_warn_about_variant(&variant) {
775 self.warn_dead_code(variant.id, variant.span, variant.ident.name, "constructed");
777 intravisit::walk_variant(self, variant, g, id);
781 fn visit_foreign_item(&mut self, fi: &'tcx hir::ForeignItem<'tcx>) {
782 if self.should_warn_about_foreign_item(fi) {
783 self.warn_dead_code(fi.hir_id(), fi.span, fi.ident.name, "used");
785 intravisit::walk_foreign_item(self, fi);
788 fn visit_field_def(&mut self, field: &'tcx hir::FieldDef<'tcx>) {
789 if self.should_warn_about_field(&field) {
790 self.warn_dead_code(field.hir_id, field.span, field.ident.name, "read");
792 intravisit::walk_field_def(self, field);
795 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
796 match impl_item.kind {
797 hir::ImplItemKind::Const(_, body_id) => {
798 if !self.symbol_is_live(impl_item.def_id) {
802 impl_item.ident.name,
806 self.visit_nested_body(body_id)
808 hir::ImplItemKind::Fn(_, body_id) => {
809 if !self.symbol_is_live(impl_item.def_id) {
810 // FIXME(66095): Because impl_item.span is annotated with things
811 // like expansion data, and ident.span isn't, we use the
812 // def_span method if it's part of a macro invocation
813 // (and thus has a source_callee set).
814 // We should probably annotate ident.span with the macro
815 // context, but that's a larger change.
816 let span = if impl_item.span.source_callee().is_some() {
817 self.tcx.sess.source_map().guess_head_span(impl_item.span)
821 self.warn_dead_code(impl_item.hir_id(), span, impl_item.ident.name, "used");
823 self.visit_nested_body(body_id)
825 hir::ImplItemKind::TyAlias(..) => {}
829 // Overwrite so that we don't warn the trait item itself.
830 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
831 match trait_item.kind {
832 hir::TraitItemKind::Const(_, Some(body_id))
833 | hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(body_id)) => {
834 self.visit_nested_body(body_id)
836 hir::TraitItemKind::Const(_, None)
837 | hir::TraitItemKind::Fn(_, hir::TraitFn::Required(_))
838 | hir::TraitItemKind::Type(..) => {}
843 fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalDefId) {
844 let (live_symbols, ignored_derived_traits) = tcx.live_symbols_and_ignored_derived_traits(());
845 let mut visitor = DeadVisitor { tcx, live_symbols, ignored_derived_traits };
846 let (module, _, module_id) = tcx.hir().get_module(module);
847 // Do not use an ItemLikeVisitor since we may want to skip visiting some items
848 // when a surrounding one is warned against or `_`.
849 intravisit::walk_mod(&mut visitor, module, module_id);
852 pub(crate) fn provide(providers: &mut Providers) {
854 Providers { live_symbols_and_ignored_derived_traits, check_mod_deathness, ..*providers };