]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/dead.rs
Rollup merge of #67873 - Dylan-DPC:feature/change-remove-to-partial, r=Amanieu
[rust.git] / src / librustc_passes / 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::hir::intravisit::{self, NestedVisitorMap, Visitor};
6 use rustc::hir::itemlikevisit::ItemLikeVisitor;
7 use rustc::hir::Node;
8 use rustc::hir::{self, PatKind, TyKind};
9
10 use rustc::hir::def::{CtorOf, DefKind, Res};
11 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
12 use rustc::lint;
13 use rustc::middle::codegen_fn_attrs::CodegenFnAttrFlags;
14 use rustc::middle::privacy;
15 use rustc::ty::{self, DefIdTree, TyCtxt};
16 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
17
18 use rustc_span;
19 use rustc_span::symbol::sym;
20 use syntax::{ast, attr};
21
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<'_>, hir_id: hir::HirId) -> bool {
27     match tcx.hir().find(hir_id) {
28         Some(Node::Item(..))
29         | Some(Node::ImplItem(..))
30         | Some(Node::ForeignItem(..))
31         | Some(Node::TraitItem(..))
32         | Some(Node::Variant(..))
33         | Some(Node::AnonConst(..))
34         | Some(Node::Pat(..)) => true,
35         _ => false,
36     }
37 }
38
39 struct MarkSymbolVisitor<'a, 'tcx> {
40     worklist: Vec<hir::HirId>,
41     tcx: TyCtxt<'tcx>,
42     tables: &'a ty::TypeckTables<'tcx>,
43     live_symbols: FxHashSet<hir::HirId>,
44     repr_has_repr_c: bool,
45     in_pat: bool,
46     inherited_pub_visibility: bool,
47     ignore_variant_stack: Vec<DefId>,
48     // maps from tuple struct constructors to tuple struct items
49     struct_constructors: FxHashMap<hir::HirId, hir::HirId>,
50 }
51
52 impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> {
53     fn check_def_id(&mut self, def_id: DefId) {
54         if let Some(hir_id) = self.tcx.hir().as_local_hir_id(def_id) {
55             if should_explore(self.tcx, hir_id) || self.struct_constructors.contains_key(&hir_id) {
56                 self.worklist.push(hir_id);
57             }
58             self.live_symbols.insert(hir_id);
59         }
60     }
61
62     fn insert_def_id(&mut self, def_id: DefId) {
63         if let Some(hir_id) = self.tcx.hir().as_local_hir_id(def_id) {
64             debug_assert!(!should_explore(self.tcx, hir_id));
65             self.live_symbols.insert(hir_id);
66         }
67     }
68
69     fn handle_res(&mut self, res: Res) {
70         match res {
71             Res::Def(DefKind::Const, _)
72             | Res::Def(DefKind::AssocConst, _)
73             | Res::Def(DefKind::TyAlias, _) => {
74                 self.check_def_id(res.def_id());
75             }
76             _ if self.in_pat => {}
77             Res::PrimTy(..) | Res::SelfCtor(..) | Res::Local(..) => {}
78             Res::Def(DefKind::Ctor(CtorOf::Variant, ..), ctor_def_id) => {
79                 let variant_id = self.tcx.parent(ctor_def_id).unwrap();
80                 let enum_id = self.tcx.parent(variant_id).unwrap();
81                 self.check_def_id(enum_id);
82                 if !self.ignore_variant_stack.contains(&ctor_def_id) {
83                     self.check_def_id(variant_id);
84                 }
85             }
86             Res::Def(DefKind::Variant, variant_id) => {
87                 let enum_id = self.tcx.parent(variant_id).unwrap();
88                 self.check_def_id(enum_id);
89                 if !self.ignore_variant_stack.contains(&variant_id) {
90                     self.check_def_id(variant_id);
91                 }
92             }
93             Res::SelfTy(t, i) => {
94                 if let Some(t) = t {
95                     self.check_def_id(t);
96                 }
97                 if let Some(i) = i {
98                     self.check_def_id(i);
99                 }
100             }
101             Res::ToolMod | Res::NonMacroAttr(..) | Res::Err => {}
102             _ => {
103                 self.check_def_id(res.def_id());
104             }
105         }
106     }
107
108     fn lookup_and_handle_method(&mut self, id: hir::HirId) {
109         if let Some(def_id) = self.tables.type_dependent_def_id(id) {
110             self.check_def_id(def_id);
111         } else {
112             bug!("no type-dependent def for method");
113         }
114     }
115
116     fn handle_field_access(&mut self, lhs: &hir::Expr<'_>, hir_id: hir::HirId) {
117         match self.tables.expr_ty_adjusted(lhs).kind {
118             ty::Adt(def, _) => {
119                 let index = self.tcx.field_index(hir_id, self.tables);
120                 self.insert_def_id(def.non_enum_variant().fields[index].did);
121             }
122             ty::Tuple(..) => {}
123             _ => span_bug!(lhs.span, "named field access on non-ADT"),
124         }
125     }
126
127     fn handle_field_pattern_match(
128         &mut self,
129         lhs: &hir::Pat<'_>,
130         res: Res,
131         pats: &[hir::FieldPat<'_>],
132     ) {
133         let variant = match self.tables.node_type(lhs.hir_id).kind {
134             ty::Adt(adt, _) => adt.variant_of_res(res),
135             _ => span_bug!(lhs.span, "non-ADT in struct pattern"),
136         };
137         for pat in pats {
138             if let PatKind::Wild = pat.pat.kind {
139                 continue;
140             }
141             let index = self.tcx.field_index(pat.hir_id, self.tables);
142             self.insert_def_id(variant.fields[index].did);
143         }
144     }
145
146     fn mark_live_symbols(&mut self) {
147         let mut scanned = FxHashSet::default();
148         while let Some(id) = self.worklist.pop() {
149             if !scanned.insert(id) {
150                 continue;
151             }
152
153             // in the case of tuple struct constructors we want to check the item, not the generated
154             // tuple struct constructor function
155             let id = self.struct_constructors.get(&id).cloned().unwrap_or(id);
156
157             if let Some(node) = self.tcx.hir().find(id) {
158                 self.live_symbols.insert(id);
159                 self.visit_node(node);
160             }
161         }
162     }
163
164     fn visit_node(&mut self, node: Node<'tcx>) {
165         let had_repr_c = self.repr_has_repr_c;
166         self.repr_has_repr_c = false;
167         let had_inherited_pub_visibility = self.inherited_pub_visibility;
168         self.inherited_pub_visibility = false;
169         match node {
170             Node::Item(item) => match item.kind {
171                 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
172                     let def_id = self.tcx.hir().local_def_id(item.hir_id);
173                     let def = self.tcx.adt_def(def_id);
174                     self.repr_has_repr_c = def.repr.c();
175
176                     intravisit::walk_item(self, &item);
177                 }
178                 hir::ItemKind::Enum(..) => {
179                     self.inherited_pub_visibility = item.vis.node.is_pub();
180
181                     intravisit::walk_item(self, &item);
182                 }
183                 hir::ItemKind::ForeignMod(..) => {}
184                 _ => {
185                     intravisit::walk_item(self, &item);
186                 }
187             },
188             Node::TraitItem(trait_item) => {
189                 intravisit::walk_trait_item(self, trait_item);
190             }
191             Node::ImplItem(impl_item) => {
192                 intravisit::walk_impl_item(self, impl_item);
193             }
194             Node::ForeignItem(foreign_item) => {
195                 intravisit::walk_foreign_item(self, &foreign_item);
196             }
197             _ => {}
198         }
199         self.repr_has_repr_c = had_repr_c;
200         self.inherited_pub_visibility = had_inherited_pub_visibility;
201     }
202
203     fn mark_as_used_if_union(&mut self, adt: &ty::AdtDef, fields: &[hir::Field<'_>]) {
204         if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did.is_local() {
205             for field in fields {
206                 let index = self.tcx.field_index(field.hir_id, self.tables);
207                 self.insert_def_id(adt.non_enum_variant().fields[index].did);
208             }
209         }
210     }
211 }
212
213 impl<'a, 'tcx> Visitor<'tcx> for MarkSymbolVisitor<'a, 'tcx> {
214     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
215         NestedVisitorMap::None
216     }
217
218     fn visit_nested_body(&mut self, body: hir::BodyId) {
219         let old_tables = self.tables;
220         self.tables = self.tcx.body_tables(body);
221         let body = self.tcx.hir().body(body);
222         self.visit_body(body);
223         self.tables = old_tables;
224     }
225
226     fn visit_variant_data(
227         &mut self,
228         def: &'tcx hir::VariantData<'tcx>,
229         _: ast::Name,
230         _: &hir::Generics<'_>,
231         _: hir::HirId,
232         _: rustc_span::Span,
233     ) {
234         let has_repr_c = self.repr_has_repr_c;
235         let inherited_pub_visibility = self.inherited_pub_visibility;
236         let live_fields = def
237             .fields()
238             .iter()
239             .filter(|f| has_repr_c || inherited_pub_visibility || f.vis.node.is_pub());
240         self.live_symbols.extend(live_fields.map(|f| f.hir_id));
241
242         intravisit::walk_struct_def(self, def);
243     }
244
245     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
246         match expr.kind {
247             hir::ExprKind::Path(ref qpath @ hir::QPath::TypeRelative(..)) => {
248                 let res = self.tables.qpath_res(qpath, expr.hir_id);
249                 self.handle_res(res);
250             }
251             hir::ExprKind::MethodCall(..) => {
252                 self.lookup_and_handle_method(expr.hir_id);
253             }
254             hir::ExprKind::Field(ref lhs, ..) => {
255                 self.handle_field_access(&lhs, expr.hir_id);
256             }
257             hir::ExprKind::Struct(_, ref fields, _) => {
258                 if let ty::Adt(ref adt, _) = self.tables.expr_ty(expr).kind {
259                     self.mark_as_used_if_union(adt, fields);
260                 }
261             }
262             _ => (),
263         }
264
265         intravisit::walk_expr(self, expr);
266     }
267
268     fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
269         // Inside the body, ignore constructions of variants
270         // necessary for the pattern to match. Those construction sites
271         // can't be reached unless the variant is constructed elsewhere.
272         let len = self.ignore_variant_stack.len();
273         self.ignore_variant_stack.extend(arm.pat.necessary_variants());
274         intravisit::walk_arm(self, arm);
275         self.ignore_variant_stack.truncate(len);
276     }
277
278     fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
279         match pat.kind {
280             PatKind::Struct(ref path, ref fields, _) => {
281                 let res = self.tables.qpath_res(path, pat.hir_id);
282                 self.handle_field_pattern_match(pat, res, fields);
283             }
284             PatKind::Path(ref qpath) => {
285                 let res = self.tables.qpath_res(qpath, pat.hir_id);
286                 self.handle_res(res);
287             }
288             _ => (),
289         }
290
291         self.in_pat = true;
292         intravisit::walk_pat(self, pat);
293         self.in_pat = false;
294     }
295
296     fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
297         self.handle_res(path.res);
298         intravisit::walk_path(self, path);
299     }
300
301     fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
302         match ty.kind {
303             TyKind::Def(item_id, _) => {
304                 let item = self.tcx.hir().expect_item(item_id.id);
305                 intravisit::walk_item(self, item);
306             }
307             _ => (),
308         }
309         intravisit::walk_ty(self, ty);
310     }
311
312     fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
313         self.live_symbols.insert(c.hir_id);
314         intravisit::walk_anon_const(self, c);
315     }
316 }
317
318 fn has_allow_dead_code_or_lang_attr(
319     tcx: TyCtxt<'_>,
320     id: hir::HirId,
321     attrs: &[ast::Attribute],
322 ) -> bool {
323     if attr::contains_name(attrs, sym::lang) {
324         return true;
325     }
326
327     // Stable attribute for #[lang = "panic_impl"]
328     if attr::contains_name(attrs, sym::panic_handler) {
329         return true;
330     }
331
332     // (To be) stable attribute for #[lang = "oom"]
333     if attr::contains_name(attrs, sym::alloc_error_handler) {
334         return true;
335     }
336
337     let def_id = tcx.hir().local_def_id(id);
338     let cg_attrs = tcx.codegen_fn_attrs(def_id);
339
340     // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
341     // forcefully, e.g., for placing it in a specific section.
342     if cg_attrs.contains_extern_indicator() || cg_attrs.flags.contains(CodegenFnAttrFlags::USED) {
343         return true;
344     }
345
346     tcx.lint_level_at_node(lint::builtin::DEAD_CODE, id).0 == lint::Allow
347 }
348
349 // This visitor seeds items that
350 //   1) We want to explicitly consider as live:
351 //     * Item annotated with #[allow(dead_code)]
352 //         - This is done so that if we want to suppress warnings for a
353 //           group of dead functions, we only have to annotate the "root".
354 //           For example, if both `f` and `g` are dead and `f` calls `g`,
355 //           then annotating `f` with `#[allow(dead_code)]` will suppress
356 //           warning for both `f` and `g`.
357 //     * Item annotated with #[lang=".."]
358 //         - This is because lang items are always callable from elsewhere.
359 //   or
360 //   2) We are not sure to be live or not
361 //     * Implementation of a trait method
362 struct LifeSeeder<'k, 'tcx> {
363     worklist: Vec<hir::HirId>,
364     krate: &'k hir::Crate<'k>,
365     tcx: TyCtxt<'tcx>,
366     // see `MarkSymbolVisitor::struct_constructors`
367     struct_constructors: FxHashMap<hir::HirId, hir::HirId>,
368 }
369
370 impl<'v, 'k, 'tcx> ItemLikeVisitor<'v> for LifeSeeder<'k, 'tcx> {
371     fn visit_item(&mut self, item: &hir::Item<'_>) {
372         let allow_dead_code = has_allow_dead_code_or_lang_attr(self.tcx, item.hir_id, &item.attrs);
373         if allow_dead_code {
374             self.worklist.push(item.hir_id);
375         }
376         match item.kind {
377             hir::ItemKind::Enum(ref enum_def, _) => {
378                 if allow_dead_code {
379                     self.worklist.extend(enum_def.variants.iter().map(|variant| variant.id));
380                 }
381
382                 for variant in enum_def.variants {
383                     if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
384                         self.struct_constructors.insert(ctor_hir_id, variant.id);
385                     }
386                 }
387             }
388             hir::ItemKind::Trait(.., trait_item_refs) => {
389                 for trait_item_ref in trait_item_refs {
390                     let trait_item = self.krate.trait_item(trait_item_ref.id);
391                     match trait_item.kind {
392                         hir::TraitItemKind::Const(_, Some(_))
393                         | hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(_)) => {
394                             if has_allow_dead_code_or_lang_attr(
395                                 self.tcx,
396                                 trait_item.hir_id,
397                                 &trait_item.attrs,
398                             ) {
399                                 self.worklist.push(trait_item.hir_id);
400                             }
401                         }
402                         _ => {}
403                     }
404                 }
405             }
406             hir::ItemKind::Impl(.., ref opt_trait, _, impl_item_refs) => {
407                 for impl_item_ref in impl_item_refs {
408                     let impl_item = self.krate.impl_item(impl_item_ref.id);
409                     if opt_trait.is_some()
410                         || has_allow_dead_code_or_lang_attr(
411                             self.tcx,
412                             impl_item.hir_id,
413                             &impl_item.attrs,
414                         )
415                     {
416                         self.worklist.push(impl_item_ref.id.hir_id);
417                     }
418                 }
419             }
420             hir::ItemKind::Struct(ref variant_data, _) => {
421                 if let Some(ctor_hir_id) = variant_data.ctor_hir_id() {
422                     self.struct_constructors.insert(ctor_hir_id, item.hir_id);
423                 }
424             }
425             _ => (),
426         }
427     }
428
429     fn visit_trait_item(&mut self, _item: &hir::TraitItem<'_>) {
430         // ignore: we are handling this in `visit_item` above
431     }
432
433     fn visit_impl_item(&mut self, _item: &hir::ImplItem<'_>) {
434         // ignore: we are handling this in `visit_item` above
435     }
436 }
437
438 fn create_and_seed_worklist<'tcx>(
439     tcx: TyCtxt<'tcx>,
440     access_levels: &privacy::AccessLevels,
441     krate: &hir::Crate<'_>,
442 ) -> (Vec<hir::HirId>, FxHashMap<hir::HirId, hir::HirId>) {
443     let worklist = access_levels
444         .map
445         .iter()
446         .filter_map(
447             |(&id, level)| {
448                 if level >= &privacy::AccessLevel::Reachable { Some(id) } else { None }
449             },
450         )
451         .chain(
452             // Seed entry point
453             tcx.entry_fn(LOCAL_CRATE).map(|(def_id, _)| tcx.hir().as_local_hir_id(def_id).unwrap()),
454         )
455         .collect::<Vec<_>>();
456
457     // Seed implemented trait items
458     let mut life_seeder =
459         LifeSeeder { worklist, krate, tcx, struct_constructors: Default::default() };
460     krate.visit_all_item_likes(&mut life_seeder);
461
462     (life_seeder.worklist, life_seeder.struct_constructors)
463 }
464
465 fn find_live<'tcx>(
466     tcx: TyCtxt<'tcx>,
467     access_levels: &privacy::AccessLevels,
468     krate: &hir::Crate<'_>,
469 ) -> FxHashSet<hir::HirId> {
470     let (worklist, struct_constructors) = create_and_seed_worklist(tcx, access_levels, krate);
471     let mut symbol_visitor = MarkSymbolVisitor {
472         worklist,
473         tcx,
474         tables: &ty::TypeckTables::empty(None),
475         live_symbols: Default::default(),
476         repr_has_repr_c: false,
477         in_pat: false,
478         inherited_pub_visibility: false,
479         ignore_variant_stack: vec![],
480         struct_constructors,
481     };
482     symbol_visitor.mark_live_symbols();
483     symbol_visitor.live_symbols
484 }
485
486 struct DeadVisitor<'tcx> {
487     tcx: TyCtxt<'tcx>,
488     live_symbols: FxHashSet<hir::HirId>,
489 }
490
491 impl DeadVisitor<'tcx> {
492     fn should_warn_about_item(&mut self, item: &hir::Item<'_>) -> bool {
493         let should_warn = match item.kind {
494             hir::ItemKind::Static(..)
495             | hir::ItemKind::Const(..)
496             | hir::ItemKind::Fn(..)
497             | hir::ItemKind::TyAlias(..)
498             | hir::ItemKind::Enum(..)
499             | hir::ItemKind::Struct(..)
500             | hir::ItemKind::Union(..) => true,
501             _ => false,
502         };
503         should_warn && !self.symbol_is_live(item.hir_id)
504     }
505
506     fn should_warn_about_field(&mut self, field: &hir::StructField<'_>) -> bool {
507         let field_type = self.tcx.type_of(self.tcx.hir().local_def_id(field.hir_id));
508         !field.is_positional()
509             && !self.symbol_is_live(field.hir_id)
510             && !field_type.is_phantom_data()
511             && !has_allow_dead_code_or_lang_attr(self.tcx, field.hir_id, &field.attrs)
512     }
513
514     fn should_warn_about_variant(&mut self, variant: &hir::Variant<'_>) -> bool {
515         !self.symbol_is_live(variant.id)
516             && !has_allow_dead_code_or_lang_attr(self.tcx, variant.id, &variant.attrs)
517     }
518
519     fn should_warn_about_foreign_item(&mut self, fi: &hir::ForeignItem<'_>) -> bool {
520         !self.symbol_is_live(fi.hir_id)
521             && !has_allow_dead_code_or_lang_attr(self.tcx, fi.hir_id, &fi.attrs)
522     }
523
524     // id := HIR id of an item's definition.
525     fn symbol_is_live(&mut self, id: hir::HirId) -> bool {
526         if self.live_symbols.contains(&id) {
527             return true;
528         }
529         // If it's a type whose items are live, then it's live, too.
530         // This is done to handle the case where, for example, the static
531         // method of a private type is used, but the type itself is never
532         // called directly.
533         let def_id = self.tcx.hir().local_def_id(id);
534         let inherent_impls = self.tcx.inherent_impls(def_id);
535         for &impl_did in inherent_impls.iter() {
536             for &item_did in &self.tcx.associated_item_def_ids(impl_did)[..] {
537                 if let Some(item_hir_id) = self.tcx.hir().as_local_hir_id(item_did) {
538                     if self.live_symbols.contains(&item_hir_id) {
539                         return true;
540                     }
541                 }
542             }
543         }
544         false
545     }
546
547     fn warn_dead_code(
548         &mut self,
549         id: hir::HirId,
550         span: rustc_span::Span,
551         name: ast::Name,
552         node_type: &str,
553         participle: &str,
554     ) {
555         if !name.as_str().starts_with("_") {
556             self.tcx.lint_hir(
557                 lint::builtin::DEAD_CODE,
558                 id,
559                 span,
560                 &format!("{} is never {}: `{}`", node_type, participle, name),
561             );
562         }
563     }
564 }
565
566 impl Visitor<'tcx> for DeadVisitor<'tcx> {
567     /// Walk nested items in place so that we don't report dead-code
568     /// on inner functions when the outer function is already getting
569     /// an error. We could do this also by checking the parents, but
570     /// this is how the code is setup and it seems harmless enough.
571     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
572         NestedVisitorMap::All(&self.tcx.hir())
573     }
574
575     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
576         if self.should_warn_about_item(item) {
577             // For most items, we want to highlight its identifier
578             let span = match item.kind {
579                 hir::ItemKind::Fn(..)
580                 | hir::ItemKind::Mod(..)
581                 | hir::ItemKind::Enum(..)
582                 | hir::ItemKind::Struct(..)
583                 | hir::ItemKind::Union(..)
584                 | hir::ItemKind::Trait(..)
585                 | hir::ItemKind::Impl(..) => {
586                     // FIXME(66095): Because item.span is annotated with things
587                     // like expansion data, and ident.span isn't, we use the
588                     // def_span method if it's part of a macro invocation
589                     // (and thus has asource_callee set).
590                     // We should probably annotate ident.span with the macro
591                     // context, but that's a larger change.
592                     if item.span.source_callee().is_some() {
593                         self.tcx.sess.source_map().def_span(item.span)
594                     } else {
595                         item.ident.span
596                     }
597                 }
598                 _ => item.span,
599             };
600             let participle = match item.kind {
601                 hir::ItemKind::Struct(..) => "constructed", // Issue #52325
602                 _ => "used",
603             };
604             self.warn_dead_code(
605                 item.hir_id,
606                 span,
607                 item.ident.name,
608                 item.kind.descriptive_variant(),
609                 participle,
610             );
611         } else {
612             // Only continue if we didn't warn
613             intravisit::walk_item(self, item);
614         }
615     }
616
617     fn visit_variant(
618         &mut self,
619         variant: &'tcx hir::Variant<'tcx>,
620         g: &'tcx hir::Generics<'tcx>,
621         id: hir::HirId,
622     ) {
623         if self.should_warn_about_variant(&variant) {
624             self.warn_dead_code(
625                 variant.id,
626                 variant.span,
627                 variant.ident.name,
628                 "variant",
629                 "constructed",
630             );
631         } else {
632             intravisit::walk_variant(self, variant, g, id);
633         }
634     }
635
636     fn visit_foreign_item(&mut self, fi: &'tcx hir::ForeignItem<'tcx>) {
637         if self.should_warn_about_foreign_item(fi) {
638             self.warn_dead_code(
639                 fi.hir_id,
640                 fi.span,
641                 fi.ident.name,
642                 fi.kind.descriptive_variant(),
643                 "used",
644             );
645         }
646         intravisit::walk_foreign_item(self, fi);
647     }
648
649     fn visit_struct_field(&mut self, field: &'tcx hir::StructField<'tcx>) {
650         if self.should_warn_about_field(&field) {
651             self.warn_dead_code(field.hir_id, field.span, field.ident.name, "field", "read");
652         }
653         intravisit::walk_struct_field(self, field);
654     }
655
656     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
657         match impl_item.kind {
658             hir::ImplItemKind::Const(_, body_id) => {
659                 if !self.symbol_is_live(impl_item.hir_id) {
660                     self.warn_dead_code(
661                         impl_item.hir_id,
662                         impl_item.span,
663                         impl_item.ident.name,
664                         "associated const",
665                         "used",
666                     );
667                 }
668                 self.visit_nested_body(body_id)
669             }
670             hir::ImplItemKind::Method(_, body_id) => {
671                 if !self.symbol_is_live(impl_item.hir_id) {
672                     let span = self.tcx.sess.source_map().def_span(impl_item.span);
673                     self.warn_dead_code(
674                         impl_item.hir_id,
675                         span,
676                         impl_item.ident.name,
677                         "method",
678                         "used",
679                     );
680                 }
681                 self.visit_nested_body(body_id)
682             }
683             hir::ImplItemKind::OpaqueTy(..) | hir::ImplItemKind::TyAlias(..) => {}
684         }
685     }
686
687     // Overwrite so that we don't warn the trait item itself.
688     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
689         match trait_item.kind {
690             hir::TraitItemKind::Const(_, Some(body_id))
691             | hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(body_id)) => {
692                 self.visit_nested_body(body_id)
693             }
694             hir::TraitItemKind::Const(_, None)
695             | hir::TraitItemKind::Method(_, hir::TraitMethod::Required(_))
696             | hir::TraitItemKind::Type(..) => {}
697         }
698     }
699 }
700
701 pub fn check_crate(tcx: TyCtxt<'_>) {
702     let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
703     let krate = tcx.hir().krate();
704     let live_symbols = find_live(tcx, access_levels, krate);
705     let mut visitor = DeadVisitor { tcx, live_symbols };
706     intravisit::walk_crate(&mut visitor, krate);
707 }