]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_passes/src/dead.rs
Move `{core,std}::stream::Stream` to `{core,std}::async_iter::AsyncIterator`.
[rust.git] / compiler / rustc_passes / src / dead.rs
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.
4
5 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
6 use rustc_errors::pluralize;
7 use rustc_hir as hir;
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};
20 use rustc_span::Span;
21 use std::mem;
22
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 {
28     matches!(
29         tcx.hir().find_by_def_id(def_id),
30         Some(
31             Node::Item(..)
32                 | Node::ImplItem(..)
33                 | Node::ForeignItem(..)
34                 | Node::TraitItem(..)
35                 | Node::Variant(..)
36                 | Node::AnonConst(..)
37         )
38     )
39 }
40
41 struct MarkSymbolVisitor<'tcx> {
42     worklist: Vec<LocalDefId>,
43     tcx: TyCtxt<'tcx>,
44     maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
45     live_symbols: FxHashSet<LocalDefId>,
46     repr_has_repr_c: bool,
47     in_pat: bool,
48     inherited_pub_visibility: bool,
49     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
55     // macro)
56     ignored_derived_traits: FxHashMap<LocalDefId, Vec<(DefId, DefId)>>,
57 }
58
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).
63     #[track_caller]
64     fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
65         self.maybe_typeck_results
66             .expect("`MarkSymbolVisitor::typeck_results` called outside of body")
67     }
68
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);
73             }
74             self.live_symbols.insert(def_id);
75         }
76     }
77
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);
82         }
83     }
84
85     fn handle_res(&mut self, res: Res) {
86         match res {
87             Res::Def(DefKind::Const | DefKind::AssocConst | DefKind::TyAlias, _) => {
88                 self.check_def_id(res.def_id());
89             }
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);
98                 }
99             }
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);
105                 }
106             }
107             Res::SelfTy(t, i) => {
108                 if let Some(t) = t {
109                     self.check_def_id(t);
110                 }
111                 if let Some((i, _)) = i {
112                     self.check_def_id(i);
113                 }
114             }
115             Res::ToolMod | Res::NonMacroAttr(..) | Res::Err => {}
116             _ => {
117                 self.check_def_id(res.def_id());
118             }
119         }
120     }
121
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);
125         } else {
126             bug!("no type-dependent def for method");
127         }
128     }
129
130     fn handle_field_access(&mut self, lhs: &hir::Expr<'_>, hir_id: hir::HirId) {
131         match self.typeck_results().expr_ty_adjusted(lhs).kind() {
132             ty::Adt(def, _) => {
133                 let index = self.tcx.field_index(hir_id, self.typeck_results());
134                 self.insert_def_id(def.non_enum_variant().fields[index].did);
135             }
136             ty::Tuple(..) => {}
137             _ => span_bug!(lhs.span, "named field access on non-ADT"),
138         }
139     }
140
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>) {
143         if self
144             .typeck_results()
145             .expr_adjustments(expr)
146             .iter()
147             .any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(_)))
148         {
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);
153         } else {
154             self.visit_expr(expr);
155         }
156     }
157
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>(
161             tcx: TyCtxt<'tcx>,
162             typeck_results: &'tcx ty::TypeckResults<'tcx>,
163             lhs: &'tcx hir::Expr<'tcx>,
164             rhs: &'tcx hir::Expr<'tcx>,
165         ) -> bool {
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),
171                     ) {
172                         if id_l == id_r {
173                             return true;
174                         }
175                     }
176                     return false;
177                 }
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);
181                     }
182                     return false;
183                 }
184                 _ => {
185                     return false;
186                 }
187             }
188         }
189
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()
193             {
194                 let is_field_assign = matches!(lhs.kind, hir::ExprKind::Field(..));
195                 self.tcx.struct_span_lint_hir(
196                     lint::builtin::DEAD_CODE,
197                     assign.hir_id,
198                     assign.span,
199                     |lint| {
200                         lint.build(&format!(
201                             "useless assignment of {} of type `{}` to itself",
202                             if is_field_assign { "field" } else { "variable" },
203                             self.typeck_results().expr_ty(lhs),
204                         ))
205                         .emit();
206                     },
207                 )
208             }
209         }
210     }
211
212     fn handle_field_pattern_match(
213         &mut self,
214         lhs: &hir::Pat<'_>,
215         res: Res,
216         pats: &[hir::PatField<'_>],
217     ) {
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"),
221         };
222         for pat in pats {
223             if let PatKind::Wild = pat.pat.kind {
224                 continue;
225             }
226             let index = self.tcx.field_index(pat.hir_id, self.typeck_results());
227             self.insert_def_id(variant.fields[index].did);
228         }
229     }
230
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) {
235                 continue;
236             }
237
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);
241
242             if let Some(node) = self.tcx.hir().find_by_def_id(id) {
243                 self.live_symbols.insert(id);
244                 self.visit_node(node);
245             }
246         }
247     }
248
249     /// Automatically generated items marked with `rustc_trivial_field_reads`
250     /// will be ignored for the purposes of dead code analysis (see PR #85200
251     /// for discussion).
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) {
255                 return false;
256             }
257
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
264                                 .entry(adt_def_id)
265                                 .or_default()
266                                 .push((trait_of, impl_of));
267                         }
268                     }
269                     return true;
270                 }
271             }
272         }
273
274         return false;
275     }
276
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()),
280             _ => None,
281         } {
282             if self.should_ignore_item(item_def_id) {
283                 return;
284             }
285         }
286
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;
293         match node {
294             Node::Item(item) => {
295                 self.pub_visibility = item.vis.node.is_pub();
296
297                 match item.kind {
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();
301
302                         intravisit::walk_item(self, &item);
303                     }
304                     hir::ItemKind::Enum(..) => {
305                         self.inherited_pub_visibility = self.pub_visibility;
306
307                         intravisit::walk_item(self, &item);
308                     }
309                     hir::ItemKind::ForeignMod { .. } => {}
310                     _ => {
311                         intravisit::walk_item(self, &item);
312                     }
313                 }
314             }
315             Node::TraitItem(trait_item) => {
316                 intravisit::walk_trait_item(self, trait_item);
317             }
318             Node::ImplItem(impl_item) => {
319                 intravisit::walk_impl_item(self, impl_item);
320             }
321             Node::ForeignItem(foreign_item) => {
322                 intravisit::walk_foreign_item(self, &foreign_item);
323             }
324             _ => {}
325         }
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;
329     }
330
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);
336             }
337         }
338     }
339 }
340
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;
348     }
349
350     fn visit_variant_data(
351         &mut self,
352         def: &'tcx hir::VariantData<'tcx>,
353         _: Symbol,
354         _: &hir::Generics<'_>,
355         _: hir::HirId,
356         _: rustc_span::Span,
357     ) {
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()))
363         });
364         let hir = self.tcx.hir();
365         self.live_symbols.extend(live_fields.map(|f| hir.local_def_id(f.hir_id)));
366
367         intravisit::walk_struct_def(self, def);
368     }
369
370     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
371         match expr.kind {
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);
375             }
376             hir::ExprKind::MethodCall(..) => {
377                 self.lookup_and_handle_method(expr.hir_id);
378             }
379             hir::ExprKind::Field(ref lhs, ..) => {
380                 self.handle_field_access(&lhs, expr.hir_id);
381             }
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);
387                 }
388             }
389             _ => (),
390         }
391
392         intravisit::walk_expr(self, expr);
393     }
394
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);
403     }
404
405     fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
406         self.in_pat = true;
407         match pat.kind {
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);
411             }
412             PatKind::Path(ref qpath) => {
413                 let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
414                 self.handle_res(res);
415             }
416             _ => (),
417         }
418
419         intravisit::walk_pat(self, pat);
420         self.in_pat = false;
421     }
422
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);
426     }
427
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);
432         }
433         intravisit::walk_ty(self, ty);
434     }
435
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);
440
441         self.live_symbols.insert(self.tcx.hir().local_def_id(c.hir_id));
442         intravisit::walk_anon_const(self, c);
443
444         self.in_pat = in_pat;
445     }
446 }
447
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) {
451         return true;
452     }
453
454     // Stable attribute for #[lang = "panic_impl"]
455     if tcx.sess.contains_name(attrs, sym::panic_handler) {
456         return true;
457     }
458
459     // (To be) stable attribute for #[lang = "oom"]
460     if tcx.sess.contains_name(attrs, sym::alloc_error_handler) {
461         return true;
462     }
463
464     let def_id = tcx.hir().local_def_id(id);
465     let cg_attrs = tcx.codegen_fn_attrs(def_id);
466
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) {
470         return true;
471     }
472
473     tcx.lint_level_at_node(lint::builtin::DEAD_CODE, id).0 == lint::Allow
474 }
475
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.
486 //   or
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>,
491     tcx: TyCtxt<'tcx>,
492     // see `MarkSymbolVisitor::struct_constructors`
493     struct_constructors: FxHashMap<LocalDefId, LocalDefId>,
494 }
495
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());
499         if allow_dead_code {
500             self.worklist.push(item.def_id);
501         }
502         match item.kind {
503             hir::ItemKind::Enum(ref enum_def, _) => {
504                 let hir = self.tcx.hir();
505                 if allow_dead_code {
506                     self.worklist.extend(
507                         enum_def.variants.iter().map(|variant| hir.local_def_id(variant.id)),
508                     );
509                 }
510
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));
515                     }
516                 }
517             }
518             hir::ItemKind::Impl(hir::Impl { ref of_trait, items, .. }) => {
519                 if of_trait.is_some() {
520                     self.worklist.push(item.def_id);
521                 }
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())
526                     {
527                         self.worklist.push(impl_item_ref.id.def_id);
528                     }
529                 }
530             }
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);
535                 }
536             }
537             _ => (),
538         }
539     }
540
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())
545         {
546             self.worklist.push(trait_item.def_id);
547         }
548     }
549
550     fn visit_impl_item(&mut self, _item: &hir::ImplItem<'_>) {
551         // ignore: we are handling this in `visit_item` above
552     }
553
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())
558         {
559             self.worklist.push(foreign_item.def_id);
560         }
561     }
562 }
563
564 fn create_and_seed_worklist<'tcx>(
565     tcx: TyCtxt<'tcx>,
566 ) -> (Vec<LocalDefId>, FxHashMap<LocalDefId, LocalDefId>) {
567     let access_levels = &tcx.privacy_access_levels(());
568     let worklist = access_levels
569         .map
570         .iter()
571         .filter_map(
572             |(&id, &level)| {
573                 if level >= privacy::AccessLevel::Reachable { Some(id) } else { None }
574             },
575         )
576         // Seed entry point
577         .chain(tcx.entry_fn(()).and_then(|(def_id, _)| def_id.as_local()))
578         .collect::<Vec<_>>();
579
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);
583
584     (life_seeder.worklist, life_seeder.struct_constructors)
585 }
586
587 fn live_symbols_and_ignored_derived_traits<'tcx>(
588     tcx: TyCtxt<'tcx>,
589     (): (),
590 ) -> (FxHashSet<LocalDefId>, FxHashMap<LocalDefId, Vec<(DefId, DefId)>>) {
591     let (worklist, struct_constructors) = create_and_seed_worklist(tcx);
592     let mut symbol_visitor = MarkSymbolVisitor {
593         worklist,
594         tcx,
595         maybe_typeck_results: None,
596         live_symbols: Default::default(),
597         repr_has_repr_c: false,
598         in_pat: false,
599         inherited_pub_visibility: false,
600         pub_visibility: false,
601         ignore_variant_stack: vec![],
602         struct_constructors,
603         ignored_derived_traits: FxHashMap::default(),
604     };
605     symbol_visitor.mark_live_symbols();
606     (symbol_visitor.live_symbols, symbol_visitor.ignored_derived_traits)
607 }
608
609 struct DeadVisitor<'tcx> {
610     tcx: TyCtxt<'tcx>,
611     live_symbols: &'tcx FxHashSet<LocalDefId>,
612     ignored_derived_traits: &'tcx FxHashMap<LocalDefId, Vec<(DefId, DefId)>>,
613 }
614
615 impl<'tcx> DeadVisitor<'tcx> {
616     fn should_warn_about_item(&mut self, item: &hir::Item<'_>) -> bool {
617         let should_warn = matches!(
618             item.kind,
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(..)
626         );
627         should_warn && !self.symbol_is_live(item.def_id)
628     }
629
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)
637     }
638
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)
642     }
643
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())
646     }
647
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) {
651             return true;
652         }
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
656         // called directly.
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) {
662                         return true;
663                     }
664                 }
665             }
666         }
667         false
668     }
669
670     fn warn_dead_code(
671         &mut self,
672         id: hir::HirId,
673         span: rustc_span::Span,
674         name: Symbol,
675         participle: &str,
676     ) {
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
687                                 .iter()
688                                 .map(|(trait_id, _)| format!("`{}`", self.tcx.item_name(*trait_id)))
689                                 .collect::<Vec<_>>()
690                                 .join(" and ");
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" };
694                             let msg = format!(
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()),
698                                 article,
699                                 plural_s,
700                                 plural_s,
701                                 traits_str,
702                                 is_are
703                             );
704                             let multispan = ign_traits
705                                 .iter()
706                                 .map(|(_, impl_id)| self.tcx.def_span(*impl_id))
707                                 .collect::<Vec<_>>();
708                             err.span_note(multispan, &msg);
709                         }
710                     }
711                 }
712                 err.emit();
713             });
714         }
715     }
716 }
717
718 impl<'tcx> Visitor<'tcx> for DeadVisitor<'tcx> {
719     type NestedFilter = nested_filter::All;
720
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 {
726         self.tcx.hir()
727     }
728
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)
748                     } else {
749                         item.ident.span
750                     }
751                 }
752                 _ => item.span,
753             };
754             let participle = match item.kind {
755                 hir::ItemKind::Struct(..) => "constructed", // Issue #52325
756                 _ => "used",
757             };
758             self.warn_dead_code(item.hir_id(), span, item.ident.name, participle);
759         } else {
760             // Only continue if we didn't warn
761             intravisit::walk_item(self, item);
762         }
763     }
764
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) {}
767
768     fn visit_variant(
769         &mut self,
770         variant: &'tcx hir::Variant<'tcx>,
771         g: &'tcx hir::Generics<'tcx>,
772         id: hir::HirId,
773     ) {
774         if self.should_warn_about_variant(&variant) {
775             self.warn_dead_code(variant.id, variant.span, variant.ident.name, "constructed");
776         } else {
777             intravisit::walk_variant(self, variant, g, id);
778         }
779     }
780
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");
784         }
785         intravisit::walk_foreign_item(self, fi);
786     }
787
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");
791         }
792         intravisit::walk_field_def(self, field);
793     }
794
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) {
799                     self.warn_dead_code(
800                         impl_item.hir_id(),
801                         impl_item.span,
802                         impl_item.ident.name,
803                         "used",
804                     );
805                 }
806                 self.visit_nested_body(body_id)
807             }
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)
818                     } else {
819                         impl_item.ident.span
820                     };
821                     self.warn_dead_code(impl_item.hir_id(), span, impl_item.ident.name, "used");
822                 }
823                 self.visit_nested_body(body_id)
824             }
825             hir::ImplItemKind::TyAlias(..) => {}
826         }
827     }
828
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)
835             }
836             hir::TraitItemKind::Const(_, None)
837             | hir::TraitItemKind::Fn(_, hir::TraitFn::Required(_))
838             | hir::TraitItemKind::Type(..) => {}
839         }
840     }
841 }
842
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);
850 }
851
852 pub(crate) fn provide(providers: &mut Providers) {
853     *providers =
854         Providers { live_symbols_and_ignored_derived_traits, check_mod_deathness, ..*providers };
855 }